Langertha/Raider.pm

filter: Statementstmt 39.3% 263 / 669 Branchbran 31.3% 84 / 268 Conditioncond 19.1% 22 / 115 MC/DCmcdc 7.2% 5 / 69 Subroutinesub 63.7% 37 / 58 Podpod 90.4% 19 / 21 totaltotal 35.8% 430 / 1200 CC 205 SCAR 65.0
CC
205
Cov
35%
_run_raid_loop
2970.0
raid_f
380.0
_gather_tools_f
156.0
CRAP 665.5
↑ Summary Langertha/Role/Chat.pm »
1 package Langertha::Raider;
2 # ABSTRACT: Autonomous agent with conversation history and MCP tools
3 7 our $VERSION = '0.502';
4 7 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use Time::HiRes qw( gettimeofday tv_interval );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Langertha::Raider::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use Langertha::RunContext;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 7 with 'Langertha::Role::PluginHost', 'Langertha::Role::Runnable';
14  
15  
16 7 has engine => (
17 is => 'ro',
18 required => 1,
19 );
20  
21  
22 7 has mission => (
23 is => 'ro',
24 isa => 'Str',
25 predicate => 'has_mission',
26 );
27  
28  
29 has history => (
30 is => 'rw',
31 isa => 'ArrayRef',
32 63 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
33 7 );
34  
35  
36 7 has max_iterations => (
37 is => 'ro',
38 isa => 'Int',
39 default => 10,
40 );
41  
42  
43 7 has max_context_tokens => (
44 is => 'ro',
45 isa => 'Int',
46 predicate => 'has_max_context_tokens',
47 );
48  
49  
50 7 has context_compress_threshold => (
51 is => 'ro',
52 isa => 'Num',
53 default => 0.75,
54 );
55  
56  
57 has compression_prompt => (
58 is => 'ro',
59 isa => 'Str',
60 lazy => 1,
61 default => sub {
62 0 ▶ 'You are a conversation summarizer. Summarize the following conversation '
Subroutine __ANON__: not called CC=1 SCAR=6.9
63 . 'between a user and an AI assistant. Preserve all key facts, decisions, '
64 . 'action items, file names, code references, and important context. '
65 . 'Be concise but complete. The summary will replace the conversation '
66 . 'history, so the assistant must be able to continue naturally.'
67 },
68 7 );
69  
70  
71 7 has compression_engine => (
72 is => 'ro',
73 predicate => 'has_compression_engine',
74 );
75  
76  
77 has session_history => (
78 is => 'ro',
79 isa => 'ArrayRef',
80 63 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
81 7 );
82  
83  
84 7 has _last_prompt_tokens => (
85 is => 'rw',
86 isa => 'Int',
87 predicate => 'has_last_prompt_tokens',
88 );
89  
90 has _injections => (
91 is => 'ro',
92 isa => 'ArrayRef',
93 63 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
94 7 );
95  
96 7 has on_iteration => (
97 is => 'rw',
98 isa => 'CodeRef',
99 predicate => 'has_on_iteration',
100 );
101  
102  
103 has metrics => (
104 is => 'rw',
105 isa => 'HashRef',
106 default => sub { {
107 63 ▶ raids => 0, iterations => 0, tool_calls => 0, time_ms => 0,
Subroutine __ANON__: called CC=1 SCAR=0.0
108 } },
109 7 );
110  
111  
112 7 has langfuse_trace_name => (
113 is => 'ro',
114 isa => 'Str',
115 default => 'raid',
116 );
117  
118  
119 7 has langfuse_user_id => (
120 is => 'ro',
121 isa => 'Str',
122 predicate => 'has_langfuse_user_id',
123 );
124  
125  
126 7 has langfuse_session_id => (
127 is => 'ro',
128 isa => 'Str',
129 predicate => 'has_langfuse_session_id',
130 );
131  
132  
133 7 has langfuse_tags => (
134 is => 'ro',
135 isa => 'ArrayRef[Str]',
136 predicate => 'has_langfuse_tags',
137 );
138  
139  
140 7 has langfuse_release => (
141 is => 'ro',
142 isa => 'Str',
143 predicate => 'has_langfuse_release',
144 );
145  
146  
147 7 has langfuse_version => (
148 is => 'ro',
149 isa => 'Str',
150 predicate => 'has_langfuse_version',
151 );
152  
153  
154 7 has langfuse_metadata => (
155 is => 'ro',
156 isa => 'HashRef',
157 predicate => 'has_langfuse_metadata',
158 );
159  
160  
161 7 has raider_mcp => (
162 is => 'ro',
163 predicate => 'has_raider_mcp',
164 );
165  
166  
167 7 has on_ask_user => (
168 is => 'rw',
169 isa => 'CodeRef',
170 predicate => 'has_on_ask_user',
171 );
172  
173  
174 7 has on_pause => (
175 is => 'rw',
176 isa => 'CodeRef',
177 predicate => 'has_on_pause',
178 );
179  
180  
181 7 has on_wait_for => (
182 is => 'rw',
183 isa => 'CodeRef',
184 predicate => 'has_on_wait_for',
185 );
186  
187  
188 7 has _continuation => (
189 is => 'rw',
190 predicate => 'has_continuation',
191 clearer => 'clear_continuation',
192 );
193  
194 has tools => (
195 is => 'ro',
196 isa => 'ArrayRef[HashRef]',
197 62 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
198 7 );
199  
200  
201 has mcp_catalog => (
202 is => 'ro',
203 isa => 'HashRef',
204 62 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
205 7 );
206  
207  
208 has engine_catalog => (
209 is => 'ro',
210 isa => 'HashRef',
211 61 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
212 7 );
213  
214  
215 7 has _active_engine => (
216 is => 'rw',
217 predicate => '_has_active_engine',
218 clearer => '_clear_active_engine',
219 );
220  
221 7 has _active_engine_name => (
222 is => 'rw',
223 isa => 'Maybe[Str]',
224 default => undef,
225 );
226  
227 has _active_catalog_mcps => (
228 is => 'ro',
229 isa => 'HashRef',
230 63 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
231 7 );
232  
233 7 has _tools_dirty => (
234 is => 'rw',
235 isa => 'Bool',
236 default => 0,
237 );
238  
239 7 has _inline_mcp => (
240 is => 'rw',
241 predicate => 'has_inline_mcp',
242 );
243  
244 7 has embedding_engine => (
245 is => 'ro',
246 predicate => 'has_embedding_engine',
247 );
248  
249  
250 has no_session_embeddings => (
251 is => 'ro',
252 63 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
253 7 );
254  
255  
256 has _session_embeddings => (
257 is => 'ro',
258 isa => 'ArrayRef',
259 63 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
260 7 );
261  
262 sub BUILD {
263 63 ▶ my ( $self ) = @_;
Subroutine BUILD: called CC=3 SCAR=11.0
Pod undocumented
264  
265 # Auto-activate catalog MCPs with auto => 1
266 63 for my $name (keys %{$self->mcp_catalog}) {
267 2 my $entry = $self->mcp_catalog->{$name};
268 2 ▶ if ($entry->{auto}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$entry{"auto"}) 1 1 2
269 1 $self->_active_catalog_mcps->{$name} = $entry->{server};
270 }
271 }
272 }
273  
274 sub clear_history {
275 1 ▶ my ( $self ) = @_;
Subroutine clear_history: called CC=1 SCAR=0.0
Pod documented
276 1 $self->history([]);
277 1 splice @{$self->_injections};
278 1 return $self;
279 }
280  
281  
282 sub add_history {
283 0 ▶ my ( $self, $role, $content ) = @_;
Subroutine add_history: not called CC=1 SCAR=6.9
Pod documented
284 0 push @{$self->history}, { role => $role, content => $content };
285 0 return $self;
286 }
287  
288  
289 sub inject {
290 0 ▶ my ( $self, @messages ) = @_;
Subroutine inject: not called CC=1 SCAR=6.9
Pod documented
291 0 push @{$self->_injections}, @messages;
292 0 return $self;
293 }
294  
295  
296 sub reset {
297 1 ▶ my ( $self ) = @_;
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
298 1 $self->clear_history;
299 1 $self->_clear_active_engine;
300 1 $self->_active_engine_name(undef);
301 1 $self->metrics({
302 raids => 0, iterations => 0, tool_calls => 0, time_ms => 0,
303 });
304 1 return $self;
305 }
306  
307  
308 sub active_engine {
309 18 ▶ my ($self) = @_;
Subroutine active_engine: called CC=2 SCAR=6.9
Pod documented
310 18 ▶ return $self->_has_active_engine ? $self->_active_engine : $self->engine;
Branch: 1 branch
BranchTrueFalseTotal
$self->_has_active_engine ? : 8 10 18
311 }
312  
313  
314 sub active_engine_name {
315 11 ▶ my ($self) = @_;
Subroutine active_engine_name: called CC=1 SCAR=0.0
Pod documented
316 11 return $self->_active_engine_name;
317 }
318  
319  
320 sub switch_engine {
321 10 ▶ my ($self, $name) = @_;
Subroutine switch_engine: called CC=3 SCAR=11.0
Pod documented
322 croak "Engine '$name' not found in engine_catalog"
323 10 ▶ unless exists $self->engine_catalog->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->engine_catalog->{$name} 1 9 10
324 9 my $entry = $self->engine_catalog->{$name};
325 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
326 9 $self->_active_engine($engine);
327 9 $self->_active_engine_name($name);
328 9 $self->_tools_dirty(1);
329 9 return $engine;
330 }
331  
332  
333 sub reset_engine {
334 7 ▶ my ($self) = @_;
Subroutine reset_engine: called CC=1 SCAR=0.0
Pod documented
335 7 $self->_clear_active_engine;
336 7 $self->_active_engine_name(undef);
337 7 $self->_tools_dirty(1);
338 7 return $self->engine;
339 }
340  
341  
342 sub engine_info {
343 7 ▶ my ($self) = @_;
Subroutine engine_info: called CC=3 SCAR=11.1
Pod documented
344 7 my $engine = $self->active_engine;
345 return {
346 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
347 class => ref $engine,
348 model => $engine->can('chat_model') ? $engine->chat_model : undef,
349 };
350 }
351  
352  
353 sub list_engines {
354 2 ▶ my ($self) = @_;
Subroutine list_engines: called CC=4 SCAR=14.0
Pod documented
355 2 my %list;
356 $list{default} = {
357 2 engine => $self->engine,
358 active => !$self->_has_active_engine,
359 };
360 2 for my $name (keys %{$self->engine_catalog}) {
361 6 my $entry = $self->engine_catalog->{$name};
362 $list{$name} = {
363 engine => $entry->{engine} // $self->engine,
364 description => $entry->{description},
365 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
366 };
367 }
368 2 return \%list;
369 }
370  
371  
372 sub add_engine {
373 2 ▶ my ( $self, $name, %opts ) = @_;
Subroutine add_engine: called CC=1 SCAR=0.0
Pod documented
374 2 $self->engine_catalog->{$name} = \%opts;
375 2 $self->_tools_dirty(1);
376 2 return;
377 }
378  
379  
380 sub remove_engine {
381 3 ▶ my ( $self, $name ) = @_;
Subroutine remove_engine: called CC=4 SCAR=13.9
Pod documented
382 croak "Engine '$name' not found in engine_catalog"
383 3 ▶ unless exists $self->engine_catalog->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->engine_catalog->{$name} 1 2 3
384 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
385 1 $self->reset_engine;
386 }
387 2 delete $self->engine_catalog->{$name};
388 2 $self->_tools_dirty(1);
389 2 return;
390 }
391  
392  
393 sub _extract_prompt_tokens {
394 0 ▶ my ( $self, $data ) = @_;
Subroutine _extract_prompt_tokens: not called CC=4 SCAR=30.0
395 # OpenAI-compatible (OpenAI, Groq, Mistral, DeepSeek, MiniMax, vLLM, Ollama, AKI)
396 0 ▶ if (my $u = $data->{usage}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $u = $$data{"usage"}) 0 0 0
397 0 ▶ return $u->{prompt_tokens} // $u->{input_tokens};
Condition0%0/3
$$u{"prompt_tokens"} // $$u{"input_tokens"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$u{"prompt_tokens"} // $$u{"input_tokens"}
$$u{"prompt_tokens"} $$u{"input_tokens"}
Truth table0%0/3
A // B
A= $$u{"prompt_tokens"}B= $$u{"input_tokens"}
ABresult
1X1
011
000
398 }
399 # Gemini
400 0 ▶ if (my $m = $data->{usageMetadata}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $m = $$data{"usageMetadata"}) 0 0 0
401 0 return $m->{promptTokenCount};
402 }
403 0 return undef;
404 }
405  
406 0 ▶async sub compress_history_f {
Subroutine compress_history_f: not called CC=3 SCAR=24.8
Pod documented
407 0 my ( $self ) = @_;
408 0 my @history = @{$self->history};
409 0 ▶ return unless @history;
Branch: 1 branch
BranchTrueFalseTotal
unless @history 0 0 0
410  
411 0 ▶ my $engine = $self->has_compression_engine
Branch: 1 branch
BranchTrueFalseTotal
$self->has_compression_engine ? : 0 0 0
412 ? $self->compression_engine : $self->engine;
413  
414 0 my @messages = (
415 { role => 'system', content => $self->compression_prompt },
416 @history,
417 { role => 'user', content => 'Provide a concise summary.' },
418 );
419  
420 0 my $request = $engine->chat_request(\@messages);
421 0 my $response = await $engine->_async_http->do_request(request => $request);
422 0 my $data = $engine->parse_response($response);
423 0 my $summary = $engine->response_text_content($data);
424  
425 # Replace working history with summary
426 0 $self->history([
427 { role => 'assistant', content => $summary },
428 ]);
429  
430 # Mark compression event in session_history
431 0 push @{$self->session_history}, {
432 role => 'system',
433 content => '[Context compressed — history summarized]',
434 };
435  
436 0 return $summary;
437 7 }
438  
439  
440 sub compress_history {
441 0 ▶ my ( $self ) = @_;
Subroutine compress_history: not called CC=1 SCAR=6.9
Pod documented
442 0 return $self->compress_history_f->get;
443 }
444  
445  
446 sub register_session_history_tool {
447 0 ▶ my ( $self, $server ) = @_;
Subroutine register_session_history_tool: not called CC=1 SCAR=6.9
Pod documented
448 $server->tool(
449 name => 'session_history',
450 description => 'Retrieve the full session history including tool calls.',
451 input_schema => {
452 type => 'object',
453 properties => {
454 query => { type => 'string', description => 'Filter messages containing this text' },
455 last_n => { type => 'integer', description => 'Return only the last N messages' },
456 },
457 },
458 code => sub {
459 0 ▶ my ( $tool, $args ) = @_;
Subroutine __ANON__: not called CC=6 SCAR=37.4
460 0 my @hist = @{$self->session_history};
461 0 ▶ if (my $q = $args->{query}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $q = $$args{"query"}) 0 0 0
462 0 ▶ @hist = grep { ($_->{content} // '') =~ /\Q$q/i } @hist;
Condition0%0/2
$$_{"content"} // ""
l!l
00
MC/DC0%0/1
$$_{"content"} // ""
$$_{"content"}
Truth table0%0/2
A
A= $$_{"content"}
Aresult
11
00
463 }
464 0 ▶ if (my $n = $args->{last_n}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $$args{"last_n"}) 0 0 0
465 0 ▶ @hist = @hist[-$n..-1] if @hist > $n;
Branch: 1 branch
BranchTrueFalseTotal
if @hist > $n 0 0 0
466 }
467 my $text = join("\n\n", map {
468 0 "[$_->{role}] $_->{content}"
469 } @hist);
470 0 ▶ $tool->text_result($text || 'No messages in session history.');
Condition0%0/2
$text || 'No messages in session history.'
l!l
00
MC/DC0%0/1
$text || 'No messages in session history.'
$text
Truth table0%0/2
A
A= $text
Aresult
11
00
471 },
472 0 );
473 }
474  
475  
476 sub _langfuse_model_parameters {
477 0 ▶ my ( $self, $engine ) = @_;
Subroutine _langfuse_model_parameters: not called CC=7 SCAR=40.3
478 0 ▶ my $e = $engine // $self->active_engine;
Condition0%0/3
$engine // $self->active_engine
l!l&&r!l&&!r
000
MC/DC0%0/2
$engine // $self->active_engine
$engine $self->active_engine
Truth table0%0/3
A // B
A= $engineB= $self->active_engine
ABresult
1X1
011
000
479 0 my %p;
480 0 ▶ $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 0 0 0
Condition0%0/3
$e->can("has_temperature") and $e->has_temperature
!ll&&!rl&&r
000
MC/DC0%0/2
$e->can("has_temperature") and $e->has_temperature
$e->can("has_temperature") $e->has_temperature
Truth table0%0/3
A and B
A= $e->can("has_temperature")B= $e->has_temperature
ABresult
0X0
100
111
481 0 ▶ $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 0 0
Condition0%0/3
$e->can("get_response_size") and $e->get_response_size
!ll&&!rl&&r
000
MC/DC0%0/2
$e->can("get_response_size") and $e->get_response_size
$e->can("get_response_size") $e->get_response_size
Truth table0%0/3
A and B
A= $e->can("get_response_size")B= $e->get_response_size
ABresult
0X0
100
111
482 0 ▶ return keys %p ? \%p : undef;
Branch: 1 branch
BranchTrueFalseTotal
keys %p ? : 0 0 0
483 }
484  
485 sub _langfuse_usage {
486 0 ▶ my ( $self, $data ) = @_;
Subroutine _langfuse_usage: not called CC=8 SCAR=42.8
487 # OpenAI-compatible + Anthropic (both use $data->{usage})
488 0 ▶ if (my $u = $data->{usage}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $u = $$data{"usage"}) 0 0 0
489 0 ▶ my $input = $u->{prompt_tokens} // $u->{input_tokens};
Condition0%0/3
$$u{"prompt_tokens"} // $$u{"input_tokens"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$u{"prompt_tokens"} // $$u{"input_tokens"}
$$u{"prompt_tokens"} $$u{"input_tokens"}
Truth table0%0/3
A // B
A= $$u{"prompt_tokens"}B= $$u{"input_tokens"}
ABresult
1X1
011
000
490 0 ▶ my $output = $u->{completion_tokens} // $u->{output_tokens};
Condition0%0/3
$$u{"completion_tokens"} // $$u{"output_tokens"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$u{"completion_tokens"} // $$u{"output_tokens"}
$$u{"completion_tokens"} $$u{"output_tokens"}
Truth table0%0/3
A // B
A= $$u{"completion_tokens"}B= $$u{"output_tokens"}
ABresult
1X1
011
000
491 return {
492 input => $input,
493 output => $output,
494 0 ▶ total => $u->{total_tokens} // (($input // 0) + ($output // 0)),
Condition0%0/7
$$u{"total_tokens"} // ($input // 0) + ($output // 0)
l!l&&r!l&&!r
000
$input // 0
l!l
00
$output // 0
l!l
00
MC/DC0%0/2
$$u{"total_tokens"} // ($input // 0) + ($output // 0)
$$u{"total_tokens"} $input
MC/DC0%0/1
$output // 0
$output
Truth table0%0/3
A // B
A= $$u{"total_tokens"}B= $input
ABresult
1X1
011
000
Truth table0%0/2
A
A= $output
Aresult
11
00
495 };
496 }
497 # Gemini
498 0 ▶ if (my $m = $data->{usageMetadata}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $m = $$data{"usageMetadata"}) 0 0 0
499 return {
500 input => $m->{promptTokenCount},
501 output => $m->{candidatesTokenCount},
502 total => $m->{totalTokenCount},
503 0 };
504 }
505 0 return undef;
506 }
507  
508 sub _self_tool_enabled {
509 56 ▶ my ( $self, $tool_name ) = @_;
Subroutine _self_tool_enabled: called CC=5 SCAR=16.2
510 56 ▶ return 0 unless $self->has_raider_mcp;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_raider_mcp 8 48 56
511 48 my $cfg = $self->raider_mcp;
512 48 ▶ return 1 if !ref $cfg; # truthy scalar = all tools
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cfg 32 16 48
513 16 ▶ return $cfg->{$tool_name} ? 1 : 0 if ref $cfg eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
if ref $cfg eq "HASH" 16 0 16
$$cfg{$tool_name} ? : 3 13 16
514 0 return 0;
515 }
516  
517 sub _self_tool_definitions {
518 7 ▶ my ( $self ) = @_;
Subroutine _self_tool_definitions: called CC=10 SCAR=23.0
519 7 my @tools;
520  
521 7 ▶ if ($self->_self_tool_enabled('ask_user')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("ask_user")) 6 1 7
522 6 push @tools, {
523 name => 'raider_ask_user',
524 description => 'Ask the user a question and wait for their answer. Use this when you need clarification or a decision from the user.',
525 inputSchema => {
526 type => 'object',
527 properties => {
528 question => { type => 'string', description => 'The question to ask the user' },
529 options => { type => 'array', items => { type => 'string' }, description => 'Optional list of choices for the user' },
530 },
531 required => ['question'],
532 },
533 };
534 }
535  
536 7 ▶ if ($self->_self_tool_enabled('wait')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("wait")) 4 3 7
537 4 push @tools, {
538 name => 'raider_wait',
539 description => 'Wait for a specified number of seconds before continuing.',
540 inputSchema => {
541 type => 'object',
542 properties => {
543 seconds => { type => 'number', description => 'Number of seconds to wait' },
544 reason => { type => 'string', description => 'Why you are waiting' },
545 },
546 required => ['seconds'],
547 },
548 };
549 }
550  
551 7 ▶ if ($self->_self_tool_enabled('wait_for')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("wait_for")) 4 3 7
552 4 push @tools, {
553 name => 'raider_wait_for',
554 description => 'Wait for an external condition to be met. The condition is evaluated by the host application.',
555 inputSchema => {
556 type => 'object',
557 properties => {
558 condition => { type => 'string', description => 'Description of the condition to wait for' },
559 args => { type => 'object', description => 'Additional arguments for the condition check' },
560 timeout => { type => 'number', description => 'Timeout in seconds' },
561 },
562 required => ['condition'],
563 },
564 };
565 }
566  
567 7 ▶ if ($self->_self_tool_enabled('pause')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("pause")) 4 3 7
568 4 push @tools, {
569 name => 'raider_pause',
570 description => 'Pause execution and return control to the user. The user can resume later with respond_f.',
571 inputSchema => {
572 type => 'object',
573 properties => {
574 reason => { type => 'string', description => 'Why you are pausing' },
575 },
576 },
577 };
578 }
579  
580 7 ▶ if ($self->_self_tool_enabled('abort')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("abort")) 5 2 7
581 5 push @tools, {
582 name => 'raider_abort',
583 description => 'Abort the current raid. Use only when the task cannot be completed.',
584 inputSchema => {
585 type => 'object',
586 properties => {
587 reason => { type => 'string', description => 'Why you are aborting' },
588 },
589 },
590 };
591 }
592  
593 7 ▶ if ($self->_self_tool_enabled('session_history')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("session_history")) 4 3 7
594 4 push @tools, {
595 name => 'raider_session_history',
596 description => 'Search or retrieve the full session history including tool calls and results.',
597 inputSchema => {
598 type => 'object',
599 properties => {
600 query => { type => 'string', description => 'Filter messages containing this text' },
601 last_n => { type => 'integer', description => 'Return only the last N messages' },
602 search => { type => 'string', description => 'Semantic search query (requires embedding engine)' },
603 },
604 },
605 };
606 }
607  
608 7 ▶ if ($self->_self_tool_enabled('manage_mcps')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_self_tool_enabled("manage_mcps")) 4 3 7
609 4 push @tools, {
610 name => 'raider_manage_mcps',
611 description => 'List, activate, or deactivate MCP tool servers from the catalog.',
612 inputSchema => {
613 type => 'object',
614 properties => {
615 action => { type => 'string', enum => ['list', 'activate', 'deactivate'], description => 'Action to perform' },
616 name => { type => 'string', description => 'Name of the MCP server (for activate/deactivate)' },
617 },
618 required => ['action'],
619 },
620 };
621 }
622  
623 7 ▶ 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;}) 2 5 7
Condition100%3/3
$self->_self_tool_enabled("switch_engine") and keys %{$self->engine_catalog;}
!ll&&!rl&&r
322
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
624 2 my @names = ('default', sort keys %{$self->engine_catalog});
625 2 push @tools, {
626 name => 'raider_switch_engine',
627 description => 'Switch to a different AI engine from the catalog. Use "default" to reset to the original engine.',
628 inputSchema => {
629 type => 'object',
630 properties => {
631 name => {
632 type => 'string',
633 enum => \@names,
634 description => 'Name of the engine to switch to',
635 },
636 },
637 required => ['name'],
638 },
639 };
640 }
641  
642 7 return \@tools;
643 }
644  
645 sub _execute_self_tool {
646 15 ▶ my ( $self, $name, $input ) = @_;
Subroutine _execute_self_tool: called CC=15 SCAR=27.6
647 15 my $short = $name;
648 15 $short =~ s/^raider_//;
649  
650 15 ▶ if ($short eq 'ask_user') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "ask_user") 2 13 15
651 2 my $question = $input->{question};
652 2 my $options = $input->{options};
653 2 ▶ if ($self->has_on_ask_user) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_ask_user) 1 1 2
654 1 my $answer = $self->on_ask_user->($question, $options);
655 1 return { type => 'result', content => [{ type => 'text', text => "$answer" }] };
656 }
657 1 return { type => 'question', question => $question, options => $options };
658 }
659  
660 13 ▶ if ($short eq 'wait') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "wait") 1 12 13
661 1 ▶ my $seconds = $input->{seconds} // 1;
Condition50%1/2
$$input{"seconds"} // 1
l!l
10
MC/DC0%0/1
$$input{"seconds"} // 1
$$input{"seconds"}
Truth table50%1/2
A
A= $$input{"seconds"}
Aresult
11
00
662 1 return { type => 'wait', seconds => $seconds, reason => $input->{reason} };
663 }
664  
665 12 ▶ if ($short eq 'wait_for') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "wait_for") 2 10 12
666 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
667 1 my $result = $self->on_wait_for->($input->{condition}, $input->{args});
668 1 return { type => 'result', content => [{ type => 'text', text => "$result" }] };
669 }
670  
671 10 ▶ if ($short eq 'pause') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "pause") 2 8 10
672 2 ▶ my $reason = $input->{reason} // '';
Condition50%1/2
$$input{"reason"} // ""
l!l
20
MC/DC0%0/1
$$input{"reason"} // ""
$$input{"reason"}
Truth table50%1/2
A
A= $$input{"reason"}
Aresult
11
00
673 2 ▶ if ($self->has_on_pause) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_pause) 1 1 2
674 1 $self->on_pause->($reason);
675 1 return { type => 'result', content => [{ type => 'text', text => "Resumed after pause." }] };
676 }
677 1 return { type => 'pause', reason => $reason };
678 }
679  
680 8 ▶ if ($short eq 'abort') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "abort") 1 7 8
681 1 ▶ return { type => 'abort', reason => $input->{reason} // 'Agent aborted' };
Condition50%1/2
$$input{"reason"} // "Agent aborted"
l!l
10
MC/DC0%0/1
$$input{"reason"} // "Agent aborted"
$$input{"reason"}
Truth table50%1/2
A
A= $$input{"reason"}
Aresult
11
00
682 }
683  
684 7 ▶ if ($short eq 'session_history') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "session_history") 3 4 7
685 3 return { type => 'result', content => [{ type => 'text', text => $self->_query_session_history($input) }] };
686 }
687  
688 4 ▶ if ($short eq 'manage_mcps') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "manage_mcps") 4 0 4
689 4 return { type => 'result', content => [{ type => 'text', text => $self->_manage_mcps($input) }] };
690 }
691  
692 0 ▶ if ($short eq 'switch_engine') {
Branch: 1 branch
BranchTrueFalseTotal
if ($short eq "switch_engine") 0 0 0
693 0 return { type => 'result', content => [{ type => 'text', text => $self->_switch_engine_tool($input) }] };
694 }
695  
696 0 die "Unknown self-tool: $name";
697 }
698  
699 sub _query_session_history {
700 3 ▶ my ( $self, $args ) = @_;
Subroutine _query_session_history: called CC=12 SCAR=37.0
701 3 my @hist = @{$self->session_history};
702  
703 # Semantic search via embeddings
704 3 ▶ if (my $search = $args->{search}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $search = $$args{"search"}) 0 3 3
705 0 my $engine = $self->_get_embedding_engine;
706 0 ▶ if ($engine) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine) { } 0 0 0
707 0 my $query_vec = $engine->simple_embedding($search);
708 0 my @scored;
709 0 for my $i (0..$#hist) {
710 0 my $emb = $self->_session_embeddings->[$i];
711 0 ▶ next unless $emb;
Branch: 1 branch
BranchTrueFalseTotal
unless $emb 0 0 0
712 0 my $sim = _cosine_similarity($query_vec, $emb);
713 0 push @scored, { idx => $i, score => $sim };
714 }
715 0 @scored = sort { $b->{score} <=> $a->{score} } @scored;
716 0 ▶ @scored = @scored[0..9] if @scored > 10;
Branch: 1 branch
BranchTrueFalseTotal
if @scored > 10 0 0 0
717 0 @hist = map { $hist[$_->{idx}] } @scored;
718 } else {
719 # Fallback to text grep
720 0 ▶ @hist = grep { ($_->{content} // '') =~ /\Q$search/i } @hist;
Condition0%0/2
$$_{"content"} // ""
l!l
00
MC/DC0%0/1
$$_{"content"} // ""
$$_{"content"}
Truth table0%0/2
A
A= $$_{"content"}
Aresult
11
00
721 }
722 }
723  
724 3 ▶ if (my $q = $args->{query}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $q = $$args{"query"}) 1 2 3
725 1 ▶ @hist = grep { ($_->{content} // '') =~ /\Q$q/i } @hist;
Condition50%1/2
$$_{"content"} // ""
l!l
50
MC/DC0%0/1
$$_{"content"} // ""
$$_{"content"}
Truth table50%1/2
A
A= $$_{"content"}
Aresult
11
00
726 }
727 3 ▶ if (my $n = $args->{last_n}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $n = $$args{"last_n"}) 1 2 3
728 1 ▶ @hist = @hist[-$n..-1] if @hist > $n;
Branch: 1 branch
BranchTrueFalseTotal
if @hist > $n 1 0 1
729 }
730  
731 my $text = join("\n\n", map {
732 3 "[$_->{role}] $_->{content}"
733 } @hist);
734 3 ▶ return $text || 'No messages in session history.';
Condition50%1/2
$text || 'No messages in session history.'
l!l
30
MC/DC0%0/1
$text || 'No messages in session history.'
$text
Truth table50%1/2
A
A= $text
Aresult
11
00
735 }
736  
737 sub _manage_mcps {
738 4 ▶ my ( $self, $args ) = @_;
Subroutine _manage_mcps: called CC=11 SCAR=24.3
739 4 my $action = $args->{action};
740  
741 4 ▶ if ($action eq 'list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "list") 1 3 4
742 1 my @lines;
743 1 for my $name (sort keys %{$self->mcp_catalog}) {
744 2 my $entry = $self->mcp_catalog->{$name};
745 2 ▶ my $active = exists $self->_active_catalog_mcps->{$name} ? 'ACTIVE' : 'inactive';
Branch: 1 branch
BranchTrueFalseTotal
exists $self->_active_catalog_mcps->{$name} ? : 1 1 2
746 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
747 2 push @lines, "- $name [$active] $desc";
748 }
749 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
750 }
751  
752 3 ▶ if ($action eq 'activate') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "activate") 2 1 3
753 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" 0 2 2
754 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
755 or return "Error: '$name' not found in catalog";
756 1 $self->_active_catalog_mcps->{$name} = $entry->{server};
757 1 $self->_tools_dirty(1);
758 1 return "Activated MCP server '$name'.";
759 }
760  
761 1 ▶ if ($action eq 'deactivate') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq "deactivate") 1 0 1
762 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" 0 1 1
763 1 delete $self->_active_catalog_mcps->{$name};
764 1 $self->_tools_dirty(1);
765 1 return "Deactivated MCP server '$name'.";
766 }
767  
768 0 return "Error: unknown action '$action'";
769 }
770  
771 sub _switch_engine_tool {
772 4 ▶ my ( $self, $args ) = @_;
Subroutine _switch_engine_tool: called CC=4 SCAR=13.9
773 4 ▶ my $name = $args->{name} or return "Error: name required";
Branch: 1 branch
BranchTrueFalseTotal
my $name = $$args{"name"} or return "Error: name required" 1 3 4
774  
775 3 ▶ if ($name eq 'default') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "default") 1 2 3
776 1 $self->reset_engine;
777 1 my $info = $self->engine_info;
778 1 return "Switched to default engine ($info->{class}, model: $info->{model}).";
779 }
780  
781 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
782 or return "Error: '$name' not found in engine catalog";
783 1 $self->switch_engine($name);
784 1 my $info = $self->engine_info;
785 1 return "Switched to engine '$name' ($info->{class}, model: $info->{model}).";
786 }
787  
788 sub _get_embedding_engine {
789 0 ▶ my ( $self ) = @_;
Subroutine _get_embedding_engine: not called CC=4 SCAR=30.0
790 0 ▶ return undef if $self->no_session_embeddings;
Branch: 1 branch
BranchTrueFalseTotal
if $self->no_session_embeddings 0 0 0
791 0 ▶ return $self->embedding_engine if $self->has_embedding_engine;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_embedding_engine 0 0 0
792 0 my $engine = $self->engine;
793 0 ▶ return $engine if $engine->does('Langertha::Role::Embedding');
Branch: 1 branch
BranchTrueFalseTotal
if $engine->does("Langertha::Role::Embedding") 0 0 0
794 0 return undef;
795 }
796  
797 sub _cosine_similarity {
798 4 ▶ my ( $a, $b ) = @_;
Subroutine _cosine_similarity: called CC=4 SCAR=13.9
799 4 my $dot = 0;
800 4 my $na = 0;
801 4 my $nb = 0;
802 4 ▶ my $len = @$a < @$b ? @$a : @$b;
Branch: 1 branch
BranchTrueFalseTotal
@$a < @$b ? : 0 4 4
803 4 for my $i (0..$len-1) {
804 9 $dot += $a->[$i] * $b->[$i];
805 9 $na += $a->[$i] * $a->[$i];
806 9 $nb += $b->[$i] * $b->[$i];
807 }
808 4 my $denom = sqrt($na) * sqrt($nb);
809 4 ▶ return $denom > 0 ? $dot / $denom : 0;
Branch: 1 branch
BranchTrueFalseTotal
$denom > 0 ? : 3 1 4
810 }
811  
812 sub _push_session_history {
813 0 ▶ my ( $self, @msgs ) = @_;
Subroutine _push_session_history: not called CC=6 SCAR=37.4
814 0 push @{$self->session_history}, @msgs;
815 # Fire-and-forget embedding computation
816 0 my $engine = $self->_get_embedding_engine;
817 0 ▶ if ($engine) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine) { } 0 0 0
818 0 for my $msg (@msgs) {
819 0 my $text = $msg->{content};
820 0 ▶ next unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 0 0 0
Condition0%0/3
defined $text and length $text
!ll&&!rl&&r
000
MC/DC0%0/2
defined $text and length $text
defined $text length $text
Truth table0%0/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
821 0 eval {
822 0 my $vec = $engine->simple_embedding($text);
823 0 push @{$self->_session_embeddings}, $vec;
824 };
825 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
826 0 push @{$self->_session_embeddings}, undef;
827 }
828 }
829 } else {
830 0 push @{$self->_session_embeddings}, (undef) x scalar @msgs;
831 }
832 }
833  
834 sub raid {
835 0 ▶ my ( $self, @messages ) = @_;
Subroutine raid: not called CC=1 SCAR=6.9
Pod documented
836 0 return $self->raid_f(@messages)->get;
837 }
838  
839 4 ▶async sub run_f {
Subroutine run_f: called CC=8 SCAR=23.0
Pod undocumented
840 4 my ( $self, $ctx ) = @_;
841 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
842 unless blessed($ctx) && $ctx->isa('Langertha::RunContext');
843  
844 4 my $input = $ctx->input;
845 4 ▶ my @messages = ref($input) eq 'ARRAY' ? @{$input} : ($input);
Branch: 1 branch
BranchTrueFalseTotal
ref $input eq 'ARRAY' ? : 0 4 4
846 4 @messages = grep { defined } @messages;
847  
848 4 my $result = await $self->raid_f(@messages);
849  
850 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
851 4 $ctx->input($result->text);
852 4 $ctx->state->{last_output} = $result->text;
853 }
854 4 $ctx->state->{last_result_type} = $result->type;
855 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
856 4 ▶ $ctx->history($self->history) if $ctx->can('history');
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->can("history") 4 0 4
857  
858 4 return $result->with_context($ctx);
859 7 }
860  
861  
862 0 ▶async sub _gather_tools_f {
Subroutine _gather_tools_f: not called CC=12 SCAR=50.5
863 0 my ( $self ) = @_;
864 0 my $engine = $self->active_engine;
865 0 my ( @all_tools, %tool_server_map );
866  
867 # Engine MCP servers
868 0 ▶ if ($engine->can('mcp_servers')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->can("mcp_servers")) 0 0 0
869 0 for my $mcp (@{$engine->mcp_servers}) {
870 0 my $tools = await $mcp->list_tools;
871 0 for my $tool (@$tools) {
872 0 $tool_server_map{$tool->{name}} = $mcp;
873 0 push @all_tools, $tool;
874 }
875 }
876 }
877  
878 # Inline MCP
879 0 ▶ if ($self->has_inline_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_inline_mcp) 0 0 0
880 0 my $tools = await $self->_inline_mcp->list_tools;
881 0 for my $tool (@$tools) {
882 0 $tool_server_map{$tool->{name}} = $self->_inline_mcp;
883 0 push @all_tools, $tool;
884 }
885 }
886  
887 # Active catalog MCPs
888 0 for my $name (sort keys %{$self->_active_catalog_mcps}) {
889 0 my $mcp = $self->_active_catalog_mcps->{$name};
890 0 my $tools = await $mcp->list_tools;
891 0 for my $tool (@$tools) {
892 0 $tool_server_map{$tool->{name}} = $mcp;
893 0 push @all_tools, $tool;
894 }
895 }
896  
897 # Self-tools (virtual — no MCP server mapping needed)
898 0 ▶ if ($self->has_raider_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_raider_mcp) 0 0 0
899 0 push @all_tools, @{$self->_self_tool_definitions};
900 }
901  
902 # Plugin self-tools
903 0 for my $plugin (@{$self->_plugin_instances}) {
904 0 my $tools = $plugin->self_tools;
905 0 ▶ push @all_tools, @$tools if $tools && @$tools;
Branch: 1 branch
BranchTrueFalseTotal
if $tools and @$tools 0 0 0
Condition0%0/3
$tools and @$tools
!ll&&!rl&&r
000
MC/DC0%0/2
$tools and @$tools
$tools @$tools
Truth table0%0/3
A and B
A= $toolsB= @$tools
ABresult
0X0
100
111
906 }
907  
908 0 return ( \@all_tools, \%tool_server_map );
909 7 }
910  
911 0 ▶async sub _initialize_inline_mcp_f {
Subroutine _initialize_inline_mcp_f: not called CC=8 SCAR=42.8
912 0 my ( $self ) = @_;
913 0 ▶ return if $self->has_inline_mcp;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_inline_mcp 0 0 0
914  
915 # Collect inline tools + plugin tools
916 0 my @all_inline;
917 0 push @all_inline, @{$self->tools};
918 0 for my $plugin (@{$self->_plugin_instances}) {
919 0 my $tools = $plugin->self_tools;
920 0 ▶ push @all_inline, @$tools if $tools && @$tools;
Branch: 1 branch
BranchTrueFalseTotal
if $tools and @$tools 0 0 0
Condition0%0/3
$tools and @$tools
!ll&&!rl&&r
000
MC/DC0%0/2
$tools and @$tools
$tools @$tools
Truth table0%0/3
A and B
A= $toolsB= @$tools
ABresult
0X0
100
111
921 }
922 0 ▶ return unless @all_inline;
Branch: 1 branch
BranchTrueFalseTotal
unless @all_inline 0 0 0
923  
924 0 require MCP::Server;
925 0 require Net::Async::MCP;
926  
927 0 my $server = MCP::Server->new(name => 'raider-inline', version => '1.0');
928 0 for my $tdef (@all_inline) {
929 $server->tool(
930 name => $tdef->{name},
931 description => $tdef->{description},
932 input_schema => $tdef->{input_schema} // $tdef->{inputSchema},
933 code => $tdef->{code},
934 0 ▶ );
Condition0%0/3
$$tdef{"input_schema"} // $$tdef{"inputSchema"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$$tdef{"input_schema"} // $$tdef{"inputSchema"}
$$tdef{"input_schema"} $$tdef{"inputSchema"}
Truth table0%0/3
A // B
A= $$tdef{"input_schema"}B= $$tdef{"inputSchema"}
ABresult
1X1
011
000
935 }
936  
937 0 my $mcp = Net::Async::MCP->new(server => $server);
938 0 $self->engine->_async_http->loop->add($mcp);
939 0 await $mcp->initialize;
940 0 $self->_inline_mcp($mcp);
941 7 }
942  
943 0 ▶async sub raid_f {
Subroutine raid_f: not called CC=19 SCAR=59.4
Pod documented
944 0 my ( $self, @messages ) = @_;
945 0 my $engine = $self->active_engine;
946 0 my $t0 = [gettimeofday];
947 0 ▶ my $langfuse = $engine->can('langfuse_enabled') && $engine->langfuse_enabled;
Condition0%0/3
$engine->can('langfuse_enabled') && $engine->langfuse_enabled
!ll&&!rl&&r
000
MC/DC0%0/2
$engine->can('langfuse_enabled') && $engine->langfuse_enabled
$engine->can('langfuse_enabled') $engine->langfuse_enabled
Truth table0%0/3
A && B
A= $engine->can('langfuse_enabled')B= $engine->langfuse_enabled
ABresult
0X0
100
111
948 0 my $trace_id;
949  
950 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
951 my %trace_meta = (
952 mission => $self->has_mission ? $self->mission : undef,
953 0 ▶ history_length => scalar @{$self->history},
Branch: 1 branch
BranchTrueFalseTotal
$self->has_mission ? : 0 0 0
954 );
955 0 ▶ if ($self->has_langfuse_metadata) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_langfuse_metadata) 0 0 0
956 0 %trace_meta = (%trace_meta, %{$self->langfuse_metadata});
957 }
958 0 ▶ $trace_id = $engine->langfuse_trace(
Branch: 5 branches
BranchTrueFalseTotal
$self->has_langfuse_user_id ? : 0 0 0
$self->has_langfuse_session_id ? : 0 0 0
$self->has_langfuse_tags ? : 0 0 0
$self->has_langfuse_release ? : 0 0 0
$self->has_langfuse_version ? : 0 0 0
959 name => $self->langfuse_trace_name,
960 input => \@messages,
961 metadata => \%trace_meta,
962 $self->has_langfuse_user_id ? ( user_id => $self->langfuse_user_id ) : (),
963 $self->has_langfuse_session_id ? ( session_id => $self->langfuse_session_id ) : (),
964 $self->has_langfuse_tags ? ( tags => $self->langfuse_tags ) : (),
965 $self->has_langfuse_release ? ( release => $self->langfuse_release ) : (),
966 $self->has_langfuse_version ? ( version => $self->langfuse_version ) : (),
967 );
968 }
969  
970 # Auto-compress if threshold exceeded
971 0 ▶ 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) 0 0 0
Condition0%0/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
000
$self->has_max_context_tokens and $self->has_last_prompt_tokens
!ll&&!rl&&r
000
MC/DC0%0/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 table0%0/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
972 && $self->_last_prompt_tokens > $self->max_context_tokens * $self->context_compress_threshold) {
973 0 await $self->compress_history_f();
974 }
975  
976 # Plugin hook: transform input messages before raid
977 0 for my $plugin (@{$self->_plugin_instances}) {
978 0 @messages = @{await $plugin->plugin_before_raid(\@messages)};
979 }
980  
981 # Initialize inline MCP if tools defined
982 0 await $self->_initialize_inline_mcp_f;
983  
984 # Gather tools from all sources
985 0 my ( $all_tools, $tool_server_map ) = await $self->_gather_tools_f;
986  
987 0 ▶ croak "No tools available (configure MCP servers, inline tools, or raider_mcp)"
Branch: 1 branch
BranchTrueFalseTotal
unless @$all_tools 0 0 0
988 unless @$all_tools;
989  
990 0 my $formatted_tools = $engine->format_tools($all_tools);
991 0 ▶ my $model_params = $langfuse ? $self->_langfuse_model_parameters($engine) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
992  
993 # Build new user messages
994 my @user_msgs = map {
995 0 ▶ ref $_ ? $_ : { role => 'user', content => $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 0 0
996 } @messages;
997  
998 # Push user messages to session_history
999 0 $self->_push_session_history(@user_msgs);
1000  
1001 # Build full conversation: mission + history + new messages
1002 0 my @conversation;
1003 0 ▶ push @conversation, { role => 'system', content => $self->mission }
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_mission 0 0 0
1004 if $self->has_mission;
1005 0 push @conversation, @{$self->history};
1006 0 push @conversation, @user_msgs;
1007  
1008 # Plugin hook: transform assembled conversation
1009 0 for my $plugin (@{$self->_plugin_instances}) {
1010 0 @conversation = @{await $plugin->plugin_build_conversation(\@conversation)};
1011 }
1012  
1013 0 my $raid_iterations = 0;
1014 0 my $raid_tool_calls = 0;
1015 0 my @injected_history;
1016  
1017 # Package loop state for potential continuation
1018 0 my $state = {
1019 engine => $engine,
1020 t0 => $t0,
1021 langfuse => $langfuse,
1022 trace_id => $trace_id,
1023 tool_server_map => $tool_server_map,
1024 formatted_tools => $formatted_tools,
1025 model_params => $model_params,
1026 user_msgs => \@user_msgs,
1027 conversation => \@conversation,
1028 raid_iterations => \$raid_iterations,
1029 raid_tool_calls => \$raid_tool_calls,
1030 injected_history => \@injected_history,
1031 };
1032  
1033 0 return await $self->_run_raid_loop($state, 1);
1034 7 }
1035  
1036 0 ▶async sub _run_raid_loop {
Subroutine _run_raid_loop: not called CC=54 SCAR=80.0
1037 0 my ( $self, $state, $start_iteration ) = @_;
1038 0 my $engine = $state->{engine};
1039 0 my $langfuse = $state->{langfuse};
1040 0 my $trace_id = $state->{trace_id};
1041 0 my $tool_server_map = $state->{tool_server_map};
1042 0 my $formatted_tools = $state->{formatted_tools};
1043 0 my $model_params = $state->{model_params};
1044 0 my $user_msgs = $state->{user_msgs};
1045 0 my $conversation = $state->{conversation};
1046 0 my $raid_iterations = $state->{raid_iterations};
1047 0 my $raid_tool_calls = $state->{raid_tool_calls};
1048 0 my $injected_history = $state->{injected_history};
1049 0 my $t0 = $state->{t0};
1050  
1051 0 for my $iteration ($start_iteration..$self->max_iterations) {
1052 0 $$raid_iterations++;
1053  
1054 # Re-gather tools if catalog/engine changed
1055 0 ▶ if ($self->_tools_dirty) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_tools_dirty) 0 0 0
1056 0 $engine = $self->active_engine;
1057 0 $state->{engine} = $engine;
1058 0 my ( $all_tools, $new_map ) = await $self->_gather_tools_f;
1059 0 $formatted_tools = $engine->format_tools($all_tools);
1060 0 $tool_server_map = $new_map;
1061 0 $state->{formatted_tools} = $formatted_tools;
1062 0 $state->{tool_server_map} = $tool_server_map;
1063 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1064 0 $model_params = $self->_langfuse_model_parameters($engine);
1065 0 $state->{model_params} = $model_params;
1066 }
1067  
1068 0 $self->_tools_dirty(0);
1069 }
1070  
1071 # Drain injections for iterations 2+
1072 0 ▶ if ($iteration > $start_iteration || $start_iteration > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($iteration > $start_iteration or $start_iteration > 1) 0 0 0
Condition0%0/3
$iteration > $start_iteration or $start_iteration > 1
l!l&&r!l&&!r
000
MC/DC0%0/2
$iteration > $start_iteration or $start_iteration > 1
$iteration > $start_iteration $start_iteration > 1
Truth table0%0/3
A or B
A= $iteration > $start_iterationB= $start_iteration > 1
ABresult
1X1
011
000
1073 0 my @injected;
1074 0 ▶ if (@{$self->_injections}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->_injections;}) 0 0 0
1075 0 push @injected, splice @{$self->_injections};
1076 }
1077 0 ▶ if ($self->has_on_iteration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on_iteration) 0 0 0
1078 0 my $cb_msgs = $self->on_iteration->($self, $iteration);
1079 0 ▶ push @injected, @$cb_msgs if $cb_msgs && @$cb_msgs;
Branch: 1 branch
BranchTrueFalseTotal
if $cb_msgs and @$cb_msgs 0 0 0
Condition0%0/3
$cb_msgs and @$cb_msgs
!ll&&!rl&&r
000
MC/DC0%0/2
$cb_msgs and @$cb_msgs
$cb_msgs @$cb_msgs
Truth table0%0/3
A and B
A= $cb_msgsB= @$cb_msgs
ABresult
0X0
100
111
1080 }
1081 0 ▶ if (@injected) {
Branch: 1 branch
BranchTrueFalseTotal
if (@injected) 0 0 0
1082 my @msgs = map {
1083 0 ▶ ref $_ ? $_ : { role => 'user', content => $_ }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 0 0
1084 } @injected;
1085 0 push @$conversation, @msgs;
1086 0 push @$injected_history, @msgs;
1087 0 $self->_push_session_history(@msgs);
1088 }
1089 }
1090  
1091 # Plugin hook: transform conversation before each LLM call
1092 0 for my $plugin (@{$self->_plugin_instances}) {
1093 0 $conversation = await $plugin->plugin_before_llm_call($conversation, $iteration);
1094 }
1095  
1096 0 ▶ my $iter_t0 = $langfuse ? $engine->_langfuse_timestamp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
1097  
1098 # Langfuse: create iteration span
1099 0 my $iter_span_id;
1100 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1101 0 $iter_span_id = $engine->langfuse_span(
1102 trace_id => $trace_id,
1103 name => "iteration-$iteration",
1104 start_time => $iter_t0,
1105 );
1106 }
1107  
1108 # Build and send the request
1109 0 my $request = $engine->build_tool_chat_request($conversation, $formatted_tools);
1110  
1111 0 my $response = await $engine->_async_http->do_request(request => $request);
1112  
1113 0 ▶ unless ($response->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($response->is_success) 0 0 0
1114 0 die "".(ref $engine)." raid request failed: ".$response->status_line."\n".$response->content;
1115 }
1116  
1117 0 my $data = $engine->parse_response($response);
1118  
1119 # Plugin hook: inspect/transform LLM response
1120 0 for my $plugin (@{$self->_plugin_instances}) {
1121 0 $data = await $plugin->plugin_after_llm_response($data, $iteration);
1122 }
1123  
1124 # Track prompt tokens for auto-compression
1125 0 my $pt = $self->_extract_prompt_tokens($data);
1126 0 ▶ $self->_last_prompt_tokens($pt) if defined $pt;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pt 0 0 0
1127  
1128 # Extract usage for Langfuse
1129 0 ▶ my $langfuse_usage = $langfuse ? $self->_langfuse_usage($data) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
1130  
1131 # Extract tool calls
1132 0 my $tool_calls = $engine->response_tool_calls($data);
1133  
1134 # No tool calls means done — extract final text
1135 0 ▶ unless (@$tool_calls) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@$tool_calls) 0 0 0
1136 0 my $text = $engine->response_text_content($data);
1137 0 ▶ if ($engine->think_tag_filter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine->think_tag_filter) 0 0 0
1138 0 ($text) = $engine->filter_think_content($text);
1139 }
1140  
1141 0 ▶ my $iter_t1 = $langfuse ? $engine->_langfuse_timestamp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
1142  
1143 # Langfuse: generation nested under iteration span
1144 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1145 0 ▶ $engine->langfuse_generation(
Branch: 2 branches
BranchTrueFalseTotal
$langfuse_usage ? : 0 0 0
$model_params ? : 0 0 0
1146 trace_id => $trace_id,
1147 parent_observation_id => $iter_span_id,
1148 name => 'llm-call',
1149 model => $engine->chat_model,
1150 input => $conversation,
1151 output => $text,
1152 start_time => $iter_t0,
1153 end_time => $iter_t1,
1154 $langfuse_usage ? ( usage => $langfuse_usage ) : (),
1155 $model_params ? ( model_parameters => $model_params ) : (),
1156 );
1157  
1158 # Close iteration span
1159 0 $engine->langfuse_update_span(
1160 id => $iter_span_id,
1161 end_time => $iter_t1,
1162 output => $text,
1163 );
1164  
1165 # Update trace with final output
1166 0 $engine->langfuse_update_trace(
1167 id => $trace_id,
1168 output => $text,
1169 );
1170 }
1171  
1172 # Persist user messages, injections, and final assistant response in history
1173 0 push @{$self->history}, @$user_msgs;
1174 0 ▶ push @{$self->history}, @$injected_history if @$injected_history;
Branch: 1 branch
BranchTrueFalseTotal
if @$injected_history 0 0 0
1175 0 push @{$self->history}, { role => 'assistant', content => $text };
1176  
1177 # Push final assistant response to session_history
1178 0 $self->_push_session_history({ role => 'assistant', content => $text });
1179  
1180 # Update metrics
1181 0 my $elapsed = tv_interval($t0) * 1000;
1182 0 my $m = $self->metrics;
1183 0 $m->{raids}++;
1184 0 $m->{iterations} += $$raid_iterations;
1185 0 $m->{tool_calls} += $$raid_tool_calls;
1186 0 $m->{time_ms} += $elapsed;
1187  
1188 0 my $result = Langertha::Raider::Result->new(type => 'final', text => $text);
1189  
1190 # Plugin hook: transform final result before return
1191 0 for my $plugin (@{$self->_plugin_instances}) {
1192 0 $result = await $plugin->plugin_after_raid($result);
1193 }
1194  
1195 0 return $result;
1196 }
1197  
1198 # Langfuse: generation for the LLM call that produced tool calls
1199 0 ▶ my $post_llm_t = $langfuse ? $engine->_langfuse_timestamp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
1200 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1201 $engine->langfuse_generation(
1202 trace_id => $trace_id,
1203 parent_observation_id => $iter_span_id,
1204 name => 'llm-call',
1205 model => $engine->chat_model,
1206 input => $conversation,
1207 output => $engine->json->encode([map {
1208 0 ▶ ($engine->extract_tool_call($_))[0]
Branch: 2 branches
BranchTrueFalseTotal
$langfuse_usage ? : 0 0 0
$model_params ? : 0 0 0
1209 } @$tool_calls]),
1210 start_time => $iter_t0,
1211 end_time => $post_llm_t,
1212 $langfuse_usage ? ( usage => $langfuse_usage ) : (),
1213 $model_params ? ( model_parameters => $model_params ) : (),
1214 );
1215 }
1216  
1217 # Execute each tool call
1218 0 my @results;
1219 0 for my $tc (@$tool_calls) {
1220 0 my ( $name, $input ) = $engine->extract_tool_call($tc);
1221  
1222 # Plugin hook: inspect/transform before tool execution
1223 0 my @plugin_tc = await $self->_plugin_pipeline_tool_call($name, $input);
1224 0 ▶ unless (@plugin_tc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@plugin_tc) 0 0 0
1225 # Plugin returned empty list — skip this tool call
1226 0 my $skip_result = {
1227 content => [{ type => 'text', text => "Tool call '$name' was skipped by plugin." }],
1228 };
1229 0 push @results, { tool_call => $tc, result => $skip_result };
1230 0 $$raid_tool_calls++;
1231 0 next;
1232 }
1233 0 ( $name, $input ) = @plugin_tc;
1234  
1235 0 ▶ my $tool_t0 = $langfuse ? $engine->_langfuse_timestamp : undef;
Branch: 1 branch
BranchTrueFalseTotal
$langfuse ? : 0 0 0
1236  
1237 # Check for virtual self-tools
1238 0 ▶ if ($name =~ /^raider_/ && $self->has_raider_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^raider_/ and $self->has_raider_mcp) 0 0 0
Condition0%0/3
$name =~ /^raider_/ and $self->has_raider_mcp
!ll&&!rl&&r
000
MC/DC0%0/2
$name =~ /^raider_/ and $self->has_raider_mcp
$name =~ /^raider_/ $self->has_raider_mcp
Truth table0%0/3
A and B
A= $name =~ /^raider_/B= $self->has_raider_mcp
ABresult
0X0
100
111
1239 0 my $self_result = $self->_execute_self_tool($name, $input);
1240  
1241 # Handle interactive self-tool results
1242 0 ▶ 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") 0 0 0
Condition0%0/3
$$self_result{"type"} eq "question" or $$self_result{"type"} eq "pause"
l!l&&r!l&&!r
000
MC/DC0%0/2
$$self_result{"type"} eq "question" or $$self_result{"type"} eq "pause"
$$self_result{"type"} eq "question" $$self_result{"type"} eq "pause"
Truth table0%0/3
A or B
A= $$self_result{"type"} eq "question"B= $$self_result{"type"} eq "pause"
ABresult
1X1
011
000
1243 # Save continuation state for respond_f
1244 $self->_continuation({
1245 state => $state,
1246 iteration => $iteration,
1247 data => $data,
1248 pending_tc => $tc,
1249 0 remaining_tcs => [grep { $_ != $tc } @$tool_calls],
1250 results_so_far => \@results,
1251 iter_span_id => $iter_span_id,
1252 });
1253  
1254 0 ▶ if ($self_result->{type} eq 'question') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{'type'} eq 'question') { } 0 0 0
1255 return Langertha::Raider::Result->new(
1256 type => 'question',
1257 content => $self_result->{question},
1258 0 ▶ $self_result->{options} ? (options => $self_result->{options}) : (),
Branch: 1 branch
BranchTrueFalseTotal
$$self_result{'options'} ? : 0 0 0
1259 );
1260 } else {
1261 return Langertha::Raider::Result->new(
1262 type => 'pause',
1263 content => $self_result->{reason},
1264 0 );
1265 }
1266 }
1267  
1268 0 ▶ if ($self_result->{type} eq 'abort') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{"type"} eq "abort") 0 0 0
1269 # Finalize metrics before aborting
1270 0 my $elapsed = tv_interval($t0) * 1000;
1271 0 my $m = $self->metrics;
1272 0 $m->{iterations} += $$raid_iterations;
1273 0 $m->{tool_calls} += $$raid_tool_calls;
1274 0 $m->{time_ms} += $elapsed;
1275  
1276 return Langertha::Raider::Result->new(
1277 type => 'abort',
1278 content => $self_result->{reason},
1279 0 );
1280 }
1281  
1282 0 ▶ if ($self_result->{type} eq 'wait') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{"type"} eq "wait") 0 0 0
1283 0 my $loop = $engine->_async_http->loop;
1284 0 await $loop->delay_future(after => $self_result->{seconds});
1285 0 my $result = {
1286 content => [{ type => 'text', text => "Waited $self_result->{seconds} seconds." }],
1287 };
1288  
1289 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1290 0 $engine->langfuse_span(
1291 trace_id => $trace_id,
1292 parent_observation_id => $iter_span_id,
1293 name => "tool: $name",
1294 input => $input,
1295 output => "Waited $self_result->{seconds} seconds.",
1296 start_time => $tool_t0,
1297 end_time => $engine->_langfuse_timestamp,
1298 );
1299 }
1300  
1301 0 push @results, { tool_call => $tc, result => $result };
1302 0 $$raid_tool_calls++;
1303 0 next;
1304 }
1305  
1306 # type eq 'result' — normal self-tool result
1307 0 my $result = $self_result;
1308  
1309 # Plugin hook: transform tool result
1310 0 for my $plugin (@{$self->_plugin_instances}) {
1311 0 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
1312 }
1313  
1314 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1315 0 ▶ my $tool_output = join('', map { $_->{text} // '' } @{$result->{content} // []});
Condition0%0/4
$$_{"text"} // ""
l!l
00
$$result{"content"} // []
l!l
00
MC/DC0%0/1
$$_{"text"} // ""
$$_{"text"}
MC/DC0%0/1
$$result{"content"} // []
$$result{"content"}
Truth table0%0/2
A
A= $$_{"text"}
Aresult
11
00
Truth table0%0/2
A
A= $$result{"content"}
Aresult
11
00
1316 0 $engine->langfuse_span(
1317 trace_id => $trace_id,
1318 parent_observation_id => $iter_span_id,
1319 name => "tool: $name",
1320 input => $input,
1321 output => $tool_output,
1322 start_time => $tool_t0,
1323 end_time => $engine->_langfuse_timestamp,
1324 );
1325 }
1326  
1327 0 push @results, { tool_call => $tc, result => $result };
1328 0 $$raid_tool_calls++;
1329 0 next;
1330 }
1331  
1332 # Normal MCP tool call
1333 0 ▶ my $mcp = $tool_server_map->{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $mcp = $$tool_server_map{$name} or die "Tool '${name}' not found on any MCP server" 0 0 0
1334 or die "Tool '$name' not found on any MCP server";
1335  
1336 my $result = await $mcp->call_tool($name, $input)->else(sub {
1337 0 ▶ my ( $error ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1338 0 Future->done({
1339 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
1340 isError => JSON::MaybeXS->true,
1341 });
1342 0 });
1343  
1344 # Plugin hook: transform tool result
1345 0 for my $plugin (@{$self->_plugin_instances}) {
1346 0 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
1347 }
1348  
1349 # Langfuse: span for each tool call, nested under iteration span
1350 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1351 0 ▶ my $tool_output = join('', map { $_->{text} // '' } @{$result->{content} // []});
Condition0%0/4
$$_{"text"} // ""
l!l
00
$$result{"content"} // []
l!l
00
MC/DC0%0/1
$$_{"text"} // ""
$$_{"text"}
MC/DC0%0/1
$$result{"content"} // []
$$result{"content"}
Truth table0%0/2
A
A= $$_{"text"}
Aresult
11
00
Truth table0%0/2
A
A= $$result{"content"}
Aresult
11
00
1352 $engine->langfuse_span(
1353 trace_id => $trace_id,
1354 parent_observation_id => $iter_span_id,
1355 name => "tool: $name",
1356 input => $input,
1357 output => $tool_output,
1358 start_time => $tool_t0,
1359 end_time => $engine->_langfuse_timestamp,
1360 0 ▶ $result->{isError} ? ( level => 'ERROR' ) : (),
Branch: 1 branch
BranchTrueFalseTotal
$$result{'isError'} ? : 0 0 0
1361 );
1362 }
1363  
1364 0 push @results, { tool_call => $tc, result => $result };
1365 0 $$raid_tool_calls++;
1366 }
1367  
1368 # Langfuse: close iteration span after tools complete
1369 0 ▶ if ($langfuse) {
Branch: 1 branch
BranchTrueFalseTotal
if ($langfuse) 0 0 0
1370 $engine->langfuse_update_span(
1371 id => $iter_span_id,
1372 end_time => $engine->_langfuse_timestamp,
1373 metadata => {
1374 tool_calls => scalar @$tool_calls,
1375 tools_used => [map {
1376 0 ($engine->extract_tool_call($_->{tool_call}))[0]
1377 } @results],
1378 },
1379 );
1380 }
1381  
1382 # Append assistant + tool results to conversation and session_history
1383 0 my @tool_msgs = $engine->format_tool_results($data, \@results);
1384 0 push @$conversation, @tool_msgs;
1385 0 $self->_push_session_history(@tool_msgs);
1386 }
1387  
1388 0 die "Raider tool loop exceeded ".$self->max_iterations." iterations";
1389 7 }
1390  
1391 0 ▶async sub respond_f {
Subroutine respond_f: not called CC=11 SCAR=48.8
Pod documented
1392 0 my ( $self, $answer ) = @_;
1393 0 ▶ croak "No pending interaction — call raid_f first"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_continuation 0 0 0
1394 unless $self->has_continuation;
1395  
1396 0 my $cont = $self->_continuation;
1397 0 $self->clear_continuation;
1398  
1399 0 my $state = $cont->{state};
1400 0 my $data = $cont->{data};
1401 0 my $pending_tc = $cont->{pending_tc};
1402 0 my @results = @{$cont->{results_so_far}};
1403 0 my $engine = $state->{engine};
1404  
1405 # Add the answer as the tool result for the pending self-tool call
1406 0 my $answer_result = {
1407 content => [{ type => 'text', text => "$answer" }],
1408 };
1409 0 push @results, { tool_call => $pending_tc, result => $answer_result };
1410 0 ${$state->{raid_tool_calls}}++;
1411  
1412 # Execute remaining tool calls from the same batch
1413 0 for my $tc (@{$cont->{remaining_tcs}}) {
1414 0 my ( $name, $input ) = $engine->extract_tool_call($tc);
1415  
1416 0 ▶ if ($name =~ /^raider_/ && $self->has_raider_mcp) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^raider_/ and $self->has_raider_mcp) 0 0 0
Condition0%0/3
$name =~ /^raider_/ and $self->has_raider_mcp
!ll&&!rl&&r
000
MC/DC0%0/2
$name =~ /^raider_/ and $self->has_raider_mcp
$name =~ /^raider_/ $self->has_raider_mcp
Truth table0%0/3
A and B
A= $name =~ /^raider_/B= $self->has_raider_mcp
ABresult
0X0
100
111
1417 0 my $self_result = $self->_execute_self_tool($name, $input);
1418 0 ▶ if ($self_result->{type} eq 'result') {
Branch: 1 branch
BranchTrueFalseTotal
if ($$self_result{"type"} eq "result") 0 0 0
1419 0 for my $plugin (@{$self->_plugin_instances}) {
1420 0 $self_result = await $plugin->plugin_after_tool_call($name, $input, $self_result);
1421 }
1422 0 push @results, { tool_call => $tc, result => $self_result };
1423 0 ${$state->{raid_tool_calls}}++;
1424 }
1425 # For simplicity, skip interactive self-tools in remaining batch
1426 0 next;
1427 }
1428  
1429 0 ▶ my $mcp = $state->{tool_server_map}{$name}
Branch: 1 branch
BranchTrueFalseTotal
my $mcp = $$state{"tool_server_map"}{$name} or die "Tool '${name}' not found on any MCP server" 0 0 0
1430 or die "Tool '$name' not found on any MCP server";
1431  
1432 my $result = await $mcp->call_tool($name, $input)->else(sub {
1433 0 ▶ my ( $error ) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1434 0 Future->done({
1435 content => [{ type => 'text', text => "Error calling tool '$name': $error" }],
1436 isError => JSON::MaybeXS->true,
1437 });
1438 0 });
1439  
1440 0 for my $plugin (@{$self->_plugin_instances}) {
1441 0 $result = await $plugin->plugin_after_tool_call($name, $input, $result);
1442 }
1443  
1444 0 push @results, { tool_call => $tc, result => $result };
1445 0 ${$state->{raid_tool_calls}}++;
1446 }
1447  
1448 # Close iteration span if Langfuse
1449 0 ▶ if ($state->{langfuse} && $cont->{iter_span_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$state{"langfuse"} and $$cont{"iter_span_id"}) 0 0 0
Condition0%0/3
$$state{"langfuse"} and $$cont{"iter_span_id"}
!ll&&!rl&&r
000
MC/DC0%0/2
$$state{"langfuse"} and $$cont{"iter_span_id"}
$$state{"langfuse"} $$cont{"iter_span_id"}
Truth table0%0/3
A and B
A= $$state{"langfuse"}B= $$cont{"iter_span_id"}
ABresult
0X0
100
111
1450 $engine->langfuse_update_span(
1451 id => $cont->{iter_span_id},
1452 0 end_time => $engine->_langfuse_timestamp,
1453 metadata => { tool_calls => scalar @results },
1454 );
1455 }
1456  
1457 # Format tool results and append to conversation
1458 0 my @tool_msgs = $engine->format_tool_results($data, \@results);
1459 0 push @{$state->{conversation}}, @tool_msgs;
1460 0 $self->_push_session_history(@tool_msgs);
1461  
1462 # Continue the raid loop from the next iteration
1463 0 return await $self->_run_raid_loop($state, $cont->{iteration} + 1);
1464 7 }
1465  
1466 sub respond {
1467 0 ▶ my ( $self, $answer ) = @_;
Subroutine respond: not called CC=1 SCAR=6.9
Pod documented
1468 0 return $self->respond_f($answer)->get;
1469 }
1470  
1471  
1472  
1473 7 __PACKAGE__->meta->make_immutable;
1474  
1475 7 1;
1476  
1477 __END__
1478  
1479 =pod
1480  
1481 =encoding UTF-8
1482  
1483 =head1 NAME
1484  
1485 Langertha::Raider - Autonomous agent with conversation history and MCP tools
1486  
1487 =head1 VERSION
1488  
1489 version 0.502
1490  
1491 =head1 SYNOPSIS
1492  
1493 use IO::Async::Loop;
1494 use Future::AsyncAwait;
1495 use Net::Async::MCP;
1496 use MCP::Server;
1497 use Langertha::Engine::Anthropic;
1498 use Langertha::Raider;
1499  
1500 # Set up MCP server with tools
1501 my $server = MCP::Server->new(name => 'demo', version => '1.0');
1502 $server->tool(
1503 name => 'list_files',
1504 description => 'List files in a directory',
1505 input_schema => {
1506 type => 'object',
1507 properties => { path => { type => 'string' } },
1508 required => ['path'],
1509 },
1510 code => sub { $_[0]->text_result(join("\n", glob("$_[1]->{path}/*"))) },
1511 );
1512  
1513 my $loop = IO::Async::Loop->new;
1514 my $mcp = Net::Async::MCP->new(server => $server);
1515 $loop->add($mcp);
1516  
1517 async sub main {
1518 await $mcp->initialize;
1519  
1520 my $engine = Langertha::Engine::Anthropic->new(
1521 api_key => $ENV{ANTHROPIC_API_KEY},
1522 mcp_servers => [$mcp],
1523 );
1524  
1525 my $raider = Langertha::Raider->new(
1526 engine => $engine,
1527 mission => 'You are a code explorer. Investigate files thoroughly.',
1528 );
1529  
1530 # First raid — uses tools, builds history
1531 my $r1 = await $raider->raid_f('What files are in the current directory?');
1532 say $r1;
1533  
1534 # Second raid — has context from first conversation
1535 my $r2 = await $raider->raid_f('Tell me more about the first file you found.');
1536 say $r2;
1537  
1538 # Check metrics
1539 my $m = $raider->metrics;
1540 say "Raids: $m->{raids}, Tool calls: $m->{tool_calls}, Time: $m->{time_ms}ms";
1541  
1542 # Reset for a fresh conversation
1543 $raider->clear_history;
1544 }
1545  
1546 main()->get;
1547  
1548 =head1 DESCRIPTION
1549  
1550 Langertha::Raider is an autonomous agent that wraps a Langertha engine
1551 with MCP tools. It maintains conversation history across multiple
1552 interactions (raids), enabling multi-turn conversations where the LLM
1553 can reference prior context.
1554  
1555 B<Key features:>
1556  
1557 =over 4
1558  
1559 =item * Conversation history persisted across raids
1560  
1561 =item * Mission (system prompt) separate from engine's system_prompt
1562  
1563 =item * Automatic MCP tool calling loop
1564  
1565 =item * Cumulative metrics tracking
1566  
1567 =item * Hermes tool calling support (inherited from engine)
1568  
1569 =item * Mid-raid context injection via C<inject()> and C<on_iteration>
1570  
1571 =back
1572  
1573 B<History management:> Only user messages and final assistant text
1574 responses are persisted in history. Intermediate tool-call messages
1575 (assistant tool requests and tool results) are NOT persisted, preventing
1576 token bloat across long conversations.
1577  
1578 =head2 engine
1579  
1580 Required. A Langertha engine instance with MCP servers configured.
1581 The engine must compose L<Langertha::Role::Tools>.
1582  
1583 =head2 mission
1584  
1585 Optional system prompt for the Raider. This is separate from the
1586 engine's own C<system_prompt> — the Raider's mission takes precedence
1587 and is prepended to every conversation.
1588  
1589 =head2 history
1590  
1591 ArrayRef of message hashes representing the conversation history.
1592 Automatically managed by C<raid>/C<raid_f>. Can be inspected or
1593 manually set.
1594  
1595 =head2 max_iterations
1596  
1597 Maximum number of tool-calling round trips per raid. Defaults to C<10>.
1598  
1599 =head2 max_context_tokens
1600  
1601 Optional. Enables auto-compression when set. When prompt token usage
1602 exceeds C<context_compress_threshold * max_context_tokens>, the working
1603 history is summarized via LLM before the next raid.
1604  
1605 =head2 context_compress_threshold
1606  
1607 Fraction of C<max_context_tokens> that triggers compression. Defaults
1608 to C<0.75> (75%).
1609  
1610 =head2 compression_prompt
1611  
1612 System prompt used for history summarization. Customizable. The default
1613 instructs the LLM to preserve key facts, decisions, and context.
1614  
1615 =head2 compression_engine
1616  
1617 Optional separate engine for compression (e.g. a cheaper model).
1618 Falls back to C<engine> when not set.
1619  
1620 =head2 session_history
1621  
1622 Full chronological archive of ALL messages including tool calls and
1623 results. Never auto-compressed. Persists across C<clear_history> and
1624 C<reset>. Only cleared manually via C<< $raider->session_history([]) >>.
1625  
1626 =head2 on_iteration
1627  
1628 Optional CodeRef called before each LLM call (iterations 2+). Receives
1629 C<($raider, $iteration)> and returns an arrayref of messages to inject,
1630 or undef/empty to skip.
1631  
1632 my $raider = Langertha::Raider->new(
1633 engine => $engine,
1634 on_iteration => sub {
1635 my ($raider, $iteration) = @_;
1636 return ['Check the error log'] if $iteration == 3;
1637 return;
1638 },
1639 );
1640  
1641 =head2 metrics
1642  
1643 HashRef of cumulative metrics across all raids:
1644  
1645 {
1646 raids => 3, # Number of completed raids
1647 iterations => 7, # Total LLM round trips
1648 tool_calls => 12, # Total tool invocations
1649 time_ms => 4500.2, # Total wall-clock time in milliseconds
1650 }
1651  
1652 =head2 langfuse_trace_name
1653  
1654 Name for the Langfuse trace created per raid. Defaults to C<'raid'>.
1655  
1656 =head2 langfuse_user_id
1657  
1658 Optional user ID passed to the Langfuse trace.
1659  
1660 =head2 langfuse_session_id
1661  
1662 Optional session ID passed to the Langfuse trace. Use this to group
1663 multiple raids into a single Langfuse session.
1664  
1665 =head2 langfuse_tags
1666  
1667 Optional tags (ArrayRef[Str]) passed to the Langfuse trace.
1668  
1669 =head2 langfuse_release
1670  
1671 Optional release identifier passed to the Langfuse trace.
1672  
1673 =head2 langfuse_version
1674  
1675 Optional version string passed to the Langfuse trace.
1676  
1677 =head2 langfuse_metadata
1678  
1679 Optional metadata HashRef merged into the Langfuse trace metadata
1680 (alongside auto-generated fields like mission and history_length).
1681  
1682 =head2 raider_mcp
1683  
1684 Enables virtual self-tools that the LLM can call to interact with the
1685 Raider itself. Set to C<1> to enable all self-tools, or pass a HashRef
1686 to enable selectively:
1687  
1688 raider_mcp => 1 # all self-tools
1689 raider_mcp => { ask_user => 1, pause => 1 } # only these
1690  
1691 Available self-tools: C<ask_user>, C<wait>, C<wait_for>, C<pause>,
1692 C<abort>, C<session_history>, C<manage_mcps>, C<switch_engine>.
1693  
1694 =head2 on_ask_user
1695  
1696 Optional callback for the C<raider_ask_user> self-tool. Receives
1697 C<($question, $options)> and must return an answer string. When not set,
1698 the raid pauses and returns a C<question> Result that can be continued
1699 with L</respond_f>.
1700  
1701 =head2 on_pause
1702  
1703 Optional callback for the C<raider_pause> self-tool. Receives C<($reason)>.
1704 When not set, the raid pauses and returns a C<pause> Result.
1705  
1706 =head2 on_wait_for
1707  
1708 Callback for the C<raider_wait_for> self-tool. Receives
1709 C<($condition, $args)> and must return a result string. Required when the
1710 LLM uses C<raider_wait_for> — will die if not set.
1711  
1712 =head2 tools
1713  
1714 Optional ArrayRef of inline tool definitions. Each entry is a HashRef with
1715 C<name>, C<description>, C<input_schema>, and C<code> keys — the same
1716 format as L<MCP::Server/tool>. An internal MCP server is created
1717 automatically.
1718  
1719 my $raider = Langertha::Raider->new(
1720 engine => $engine,
1721 tools => [{
1722 name => 'greet',
1723 description => 'Say hello',
1724 input_schema => { type => 'object', properties => { name => { type => 'string' } } },
1725 code => sub { $_[0]->text_result("Hello $_[1]->{name}!") },
1726 }],
1727 );
1728  
1729 =head2 mcp_catalog
1730  
1731 HashRef of named MCP servers available for dynamic activation. The LLM can
1732 use C<raider_manage_mcps> to list, activate, and deactivate catalog entries.
1733  
1734 mcp_catalog => {
1735 database => { server => $db_mcp, description => 'Database tools', auto => 1 },
1736 email => { server => $email_mcp, description => 'Email tools' },
1737 }
1738  
1739 Entries with C<< auto => 1 >> are activated at construction time.
1740  
1741 =head2 engine_catalog
1742  
1743 HashRef of named engines available for runtime switching via C<switch_engine>.
1744  
1745 engine_catalog => {
1746 fast => { engine => $groq, description => 'Fast inference' },
1747 smart => { engine => $anthropic, description => 'Complex reasoning' },
1748 code => { engine => $deepseek, description => 'Code generation' },
1749 }
1750  
1751 Entries without an C<engine> key refer to the default engine (the one passed
1752 as C<engine> at construction). This lets you give the default engine a named
1753 catalog entry with a description:
1754  
1755 engine_catalog => {
1756 sonnet => { description => 'Balanced model for everyday tasks' },
1757 fast => { engine => $groq, description => 'Fast inference' },
1758 smart => { engine => $opus, description => 'Complex reasoning' },
1759 }
1760  
1761 The LLM always sees a C<default> entry (reset to original) plus all catalog
1762 keys in the C<raider_switch_engine> tool enum.
1763  
1764 Use C<switch_engine>, C<reset_engine>, C<active_engine>, and C<engine_info>
1765 to control which engine is used during raids.
1766  
1767 =head2 embedding_engine
1768  
1769 Optional engine with L<Langertha::Role::Embedding> for semantic history search.
1770 When not set, auto-detects if the main C<engine> supports embeddings.
1771 Set L</no_session_embeddings> to disable auto-detection.
1772  
1773 =head2 no_session_embeddings
1774  
1775 When true, disables automatic embedding computation for session history
1776 entries. Useful when the engine supports embeddings but calling it would
1777 cause issues (e.g. self-referencing proxy deadlock).
1778  
1779 =head2 clear_history
1780  
1781 $raider->clear_history;
1782  
1783 Clears conversation history and pending injections while preserving metrics.
1784  
1785 =head2 add_history
1786  
1787 $raider->add_history('user', 'Hello');
1788 $raider->add_history('assistant', 'Hi there!');
1789  
1790 Appends a message to the conversation history. Useful for replaying
1791 persisted messages into a fresh Raider instance.
1792  
1793 =head2 inject
1794  
1795 $raider->inject('Also check the test files');
1796 $raider->inject({ role => 'user', content => 'Focus on .pm files' });
1797  
1798 Queues messages to be injected into the conversation at the next iteration.
1799 Strings are automatically wrapped as user messages. The Raider drains the
1800 queue before each LLM call (iterations 2+).
1801  
1802 =head2 reset
1803  
1804 $raider->reset;
1805  
1806 Clears conversation history, metrics, and resets to the default engine.
1807  
1808 =head2 active_engine
1809  
1810 my $engine = $raider->active_engine;
1811  
1812 Returns the currently active engine. If C<switch_engine> was called, returns
1813 the catalog engine; otherwise returns the default C<engine>.
1814  
1815 =head2 active_engine_name
1816  
1817 my $name = $raider->active_engine_name; # 'smart' or undef
1818  
1819 Returns the name of the currently active catalog engine, or C<undef> if using
1820 the default engine.
1821  
1822 =head2 switch_engine
1823  
1824 $raider->switch_engine('smart');
1825  
1826 Switches to a named engine from the C<engine_catalog>. Sets C<_tools_dirty>
1827 so the raid loop re-gathers and re-formats tools for the new engine.
1828 Croaks if the name is not in the catalog.
1829  
1830 =head2 reset_engine
1831  
1832 $raider->reset_engine;
1833  
1834 Switches back to the default engine (the one passed at construction).
1835  
1836 =head2 engine_info
1837  
1838 my $info = $raider->engine_info;
1839 # { name => 'smart', class => 'Langertha::Engine::Anthropic', model => 'claude-sonnet-4-6' }
1840  
1841 Returns a hashref with the active engine's name, class, and model.
1842  
1843 =head2 list_engines
1844  
1845 my $engines = $raider->list_engines;
1846  
1847 Returns a hashref of all available engines (default + catalog entries),
1848 each with C<engine>, C<description> (if from catalog), and C<active> flag.
1849  
1850 =head2 add_engine
1851  
1852 $raider->add_engine('vision', engine => $vision_engine, description => 'Vision model');
1853 $raider->add_engine('main', description => 'Default model for general tasks');
1854  
1855 Adds a new engine to the catalog at runtime. If C<engine> is omitted, the
1856 entry refers to the default engine. The LLM will see it in the
1857 C<raider_switch_engine> tool after the next tool re-gather.
1858  
1859 =head2 remove_engine
1860  
1861 $raider->remove_engine('vision');
1862  
1863 Removes an engine from the catalog. If the removed engine is currently active,
1864 automatically resets to the default engine.
1865  
1866 =head2 compress_history_f
1867  
1868 my $summary = await $raider->compress_history_f;
1869  
1870 Async. Summarizes the current working history via LLM and replaces it
1871 with the summary. Uses C<compression_engine> if set, otherwise falls
1872 back to C<engine>. A marker is added to C<session_history>.
1873  
1874 =head2 compress_history
1875  
1876 my $summary = $raider->compress_history;
1877  
1878 Synchronous wrapper around C<compress_history_f>.
1879  
1880 =head2 register_session_history_tool
1881  
1882 $raider->register_session_history_tool($mcp_server);
1883  
1884 Registers a C<session_history> MCP tool on the given server, allowing
1885 the LLM to query its own full session history. Supports C<query>
1886 (text filter) and C<last_n> (return last N messages) parameters.
1887  
1888 =head2 raid
1889  
1890 my $response = $raider->raid(@messages);
1891  
1892 Synchronous wrapper around C<raid_f>. Sends messages, runs the tool
1893 loop, and returns the final text response. Updates history and metrics.
1894  
1895 =head2 raid_f
1896  
1897 my $result = await $raider->raid_f(@messages);
1898  
1899 Async tool-calling conversation. Accepts the same message arguments as
1900 C<simple_chat> (strings become user messages, hashrefs pass through).
1901 Returns a L<Future> resolving to a L<Langertha::Raider::Result>.
1902  
1903 The result stringifies to the final text (backward compatible), but also
1904 provides C<type>, C<is_final>, C<is_question>, C<is_pause>, C<is_abort>
1905 for programmatic handling of interactive self-tools.
1906  
1907 =head2 respond_f
1908  
1909 my $result = await $raider->respond_f($answer);
1910  
1911 Continue a paused raid after a C<question> or C<pause> result. The answer
1912 is used as the tool result and the raid loop resumes. Returns the next
1913 L<Langertha::Raider::Result>.
1914  
1915 =head2 respond
1916  
1917 my $result = $raider->respond($answer);
1918  
1919 Synchronous wrapper around C<respond_f>.
1920  
1921 =head2 plugins
1922  
1923 my $raider = Langertha::Raider->new(
1924 plugins => ['Langfuse', 'MyApp::CustomPlugin'],
1925 engine => $engine,
1926 );
1927  
1928 Arrayref of plugin names or L<Langertha::Plugin> instances. Short names
1929 are resolved first to C<Langertha::Plugin::$name>, then to
1930 C<LangerthaX::Plugin::$name>. Fully qualified names (with C<::>) are
1931 used as-is.
1932  
1933 Plugin instances are created automatically with C<< raider => $self >>.
1934 Extra constructor arguments can be passed via C<_plugin_args>.
1935  
1936 =head1 SEE ALSO
1937  
1938 =over
1939  
1940 =item * L<Langertha::Role::Tools> - Lower-level single-turn tool calling
1941  
1942 =item * L<Langertha::Role::Langfuse> - Observability integration (used by Raider)
1943  
1944 =item * L<Langertha::Role::SystemPrompt> - Engine-level system prompt (Raider uses C<mission> instead)
1945  
1946 =item * L<Langertha::Plugin> - Base role and documentation for Raider plugins
1947  
1948 =back
1949  
1950 =head1 SUPPORT
1951  
1952 =head2 Issues
1953  
1954 Please report bugs and feature requests on GitHub at
1955 L<https://github.com/Getty/langertha/issues>.
1956  
1957 =head2 IRC
1958  
1959 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
1960  
1961 =head1 CONTRIBUTING
1962  
1963 Contributions are welcome! Please fork the repository and submit a pull request.
1964  
1965 =head1 AUTHOR
1966  
1967 Torsten Raudssus <getty@cpan.org>
1968  
1969 =head1 COPYRIGHT AND LICENSE
1970  
1971 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
1972  
1973 This is free software; you can redistribute it and/or modify it under
1974 the same terms as the Perl 5 programming language system itself.
1975  
1976 =cut
↑ Summary Langertha/Role/Chat.pm »