blib/lib/SignalWire/Agent/AgentBase.pm

filter: Statementstmt 86.4% 724 / 838 Branchbran 70.0% 199 / 284 Conditioncond 43.1% 100 / 232 MC/DCmcdc 20.3% 27 / 133 Subroutinesub 89.7% 123 / 137 Podpod 0.0% 0 / 67 totaltotal 69.3% 1173 / 1691 CC 247 SCAR 26.4
CC
247
Cov
76%
extract_sip_username
72.0
__ANON__
40.6
_handle_swaig
35.9
CRAP 14.0
« scripts/enumerate_surface.pl ↑ Summary blib/lib/SignalWire/Relay/Action.pm »
1 package SignalWire::Agent::AgentBase;
2 # Copyright (c) 2025 SignalWire
3 # Licensed under the MIT License.
4  
5 37 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 37 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 37 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 37 ▶use SignalWire::SWML::Service;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 37 extends 'SignalWire::SWML::Service';
10 37 ▶use JSON qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 37 ▶use MIME::Base64 qw(encode_base64 decode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 37 ▶use Digest::SHA qw(hmac_sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 37 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 37 ▶use Scalar::Util qw(blessed reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 37 ▶use Storable qw(dclone);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 37 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # ---------- attributes ----------
19  
20 # name, route, host, port, basic_auth_user, basic_auth_password, document,
21 # tools, tool_order, routing_callbacks are inherited from Service.
22 # Override AgentBase's defaults where they diverge from Service's:
23 55 ▶has '+name' => (default => sub { 'agent' });
Subroutine __ANON__: called CC=1 SCAR=0.0
24 409 ▶has '+port' => (default => sub { $ENV{PORT} || 3000 });
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"PORT"} or 3000 0 409 409
25 37 has '+basic_auth_user' => (
26 lazy => 1,
27 builder => '_build_basic_auth_user',
28 );
29 37 has '+basic_auth_password' => (
30 lazy => 1,
31 builder => '_build_basic_auth_password',
32 );
33  
34 # Call settings
35 409 ▶has auto_answer => (is => 'rw', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
36 408 ▶has record_call => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
37 410 ▶has record_format => (is => 'rw', default => sub { 'mp4' });
Subroutine __ANON__: called CC=1 SCAR=0.0
38 410 ▶has record_stereo => (is => 'rw', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
39  
40 # Prompt system
41 412 ▶has prompt_text => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
42 412 ▶has post_prompt => (is => 'rw', default => sub { '' });
Subroutine __ANON__: called CC=1 SCAR=0.0
43 406 ▶has use_pom => (is => 'rw', default => sub { 1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
44 412 ▶has pom_sections => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
45  
46 # Tool registry — `tools` and `tool_order` are now declared on Service
47 # (lifted so non-agent SWML services can host SWAIG functions). Inherited.
48  
49 # AI config
50 412 ▶has hints => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
51 412 ▶has pattern_hints => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
52 412 ▶has languages => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
53 412 ▶has pronunciations => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
54 412 ▶has params => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
55 412 ▶has global_data => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
56 412 ▶has native_functions => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
57  
58 # Internal settings
59 412 ▶has internal_fillers => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
60 412 ▶has debug_events_level => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
61  
62 # Includes and LLM params
63 412 ▶has function_includes => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
64 412 ▶has prompt_llm_params => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
65 412 ▶has post_prompt_llm_params => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
66  
67 # Verb insertion points
68 412 ▶has pre_answer_verbs => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
69 412 ▶has post_answer_verbs => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
70 412 ▶has post_ai_verbs => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
71 412 ▶has answer_config => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
72  
73 # Context system (lazy)
74 37 has context_builder => (
75 is => 'rw',
76 lazy => 1,
77 builder => '_build_context_builder',
78 );
79  
80 # Callbacks
81 415 ▶has dynamic_config_callback => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
82 415 ▶has summary_callback => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
83 415 ▶has debug_event_handler => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
84  
85 # URLs
86 412 ▶has webhook_url => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
87 412 ▶has post_prompt_url => (is => 'rw', default => sub { undef });
Subroutine __ANON__: called CC=1 SCAR=0.0
88 37 has proxy_url_base => (is => 'rw', lazy => 1, builder => '_build_proxy_url_base');
89 412 ▶has swaig_query_params => (is => 'rw', default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
90  
91 # Session manager (built in BUILD)
92 37 has session_manager => (is => 'rw');
93  
94 # Webhook signature validation. When set (or SIGNALWIRE_SIGNING_KEY env
95 # is non-empty), the PSGI app auto-mounts SignalWire::Security::WebhookMiddleware
96 # on POST /, POST /swaig, POST /post_prompt and rejects unsigned/invalid
97 # requests with 403. When unset, AgentBase logs a prominent startup
98 # warning the first time psgi_app is built.
99 37 has signing_key => (
100 is => 'rw',
101 lazy => 1,
102 builder => '_build_signing_key',
103 );
104  
105 22 ▶sub _build_signing_key {
Subroutine _build_signing_key: called CC=1 SCAR=0.0
106 22 my ($self) = @_;
107 22 return $ENV{SIGNALWIRE_SIGNING_KEY};
108 }
109  
110 # Skill manager
111 37 has skill_manager => (is => 'rw', lazy => 1, builder => '_build_skill_manager');
112  
113 # MCP integration
114 412 ▶has mcp_servers => (is => 'rw', default => sub { [] });
Subroutine __ANON__: called CC=1 SCAR=0.0
115 412 ▶has mcp_server_enabled => (is => 'rw', default => sub { 0 });
Subroutine __ANON__: called CC=1 SCAR=0.0
116  
117 # ---------- builders ----------
118  
119 69 ▶sub _build_basic_auth_user {
Subroutine _build_basic_auth_user: called CC=2 SCAR=7.1
120 69 my ($self) = @_;
121 69 ▶ return $ENV{SWML_BASIC_AUTH_USER} || $self->name;
Condition66%2/3
$ENV{'SWML_BASIC_AUTH_USER'} || $self->name
l!l&&r!l&&!r
2670
MC/DC0%0/2
$ENV{'SWML_BASIC_AUTH_USER'} || $self->name
$ENV{'SWML_BASIC_AUTH_USER'} $self->name
Truth table66%2/3
A || B
A= $ENV{'SWML_BASIC_AUTH_USER'}B= $self->name
ABresult
1X1
011
000
122 }
123  
124 69 ▶sub _build_basic_auth_password {
Subroutine _build_basic_auth_password: called CC=3 SCAR=11.2
125 69 my ($self) = @_;
126 69 ▶ return $ENV{SWML_BASIC_AUTH_PASSWORD} if $ENV{SWML_BASIC_AUTH_PASSWORD};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"SWML_BASIC_AUTH_PASSWORD"} 2 67 69
127  
128 67 my $password = _generate_random_password();
129 # Warn loudly so external callers (tests, RPC clients, MCP) know why
130 # they are getting HTTP 401. This is the silent cause of every
131 # external caller failing when .env wasn't loaded — the password
132 # lives only in this process and changes on every restart.
133 67 ▶ carp "basic_auth_password_autogenerated: username=\""
Condition33%1/3
$self->basic_auth_user || $self->name
l!l&&r!l&&!r
6700
MC/DC0%0/2
$self->basic_auth_user || $self->name
$self->basic_auth_user $self->name
Truth table33%1/3
A || B
A= $self->basic_auth_userB= $self->name
ABresult
1X1
011
000
134 . ($self->basic_auth_user || $self->name) . "\". "
135 . "No SWML_BASIC_AUTH_PASSWORD found in environment and no "
136 . "basic_auth_password passed to the agent constructor. The SDK "
137 . "generated a random password that exists only in this process; "
138 . "external callers will get HTTP 401 unless they read the value "
139 . "from this process's env. To fix, set SWML_BASIC_AUTH_USER and "
140 . "SWML_BASIC_AUTH_PASSWORD in your environment, or pass "
141 . "basic_auth_user => ... , basic_auth_password => ... to "
142 . "AgentBase->new(...).";
143 67 return $password;
144 }
145  
146 80 ▶sub _build_proxy_url_base {
Subroutine _build_proxy_url_base: called CC=2 SCAR=6.9
147 80 ▶ return $ENV{SWML_PROXY_URL_BASE} || undef;
Condition100%2/2
$ENV{'SWML_PROXY_URL_BASE'} || undef
l!l
179
MC/DC100%1/1
$ENV{'SWML_PROXY_URL_BASE'} || undef
$ENV{'SWML_PROXY_URL_BASE'}
Truth table100%2/2
A
A= $ENV{'SWML_PROXY_URL_BASE'}
Aresult
11
00
148 }
149  
150 74 ▶sub _build_context_builder {
Subroutine _build_context_builder: called CC=1 SCAR=0.0
151 74 require SignalWire::Contexts::ContextBuilder;
152 74 return SignalWire::Contexts::ContextBuilder->new;
153 }
154  
155 2 ▶sub _build_skill_manager {
Subroutine _build_skill_manager: called CC=1 SCAR=0.0
156 2 my ($self) = @_;
157 2 require SignalWire::Skills::SkillManager;
158 2 return SignalWire::Skills::SkillManager->new(agent => $self);
159 }
160  
161 415 ▶sub BUILD {
Subroutine BUILD: called CC=2 SCAR=6.9
Pod undocumented
162 415 my ($self) = @_;
163  
164 # Strip trailing slash from route
165 415 my $r = $self->route;
166 415 ▶ $r =~ s{/+$}{} if $r ne '/';
Branch: 1 branch
BranchTrueFalseTotal
if $r ne "/" 31 384 415
167 415 $self->route($r);
168  
169 # Initialize session manager
170 415 require SignalWire::Security::SessionManager;
171 415 $self->session_manager(
172 SignalWire::Security::SessionManager->new(token_expiry_secs => 3600)
173 );
174 }
175  
176 # ---------- Prompt methods ----------
177  
178 11 ▶sub set_prompt_text {
Subroutine set_prompt_text: called CC=1 SCAR=0.0
Pod undocumented
179 11 my ($self, $text) = @_;
180 11 $self->prompt_text($text);
181 11 return $self;
182 }
183  
184 6 ▶sub set_post_prompt {
Subroutine set_post_prompt: called CC=1 SCAR=0.0
Pod undocumented
185 6 my ($self, $text) = @_;
186 6 $self->post_prompt($text);
187 6 return $self;
188 }
189  
190 161 ▶sub prompt_add_section {
Subroutine prompt_add_section: called CC=3 SCAR=11.0
Pod undocumented
191 161 my ($self, $title, $body, %opts) = @_;
192 161 ▶ my $section = {
Condition100%2/2
$body // ""
l!l
1601
MC/DC100%1/1
$body // ""
$body
Truth table100%2/2
A
A= $body
Aresult
11
00
193 title => $title,
194 body => $body // '',
195 };
196 161 ▶ $section->{bullets} = $opts{bullets} if $opts{bullets};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"bullets"} 108 53 161
197 161 push @{ $self->pom_sections }, $section;
198 161 return $self;
199 }
200  
201 7 ▶sub prompt_add_subsection {
Subroutine prompt_add_subsection: called CC=6 SCAR=18.0
Pod undocumented
202 7 my ($self, $parent_title, $title, $body, %opts) = @_;
203 7 for my $sec (@{ $self->pom_sections }) {
204 6 ▶ if ($sec->{title} eq $parent_title) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sec->{"title"} eq $parent_title) 6 0 6
205 6 ▶ $sec->{subsections} //= [];
Condition100%2/2
$sec->{"subsections"} //= []
l!l
15
MC/DC100%1/1
$sec->{"subsections"} //= []
$sec->{"subsections"}
Truth table100%2/2
A
A= $sec->{"subsections"}
Aresult
11
00
206 6 ▶ my $sub = { title => $title, body => $body // '' };
Condition50%1/2
$body // ""
l!l
60
MC/DC0%0/1
$body // ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
207 6 ▶ $sub->{bullets} = $opts{bullets} if $opts{bullets};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"bullets"} 2 4 6
208 6 push @{ $sec->{subsections} }, $sub;
209 6 last;
210 }
211 }
212 7 return $self;
213 }
214  
215 5 ▶sub prompt_add_to_section {
Subroutine prompt_add_to_section: called CC=6 SCAR=17.9
Pod undocumented
216 5 my ($self, $title, %opts) = @_;
217 5 for my $sec (@{ $self->pom_sections }) {
218 5 ▶ if ($sec->{title} eq $title) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sec->{"title"} eq $title) 5 0 5
219 5 ▶ if ($opts{body}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"body"}) 1 4 5
220 1 $sec->{body} .= "\n" . $opts{body};
221 }
222 5 ▶ if ($opts{bullets}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"bullets"}) 4 1 5
223 4 ▶ $sec->{bullets} //= [];
Condition100%2/2
$sec->{"bullets"} //= []
l!l
22
MC/DC100%1/1
$sec->{"bullets"} //= []
$sec->{"bullets"}
Truth table100%2/2
A
A= $sec->{"bullets"}
Aresult
11
00
224 4 push @{ $sec->{bullets} }, @{ $opts{bullets} };
225 }
226 5 last;
227 }
228 }
229 5 return $self;
230 }
231  
232 35 ▶sub prompt_has_section {
Subroutine prompt_has_section: called CC=3 SCAR=11.0
Pod undocumented
233 35 my ($self, $title) = @_;
234 35 for my $sec (@{ $self->pom_sections }) {
235 65 ▶ return 1 if $sec->{title} eq $title;
Branch: 1 branch
BranchTrueFalseTotal
if $sec->{"title"} eq $title 28 37 65
236 }
237 7 return 0;
238 }
239  
240 77 ▶sub get_prompt {
Subroutine get_prompt: called CC=3 SCAR=11.0
Pod undocumented
241 77 my ($self) = @_;
242 77 ▶ if ($self->use_pom && @{ $self->pom_sections }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->use_pom and @{$self->pom_sections;}) 24 53 77
Condition100%3/3
$self->use_pom and @{$self->pom_sections;}
!ll&&!rl&&r
54824
MC/DC100%2/2
$self->use_pom and @{$self->pom_sections;}
$self->use_pom @{$self->pom_sections;}
Truth table100%3/3
A and B
A= $self->use_pomB= @{$self->pom_sections;}
ABresult
0X0
100
111
243 24 return $self->pom_sections;
244 }
245 53 return $self->prompt_text;
246 }
247  
248 # Read-only snapshot of the agent's POM as a typed
249 # SignalWire::POM::PromptObjectModel object.
250 #
251 # Python parity: ``agent.pom`` instance attribute (agent_base.py
252 # line 209) — Python returns a PromptObjectModel instance built from
253 # ``pom_sections`` (or None when ``use_pom`` is false). This Perl port
254 # mirrors that contract: undef when use_pom is off, otherwise a fresh
255 # PromptObjectModel constructed from a deep-cloned copy of the
256 # internal section list so caller mutations cannot leak back.
257 4 ▶sub pom {
Subroutine pom: called CC=3 SCAR=11.0
Pod undocumented
258 4 my ($self) = @_;
259 4 ▶ return undef unless $self->use_pom;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->use_pom 1 3 4
260 3 require Storable;
261 3 require SignalWire::POM::PromptObjectModel;
262 3 my $cloned = Storable::dclone($self->pom_sections);
263 # Empty pom_sections still returns a PromptObjectModel (Python
264 # parity: ``self.pom = PromptObjectModel()`` even when no sections
265 # have been added).
266 3 ▶ return SignalWire::POM::PromptObjectModel->new if !@$cloned;
Branch: 1 branch
BranchTrueFalseTotal
unless @$cloned 0 3 3
267 3 return SignalWire::POM::PromptObjectModel->_from_data($cloned);
268 }
269  
270 # Returns the post-prompt text whatever set_post_prompt stored, or
271 # the empty string when none has been set.
272 #
273 # Mirrors Python's PromptManager.get_post_prompt /
274 # PromptMixin.get_post_prompt — used by SWML rendering when a
275 # post-prompt is configured.
276 0 ▶sub get_post_prompt {
Subroutine get_post_prompt: not called CC=1 SCAR=6.9
Pod undocumented
277 0 my ($self) = @_;
278 0 return $self->post_prompt;
279 }
280  
281 # Returns the raw prompt text whatever set_prompt_text stored, or the
282 # empty string when no raw prompt has been set. Distinct from
283 # get_prompt which may return the POM array when use_pom is true.
284 #
285 # Mirrors Python's PromptManager.get_raw_prompt.
286 0 ▶sub get_raw_prompt {
Subroutine get_raw_prompt: not called CC=1 SCAR=6.9
Pod undocumented
287 0 my ($self) = @_;
288 0 return $self->prompt_text;
289 }
290  
291 # Sets the prompt as a list of POM section hashes. Each section hash
292 # supports keys "title", "body", "bullets", "numbered",
293 # "numbered_bullets", and "subsections". Switches the agent to POM
294 # mode.
295 #
296 # Mirrors Python's PromptManager.set_prompt_pom — accepts a list of
297 # section dicts and stores them in pom_sections.
298 0 ▶sub set_prompt_pom {
Subroutine set_prompt_pom: not called CC=2 SCAR=17.9
Pod undocumented
299 0 my ($self, $pom) = @_;
300 0 $self->use_pom(1);
301 0 ▶ $pom //= [];
Condition0%0/2
$pom //= []
l!l
00
MC/DC0%0/1
$pom //= []
$pom
Truth table0%0/2
A
A= $pom
Aresult
11
00
302 0 $self->pom_sections([ @$pom ]);
303 0 return $self;
304 }
305  
306 # Returns the contexts dictionary as a hashref of serialised SWML, or
307 # undef when no contexts have been defined yet.
308 #
309 # Mirrors Python's PromptManager.get_contexts which returns the
310 # contexts dict or None.
311 0 ▶sub get_contexts {
Subroutine get_contexts: not called CC=2 SCAR=17.9
Pod undocumented
312 0 my ($self) = @_;
313 0 my $cb = $self->context_builder;
314 0 ▶ return undef unless defined $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cb 0 0 0
315 0 return $cb->to_hash;
316 }
317  
318 # ---------- Tool methods ----------
319  
320 #
321 # define_tool — register a SWAIG tool (function) that the AI can invoke
322 # during a call.
323 #
324 # HOW THIS BECOMES A TOOL THE MODEL SEES
325 #
326 # A SWAIG function is EXACTLY THE SAME CONCEPT as a "tool" in native
327 # OpenAI / Anthropic tool calling. On every LLM turn, the SDK renders
328 # each registered SWAIG function into the OpenAI tool schema:
329 #
330 # {
331 # "type": "function",
332 # "function": {
333 # "name": "your_name_here",
334 # "description": "your description text",
335 # "parameters": { ... your JSON schema ... }
336 # }
337 # }
338 #
339 # That schema is sent to the model as part of the same API call that
340 # produces the next assistant message. The model reads:
341 #
342 # - the function `description` to decide WHEN to call this tool
343 # - each parameter `description` (inside parameters) to decide HOW
344 # to fill in that argument from the user's utterance
345 #
346 # This means DESCRIPTIONS ARE PROMPT ENGINEERING, not developer
347 # comments. A vague description is the #1 cause of "the model has the
348 # right tool but doesn't call it" failures.
349 #
350 # BAD vs GOOD descriptions:
351 #
352 # BAD : description => 'Lookup function'
353 # GOOD: description => 'Look up a customer\'s account details by '
354 # . 'account number. Use this BEFORE quoting any '
355 # . 'account-specific info (balance, plan, '
356 # . 'status). Do not use for general product '
357 # . 'questions.'
358 #
359 # BAD : parameters => { id => { type=>'string', description=>'the id' } }
360 # GOOD: parameters => { account_number => { type=>'string',
361 # description => 'The customer\'s 8-digit account number, '
362 # . 'no dashes or spaces. Ask the user if they '
363 # . 'don\'t provide it.' } }
364 #
365 # TOOL COUNT MATTERS: LLM tool selection accuracy degrades past ~7-8
366 # simultaneously-active tools per call. Use Step->set_functions() to
367 # partition tools across steps so only the relevant subset is active at
368 # any moment. See SignalWire::Contexts.
369 #
370 # define_tool, register_swaig_function, define_tools, on_function_call are
371 # provided by SignalWire::SWML::Service (parent). Inherited via `extends`.
372  
373 # Mint a per-call SWAIG-function token via the agent's SessionManager.
374 #
375 # Python parity: state_mixin.StateMixin._create_tool_token —
376 # delegates to SessionManager->create_tool_token and returns "" on any
377 # raised error (Python catches all exceptions and returns "").
378 2 ▶sub create_tool_token {
Subroutine create_tool_token: called CC=2 SCAR=7.1
Pod undocumented
379 2 my ($self, $tool_name, $call_id) = @_;
380 2 my $token = '';
381 eval {
382 2 $token = $self->session_manager->create_tool_token($tool_name, $call_id);
383 2 1;
384 2 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $token = $self->session_manager->create_tool_token($tool_name, $call_id); 1 } } or do { return "" } 2 0 2
385 0 return '';
386 };
387 2 return $token;
388 }
389  
390 # Validate a per-call SWAIG-function token. Returns false (0) when the
391 # function is not registered, when the SessionManager rejects the token,
392 # or on any underlying exception.
393 #
394 # Python parity: state_mixin.StateMixin.validate_tool_token —
395 # rejects unknown function names up-front and swallows errors.
396 4 ▶sub validate_tool_token {
Subroutine validate_tool_token: called CC=4 SCAR=14.0
Pod undocumented
397 4 my ($self, $function_name, $token, $call_id) = @_;
398 4 ▶ return 0 unless $self->has_function($function_name);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_function($function_name) 1 3 4
399 3 my $result = 0;
400 eval {
401 # Note: Perl SessionManager's validate_token signature is
402 # (call_id, function_name, token), not the Python order. The
403 # AgentBase facade keeps the Python order so callers can write
404 # the same code across languages.
405 3 $result = $self->session_manager->validate_token($call_id, $function_name, $token);
406 3 1;
407 3 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $result = $self->session_manager->validate_token($call_id, $function_name, $token); 1 } } or do { return 0 } 3 0 3
408 0 return 0;
409 };
410 3 ▶ return $result ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$result ? : 1 2 3
411 }
412  
413 # ---------- AI Config methods ----------
414  
415 10 ▶sub add_hint {
Subroutine add_hint: called CC=1 SCAR=0.0
Pod undocumented
416 10 my ($self, $hint) = @_;
417 10 push @{ $self->hints }, $hint;
418 10 return $self;
419 }
420  
421 7 ▶sub add_hints {
Subroutine add_hints: called CC=10 SCAR=23.9
Pod undocumented
422 7 my ($self, $hints) = @_;
423 # Python parity: add_hints(hints: List[str]). Accept an arrayref
424 # as the canonical form. Backward-compat: also accept slurpy
425 # (``add_hints('a', 'b', 'c')``) when the first arg is a string.
426 7 ▶ if (ref $hints eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $hints eq 'ARRAY') { } 3 4 7
427 3 for my $h (@$hints) {
428 7 ▶ push @{ $self->hints }, $h if defined $h && !ref($h) && length $h;
Branch: 1 branch
BranchTrueFalseTotal
if defined $h and not ref $h and length $h 5 2 7
Condition83%5/6
defined $h and not ref $h and length $h
!ll&&!rl&&r
115
defined $h and not ref $h
!ll&&!rl&&r
106
MC/DC66%2/3
defined $h and not ref $h and length $h
defined $h not ref $h length $h
Truth table75%3/4
A and not(B) and C
A= defined $hB= not ref $hC= length $h
ABCresult
0XX0
10X0
1100
1111
429 }
430 } else {
431 # Slurpy form — re-grab @_ skipping $self.
432 4 my @rest = @_;
433 4 shift @rest;
434 4 for my $h (@rest) {
435 13 ▶ push @{ $self->hints }, $h if defined $h && !ref($h) && length $h;
Branch: 1 branch
BranchTrueFalseTotal
if defined $h and not ref $h and length $h 13 0 13
Condition33%2/6
defined $h and not ref $h and length $h
!ll&&!rl&&r
0013
defined $h and not ref $h
!ll&&!rl&&r
0013
MC/DC0%0/3
defined $h and not ref $h and length $h
defined $h not ref $h length $h
Truth table25%1/4
A and not(B) and C
A= defined $hB= not ref $hC= length $h
ABCresult
0XX0
10X0
1100
1111
436 }
437 }
438 7 return $self;
439 }
440  
441 1 ▶sub add_pattern_hint {
Subroutine add_pattern_hint: called CC=1 SCAR=0.0
Pod undocumented
442 1 my ($self, $pattern) = @_;
443 1 push @{ $self->pattern_hints }, $pattern;
444 1 return $self;
445 }
446  
447 15 ▶sub add_language {
Subroutine add_language: called CC=5 SCAR=16.3
Pod undocumented
448 15 my ($self, %lang) = @_;
449 # Per-language params (engine-specific tuning, voice settings, etc.).
450 # Python parity (commit 029ca6f): only emit the ``params`` key when
451 # the supplied hashref is non-empty so SWML stays byte-identical for
452 # existing callers who don't pass params. Treat an explicit empty
453 # hashref the same as "not passed".
454 15 ▶ if (exists $lang{params}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $lang{"params"}) 6 9 15
455 6 my $p = $lang{params};
456 6 ▶ if (!defined $p || ref($p) ne 'HASH' || !%$p) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $p or ref $p ne "HASH" or not %$p) 1 5 6
Condition50%3/6
not defined $p or ref $p ne "HASH" or not %$p
l!l&&r!l&&!r
015
not defined $p or ref $p ne "HASH"
l!l&&r!l&&!r
006
MC/DC33%1/3
not defined $p or ref $p ne "HASH" or not %$p
not defined $p ref $p ne "HASH" not %$p
Truth table50%2/4
not(A) or B or not(C)
A= not defined $pB= ref $p ne "HASH"C= not %$p
ABCresult
1XX1
01X1
0011
0000
457 1 delete $lang{params};
458 }
459 }
460 15 push @{ $self->languages }, \%lang;
461 15 return $self;
462 }
463  
464 1 ▶sub set_languages {
Subroutine set_languages: called CC=1 SCAR=0.0
Pod undocumented
465 1 my ($self, $langs) = @_;
466 1 $self->languages($langs);
467 1 return $self;
468 }
469  
470 # Set (or replace) the per-language ``params`` hashref on an
471 # already-added language. Python parity (commit 029ca6f): empty hashref
472 # removes the key; unknown ``code`` is a no-op; always returns $self
473 # for chaining.
474 5 ▶sub set_language_params {
Subroutine set_language_params: called CC=7 SCAR=19.9
Pod undocumented
475 5 my ($self, $code, $params) = @_;
476 5 for my $language (@{ $self->languages }) {
477 5 ▶ next unless defined $language->{code} && $language->{code} eq $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $language->{"code"} and $language->{"code"} eq $code 1 4 5
Condition66%2/3
defined $language->{"code"} and $language->{"code"} eq $code
!ll&&!rl&&r
014
MC/DC50%1/2
defined $language->{"code"} and $language->{"code"} eq $code
defined $language->{"code"} $language->{"code"} eq $code
Truth table66%2/3
A and B
A= defined $language->{"code"}B= $language->{"code"} eq $code
ABresult
0X0
100
111
478 4 ▶ if (defined $params && ref($params) eq 'HASH' && %$params) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params and ref $params eq 'HASH' and %$params) { } 3 1 4
Condition50%3/6
defined $params and ref $params eq "HASH" and %$params
!ll&&!rl&&r
013
defined $params and ref $params eq "HASH"
!ll&&!rl&&r
004
MC/DC33%1/3
defined $params and ref $params eq "HASH" and %$params
defined $params ref $params eq "HASH" %$params
Truth table50%2/4
A and B and C
A= defined $paramsB= ref $params eq "HASH"C= %$params
ABCresult
0XX0
10X0
1100
1111
479 3 $language->{params} = $params;
480 } else {
481 1 delete $language->{params};
482 }
483 4 last;
484 }
485 5 return $self;
486 }
487  
488 # Read the per-language ``params`` hashref for a previously-added
489 # language. Returns undef when the code is unknown or when params were
490 # never set — no exception path (matches Python's ``return None``).
491 7 ▶sub get_language_params {
Subroutine get_language_params: called CC=4 SCAR=14.6
Pod undocumented
492 7 my ($self, $code) = @_;
493 7 for my $language (@{ $self->languages }) {
494 6 ▶ next unless defined $language->{code} && $language->{code} eq $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $language->{"code"} and $language->{"code"} eq $code 0 6 6
Condition33%1/3
defined $language->{"code"} and $language->{"code"} eq $code
!ll&&!rl&&r
006
MC/DC0%0/2
defined $language->{"code"} and $language->{"code"} eq $code
defined $language->{"code"} $language->{"code"} eq $code
Truth table33%1/3
A and B
A= defined $language->{"code"}B= $language->{"code"} eq $code
ABresult
0X0
100
111
495 6 return $language->{params};
496 }
497 1 return undef;
498 }
499  
500 4 ▶sub add_pronunciation {
Subroutine add_pronunciation: called CC=1 SCAR=0.0
Pod undocumented
501 4 my ($self, %pron) = @_;
502 4 push @{ $self->pronunciations }, \%pron;
503 4 return $self;
504 }
505  
506 1 ▶sub set_pronunciations {
Subroutine set_pronunciations: called CC=1 SCAR=0.0
Pod undocumented
507 1 my ($self, $prons) = @_;
508 1 $self->pronunciations($prons);
509 1 return $self;
510 }
511  
512 7 ▶sub set_param {
Subroutine set_param: called CC=1 SCAR=0.0
Pod undocumented
513 7 my ($self, $key, $value) = @_;
514 7 $self->params->{$key} = $value;
515 7 return $self;
516 }
517  
518 2 ▶sub set_params {
Subroutine set_params: called CC=1 SCAR=0.0
Pod undocumented
519 2 my ($self, $p) = @_;
520 2 $self->params({ %{ $self->params }, %$p });
521 2 return $self;
522 }
523  
524 66 ▶sub set_global_data {
Subroutine set_global_data: called CC=1 SCAR=0.0
Pod undocumented
525 66 my ($self, $data) = @_;
526 66 $self->global_data($data);
527 66 return $self;
528 }
529  
530 3 ▶sub update_global_data {
Subroutine update_global_data: called CC=1 SCAR=0.0
Pod undocumented
531 3 my ($self, $data) = @_;
532 3 $self->global_data({ %{ $self->global_data }, %$data });
533 3 return $self;
534 }
535  
536 5 ▶sub set_native_functions {
Subroutine set_native_functions: called CC=1 SCAR=0.0
Pod undocumented
537 5 my ($self, $funcs) = @_;
538 5 $self->native_functions($funcs);
539 5 return $self;
540 }
541  
542 #
543 # The complete set of internal SWAIG function names that accept fillers,
544 # matching the SWAIGInternalFiller schema definition. Any name outside
545 # this set is silently ignored by the runtime — set_internal_fillers and
546 # add_internal_filler warn if you pass an unknown name.
547 #
548 # Notable absences: change_step, gather_submit, and arbitrary user-defined
549 # SWAIG function names are NOT supported.
550 #
551 37 our %SUPPORTED_INTERNAL_FILLER_NAMES = (
552 hangup => 1, # AI is hanging up the call
553 check_time => 1, # AI is checking the time
554 wait_for_user => 1, # AI is waiting for user input
555 wait_seconds => 1, # deliberate pause / wait period
556 adjust_response_latency => 1, # AI is adjusting response timing
557 next_step => 1, # transitioning between steps in prompt.contexts
558 change_context => 1, # switching between contexts in prompt.contexts
559 get_visual_input => 1, # processing visual input (enable_vision)
560 get_ideal_strategy => 1, # thinking (enable_thinking)
561 );
562  
563 #
564 # set_internal_fillers — set internal fillers for native SWAIG functions.
565 #
566 # Internal fillers are short phrases the AI agent speaks (via TTS) while
567 # an internal/native function is running, so the caller doesn't hear
568 # dead air during transitions or background work.
569 #
570 # Supported function names (match the SWAIGInternalFiller schema):
571 # hangup, check_time, wait_for_user, wait_seconds,
572 # adjust_response_latency, next_step, change_context,
573 # get_visual_input, get_ideal_strategy
574 #
575 # Notably NOT supported: change_step, gather_submit, or arbitrary
576 # user-defined SWAIG function names. The runtime only honors fillers for
577 # the names listed above; everything else is silently ignored at the
578 # SWML level. This method warns at registration time if you pass an
579 # unknown name so you catch the typo early.
580 #
581 # Expected format:
582 # { function_name => { language_code => [ phrase1, phrase2, ... ] } }
583 #
584 3 ▶sub set_internal_fillers {
Subroutine set_internal_fillers: called CC=3 SCAR=17.3
Pod undocumented
585 3 my ($self, $fillers) = @_;
586 3 ▶ if (ref $fillers eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fillers eq "HASH") 0 3 3
587 0 my @unknown = sort grep { !exists $SUPPORTED_INTERNAL_FILLER_NAMES{$_} }
588 keys %$fillers;
589 0 ▶ if (@unknown) {
Branch: 1 branch
BranchTrueFalseTotal
if (@unknown) 0 0 0
590 0 my @supported = sort keys %SUPPORTED_INTERNAL_FILLER_NAMES;
591 carp "unknown_internal_filler_names: ["
592 0 . join(', ', map { "'$_'" } @unknown)
593 . "]. set_internal_fillers received names that the SWML "
594 . "schema does not recognize. Those entries will be "
595 . "ignored by the runtime. Supported names: ["
596 0 . join(', ', map { "'$_'" } @supported) . "].";
597 }
598 }
599 3 $self->internal_fillers($fillers);
600 3 return $self;
601 }
602  
603 #
604 # add_internal_filler — add a single internal filler entry.
605 #
606 # See set_internal_fillers for the complete list of supported internal
607 # function names and what fillers do. Calling with a function name
608 # outside the supported set logs a warning but the entry is still stored.
609 #
610 # Three calling conventions are supported:
611 #
612 # $agent->add_internal_filler('plain text') # legacy: raw scalar
613 # $agent->add_internal_filler({ ... }) # legacy: raw hashref
614 # $agent->add_internal_filler($function_name, $lang_code, \@phrases)
615 #
616 2 ▶sub add_internal_filler {
Subroutine add_internal_filler: called CC=8 SCAR=32.6
Pod undocumented
617 2 my ($self, @args) = @_;
618  
619 # Legacy forms: single scalar or single hashref — preserve existing
620 # behavior (push onto the flat arrayref).
621 2 ▶ if (@args == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1) 2 0 2
622 2 my $filler = $args[0];
623 2 ▶ if (!defined $self->internal_fillers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->internal_fillers) 1 1 2
624 1 $self->internal_fillers([]);
625 }
626 2 my $store = $self->internal_fillers;
627 2 ▶ push @$store, $filler if ref $store eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $store eq "ARRAY" 2 0 2
628 2 return $self;
629 }
630  
631 # New form: (function_name, language_code, fillers_arrayref)
632 0 my ($function_name, $language_code, $fillers) = @args;
633 0 ▶ if (!exists $SUPPORTED_INTERNAL_FILLER_NAMES{$function_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $SignalWire::Agent::AgentBase::SUPPORTED_INTERNAL_FILLER_NAMES{$function_name}) 0 0 0
634 0 my @supported = sort keys %SUPPORTED_INTERNAL_FILLER_NAMES;
635 carp "unknown_internal_filler_name: '$function_name'. "
636 . "add_internal_filler received a function name the SWML "
637 . "schema does not recognize. The entry will be stored but "
638 . "the runtime will not play these fillers. Supported "
639 0 . "names: [" . join(', ', map { "'$_'" } @supported) . "].";
640 }
641 # Initialise as a hashref if empty or legacy list.
642 0 my $store = $self->internal_fillers;
643 0 ▶ if (!defined $store || ref $store ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $store or ref $store ne "HASH") 0 0 0
Condition0%0/3
not defined $store or ref $store ne "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $store or ref $store ne "HASH"
not defined $store ref $store ne "HASH"
Truth table0%0/3
not(A) or B
A= not defined $storeB= ref $store ne "HASH"
ABresult
1X1
011
000
644 0 $store = {};
645 0 $self->internal_fillers($store);
646 }
647 0 ▶ $store->{$function_name} //= {};
Condition0%0/2
$store->{$function_name} //= {}
l!l
00
MC/DC0%0/1
$store->{$function_name} //= {}
$store->{$function_name}
Truth table0%0/2
A
A= $store->{$function_name}
Aresult
11
00
648 0 $store->{$function_name}{$language_code} = $fillers;
649 0 return $self;
650 }
651  
652 5 ▶sub enable_debug_events {
Subroutine enable_debug_events: called CC=2 SCAR=6.9
Pod undocumented
653 5 my ($self, $level) = @_;
654 5 ▶ $level //= 1;
Condition100%2/2
$level //= 1
l!l
41
MC/DC100%1/1
$level //= 1
$level
Truth table100%2/2
A
A= $level
Aresult
11
00
655 5 $self->debug_events_level($level);
656 5 return $self;
657 }
658  
659 3 ▶sub add_function_include {
Subroutine add_function_include: called CC=1 SCAR=0.0
Pod undocumented
660 3 my ($self, $include) = @_;
661 3 push @{ $self->function_includes }, $include;
662 3 return $self;
663 }
664  
665 0 ▶sub set_function_includes {
Subroutine set_function_includes: not called CC=1 SCAR=6.9
Pod undocumented
666 0 my ($self, $includes) = @_;
667 0 $self->function_includes($includes);
668 0 return $self;
669 }
670  
671 8 ▶sub set_prompt_llm_params {
Subroutine set_prompt_llm_params: called CC=1 SCAR=0.0
Pod undocumented
672 8 my ($self, %p) = @_;
673 8 $self->prompt_llm_params({ %{ $self->prompt_llm_params }, %p });
674 8 return $self;
675 }
676  
677 4 ▶sub set_post_prompt_llm_params {
Subroutine set_post_prompt_llm_params: called CC=1 SCAR=0.0
Pod undocumented
678 4 my ($self, %p) = @_;
679 4 $self->post_prompt_llm_params({ %{ $self->post_prompt_llm_params }, %p });
680 4 return $self;
681 }
682  
683 # ---------- Verb management ----------
684  
685 10 ▶sub add_pre_answer_verb {
Subroutine add_pre_answer_verb: called CC=1 SCAR=0.0
Pod undocumented
686 10 my ($self, $verb_name, $verb_config) = @_;
687 10 push @{ $self->pre_answer_verbs }, { $verb_name => $verb_config };
688 10 return $self;
689 }
690  
691 8 ▶sub add_post_answer_verb {
Subroutine add_post_answer_verb: called CC=1 SCAR=0.0
Pod undocumented
692 8 my ($self, $verb_name, $verb_config) = @_;
693 8 push @{ $self->post_answer_verbs }, { $verb_name => $verb_config };
694 8 return $self;
695 }
696  
697 8 ▶sub add_post_ai_verb {
Subroutine add_post_ai_verb: called CC=1 SCAR=0.0
Pod undocumented
698 8 my ($self, $verb_name, $verb_config) = @_;
699 8 push @{ $self->post_ai_verbs }, { $verb_name => $verb_config };
700 8 return $self;
701 }
702  
703 2 ▶sub clear_pre_answer_verbs {
Subroutine clear_pre_answer_verbs: called CC=1 SCAR=0.0
Pod undocumented
704 2 my ($self) = @_;
705 2 $self->pre_answer_verbs([]);
706 2 return $self;
707 }
708  
709 2 ▶sub clear_post_answer_verbs {
Subroutine clear_post_answer_verbs: called CC=1 SCAR=0.0
Pod undocumented
710 2 my ($self) = @_;
711 2 $self->post_answer_verbs([]);
712 2 return $self;
713 }
714  
715 2 ▶sub clear_post_ai_verbs {
Subroutine clear_post_ai_verbs: called CC=1 SCAR=0.0
Pod undocumented
716 2 my ($self) = @_;
717 2 $self->post_ai_verbs([]);
718 2 return $self;
719 }
720  
721 1 ▶sub set_answer_config {
Subroutine set_answer_config: called CC=1 SCAR=0.0
Pod undocumented
722 1 my ($self, $config) = @_;
723 1 $self->answer_config($config);
724 1 return $self;
725 }
726  
727 # ---------- Contexts ----------
728  
729 #
730 # define_contexts — return this agent's ContextBuilder, attaching the
731 # agent so that ContextBuilder->validate can check user-defined tool
732 # names against reserved native tool names (next_step, change_context,
733 # gather_submit). See SignalWire::Contexts::ContextBuilder.
734 #
735 4 ▶sub define_contexts {
Subroutine define_contexts: called CC=13 SCAR=27.4
Pod undocumented
736 4 my ($self, $contexts) = @_;
737 # Python parity: PromptMixin.define_contexts(contexts=None).
738 # - When called with no arg (legacy / Perl idiom), returns the
739 # ContextBuilder for fluent chaining (``$agent->define_contexts->add_context(...)``).
740 # - When called with a hashref or ContextBuilder, applies that
741 # configuration via context_builder and returns $self for chaining.
742 4 ▶ if (defined $contexts) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $contexts) 2 2 4
743 2 ▶ if (ref $contexts eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $contexts eq "HASH") 1 1 2
744 # Apply each top-level context name -> config pair.
745 1 my $cb = $self->context_builder;
746 1 ▶ $cb->attach_agent($self) if $cb->can('attach_agent');
Branch: 1 branch
BranchTrueFalseTotal
if $cb->can("attach_agent") 1 0 1
747 1 for my $name (keys %$contexts) {
748 1 my $cfg = $contexts->{$name};
749 1 my $ctx = $cb->add_context($name);
750 # Best-effort: if config is a hashref, apply known keys.
751 1 ▶ if (ref $cfg eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cfg eq "HASH") 1 0 1
752 1 ▶ if (defined $cfg->{steps} && ref $cfg->{steps} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cfg->{"steps"} and ref $cfg->{"steps"} eq "HASH") 1 0 1
Condition33%1/3
defined $cfg->{"steps"} and ref $cfg->{"steps"} eq "HASH"
!ll&&!rl&&r
001
MC/DC0%0/2
defined $cfg->{"steps"} and ref $cfg->{"steps"} eq "HASH"
defined $cfg->{"steps"} ref $cfg->{"steps"} eq "HASH"
Truth table33%1/3
A and B
A= defined $cfg->{"steps"}B= ref $cfg->{"steps"} eq "HASH"
ABresult
0X0
100
111
753 1 for my $sname (keys %{ $cfg->{steps} }) {
754 1 $ctx->add_step($sname, %{ $cfg->{steps}{$sname} });
755 }
756 }
757 }
758 }
759 1 return $self;
760 }
761 # ContextBuilder-like object: assume $contexts->to_hash is the
762 # canonical projection; replace this agent's builder with it.
763 1 ▶ if (ref $contexts && $contexts->can('to_hash')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $contexts and $contexts->can("to_hash")) 1 0 1
Condition33%1/3
ref $contexts and $contexts->can("to_hash")
!ll&&!rl&&r
001
MC/DC0%0/2
ref $contexts and $contexts->can("to_hash")
ref $contexts $contexts->can("to_hash")
Truth table33%1/3
A and B
A= ref $contextsB= $contexts->can("to_hash")
ABresult
0X0
100
111
764 1 $self->{_external_context_builder} = $contexts;
765 1 ▶ $contexts->attach_agent($self) if $contexts->can('attach_agent');
Branch: 1 branch
BranchTrueFalseTotal
if $contexts->can("attach_agent") 1 0 1
766 1 return $self;
767 }
768 0 die "define_contexts: contexts must be a hashref or a ContextBuilder";
769 }
770 # No-arg form: return the (memoized) ContextBuilder.
771 2 my $cb = $self->context_builder;
772 2 ▶ $cb->attach_agent($self) if $cb->can('attach_agent');
Branch: 1 branch
BranchTrueFalseTotal
if $cb->can("attach_agent") 2 0 2
773 2 return $cb;
774 }
775  
776 #
777 # reset_contexts — remove all contexts, returning the agent to a
778 # no-contexts state. Convenience wrapper around
779 # define_contexts()->reset(). Use in a dynamic config callback when
780 # you need to rebuild contexts from scratch for a specific request.
781 #
782 0 ▶sub reset_contexts {
Subroutine reset_contexts: not called CC=2 SCAR=17.9
Pod undocumented
783 0 my ($self) = @_;
784 0 ▶ if ($self->context_builder->can('reset')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->context_builder->can("reset")) 0 0 0
785 0 $self->context_builder->reset;
786 }
787 0 return $self;
788 }
789  
790 #
791 # list_tool_names — return the names of every registered SWAIG tool in
792 # insertion order. Used by SignalWire::Contexts::ContextBuilder->validate
793 # to detect collisions with reserved native tool names.
794 #
795 1 ▶sub list_tool_names {
Subroutine list_tool_names: called CC=1 SCAR=0.0
Pod undocumented
796 1 my ($self) = @_;
797 1 return @{ $self->tool_order };
798 }
799  
800 0 ▶sub contexts {
Subroutine contexts: not called CC=1 SCAR=6.9
Pod undocumented
801 0 my ($self) = @_;
802 0 return $self->context_builder;
803 }
804  
805 # ---------- Skills ----------
806  
807 2 ▶sub add_skill {
Subroutine add_skill: called CC=2 SCAR=7.1
Pod undocumented
808 2 my ($self, $skill_name, $params) = @_;
809 2 ▶ $params //= {};
Condition50%1/2
$params //= {}
l!l
02
MC/DC0%0/1
$params //= {}
$params
Truth table50%1/2
A
A= $params
Aresult
11
00
810 2 return $self->skill_manager->load_skill($skill_name, undef, $params);
811 }
812  
813 0 ▶sub remove_skill {
Subroutine remove_skill: not called CC=1 SCAR=6.9
Pod undocumented
814 0 my ($self, $skill_name) = @_;
815 0 return $self->skill_manager->unload_skill($skill_name);
816 }
817  
818 0 ▶sub list_skills {
Subroutine list_skills: not called CC=1 SCAR=6.9
Pod undocumented
819 0 my ($self) = @_;
820 0 return $self->skill_manager->list_skills;
821 }
822  
823 1 ▶sub has_skill {
Subroutine has_skill: called CC=1 SCAR=0.0
Pod undocumented
824 1 my ($self, $skill_name) = @_;
825 1 return $self->skill_manager->has_skill($skill_name);
826 }
827  
828 # ---------- Web / callback setters ----------
829  
830 3 ▶sub set_dynamic_config_callback {
Subroutine set_dynamic_config_callback: called CC=1 SCAR=0.0
Pod undocumented
831 3 my ($self, $cb) = @_;
832 3 $self->dynamic_config_callback($cb);
833 3 return $self;
834 }
835  
836 3 ▶sub set_web_hook_url {
Subroutine set_web_hook_url: called CC=1 SCAR=0.0
Pod undocumented
837 3 my ($self, $url) = @_;
838 3 $self->webhook_url($url);
839 3 return $self;
840 }
841  
842 2 ▶sub set_post_prompt_url {
Subroutine set_post_prompt_url: called CC=1 SCAR=0.0
Pod undocumented
843 2 my ($self, $url) = @_;
844 2 $self->post_prompt_url($url);
845 2 return $self;
846 }
847  
848 2 ▶sub manual_set_proxy_url {
Subroutine manual_set_proxy_url: called CC=1 SCAR=0.0
Pod undocumented
849 2 my ($self, $url) = @_;
850 2 $self->proxy_url_base($url);
851 2 return $self;
852 }
853  
854 6 ▶sub add_swaig_query_params {
Subroutine add_swaig_query_params: called CC=1 SCAR=0.0
Pod undocumented
855 6 my ($self, %params) = @_;
856 6 $self->swaig_query_params({ %{ $self->swaig_query_params }, %params });
857 6 return $self;
858 }
859  
860 2 ▶sub clear_swaig_query_params {
Subroutine clear_swaig_query_params: called CC=1 SCAR=0.0
Pod undocumented
861 2 my ($self) = @_;
862 2 $self->swaig_query_params({});
863 2 return $self;
864 }
865  
866 5 ▶sub on_summary {
Subroutine on_summary: called CC=3 SCAR=11.0
Pod undocumented
867 5 my ($self, $summary, $raw_data) = @_;
868 # Python parity: AgentBase.on_summary(summary, raw_data=None).
869 #
870 # Two invocation forms:
871 # 1. Registration form (Perl idiom):
872 # $agent->on_summary(sub { my ($summary, $raw) = @_; ... });
873 # A coderef as the first arg installs that handler as the
874 # summary callback and returns $self for chaining.
875 # 2. Dispatch form (Python parity):
876 # $agent->on_summary($summary, $raw_data);
877 # Anything else is treated as the summary payload itself
878 # and dispatches to the registered callback. Default
879 # implementation is a no-op (matches Python's pass).
880 5 ▶ if (ref $summary eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $summary eq "CODE") 3 2 5
881 3 $self->summary_callback($summary);
882 3 return $self;
883 }
884 2 my $cb = $self->summary_callback;
885 2 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) 1 1 2
886 1 return $cb->($summary, $raw_data);
887 }
888 1 return undef;
889 }
890  
891 1 ▶sub on_debug_event {
Subroutine on_debug_event: called CC=1 SCAR=0.0
Pod undocumented
892 1 my ($self, $cb) = @_;
893 1 $self->debug_event_handler($cb);
894 1 return $self;
895 }
896  
897 # ---------- MCP integration ----------
898  
899 7 ▶sub add_mcp_server {
Subroutine add_mcp_server: called CC=4 SCAR=13.9
Pod undocumented
900 7 my ($self, $url, %opts) = @_;
901 7 my $server = { url => $url };
902 7 ▶ $server->{headers} = $opts{headers} if $opts{headers};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"headers"} 2 5 7
903 7 ▶ $server->{resources} = JSON::true if $opts{resources};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"resources"} 1 6 7
904 7 ▶ $server->{resource_vars} = $opts{resource_vars} if $opts{resource_vars};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"resource_vars"} 1 6 7
905 7 push @{ $self->mcp_servers }, $server;
906 7 return $self;
907 }
908  
909 10 ▶sub enable_mcp_server {
Subroutine enable_mcp_server: called CC=1 SCAR=0.0
Pod undocumented
910 10 my ($self) = @_;
911 10 $self->mcp_server_enabled(1);
912 10 return $self;
913 }
914  
915 2 ▶sub _build_mcp_tool_list {
Subroutine _build_mcp_tool_list: called CC=8 SCAR=23.9
916 2 my ($self) = @_;
917 2 my @tools;
918 2 for my $fname (@{ $self->tool_order }) {
919 2 my $tool = $self->tools->{$fname};
920 2 ▶ next unless $tool;
Branch: 1 branch
BranchTrueFalseTotal
unless $tool 0 2 2
921 my $t = {
922 name => $fname,
923 2 ▶ description => $tool->{description} || $fname,
Condition33%1/3
$tool->{'description'} || $fname
l!l&&r!l&&!r
200
MC/DC0%0/2
$tool->{'description'} || $fname
$tool->{'description'} $fname
Truth table33%1/3
A || B
A= $tool->{'description'}B= $fname
ABresult
1X1
011
000
924 };
925 2 ▶ if ($tool->{parameters} && %{ $tool->{parameters} }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tool->{'parameters'} and %{$tool->{'parameters'};}) { } 2 0 2
Condition33%1/3
$tool->{"parameters"} and %{$tool->{"parameters"};}
!ll&&!rl&&r
002
MC/DC0%0/2
$tool->{"parameters"} and %{$tool->{"parameters"};}
$tool->{"parameters"} %{$tool->{"parameters"};}
Truth table33%1/3
A and B
A= $tool->{"parameters"}B= %{$tool->{"parameters"};}
ABresult
0X0
100
111
926 2 my $params = $tool->{parameters};
927 2 ▶ if ($params->{type} && $params->{type} eq 'object') {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'type'} and $params->{'type'} eq 'object') { } 0 2 2
Condition33%1/3
$params->{"type"} and $params->{"type"} eq "object"
!ll&&!rl&&r
200
MC/DC0%0/2
$params->{"type"} and $params->{"type"} eq "object"
$params->{"type"} $params->{"type"} eq "object"
Truth table33%1/3
A and B
A= $params->{"type"}B= $params->{"type"} eq "object"
ABresult
0X0
100
111
928 0 $t->{inputSchema} = $params;
929 } else {
930 2 $t->{inputSchema} = { type => 'object', properties => $params };
931 }
932 } else {
933 0 $t->{inputSchema} = { type => 'object', properties => {} };
934 }
935 2 push @tools, $t;
936 }
937 2 return \@tools;
938 }
939  
940 8 ▶sub _handle_mcp_request {
Subroutine _handle_mcp_request: called CC=21 SCAR=33.3
941 8 my ($self, $body) = @_;
942 8 ▶ my $jsonrpc = $body->{jsonrpc} // '';
Condition50%1/2
$body->{"jsonrpc"} // ""
l!l
80
MC/DC0%0/1
$body->{"jsonrpc"} // ""
$body->{"jsonrpc"}
Truth table50%1/2
A
A= $body->{"jsonrpc"}
Aresult
11
00
943 8 ▶ my $method = $body->{method} // '';
Condition50%1/2
$body->{"method"} // ""
l!l
80
MC/DC0%0/1
$body->{"method"} // ""
$body->{"method"}
Truth table50%1/2
A
A= $body->{"method"}
Aresult
11
00
944 8 my $req_id = $body->{id};
945 8 ▶ my $params = $body->{params} // {};
Condition100%2/2
$body->{"params"} // {}
l!l
53
MC/DC100%1/1
$body->{"params"} // {}
$body->{"params"}
Truth table100%2/2
A
A= $body->{"params"}
Aresult
11
00
946  
947 8 ▶ if ($jsonrpc ne '2.0') {
Branch: 1 branch
BranchTrueFalseTotal
if ($jsonrpc ne "2.0") 1 7 8
948 1 return _mcp_error($req_id, -32600, 'Invalid JSON-RPC version');
949 }
950  
951 # Initialize
952 7 ▶ if ($method eq 'initialize') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "initialize") 1 6 7
953 return {
954 1 jsonrpc => '2.0', id => $req_id,
955 result => {
956 protocolVersion => '2025-06-18',
957 capabilities => { tools => {} },
958 serverInfo => { name => $self->name, version => '1.0.0' },
959 },
960 };
961 }
962  
963 # Initialized notification
964 6 ▶ if ($method eq 'notifications/initialized') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "notifications/initialized") 1 5 6
965 1 return { jsonrpc => '2.0', id => $req_id, result => {} };
966 }
967  
968 # List tools
969 5 ▶ if ($method eq 'tools/list') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "tools/list") 1 4 5
970 return {
971 1 jsonrpc => '2.0', id => $req_id,
972 result => { tools => $self->_build_mcp_tool_list },
973 };
974 }
975  
976 # Call tool
977 4 ▶ if ($method eq 'tools/call') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "tools/call") 2 2 4
978 2 ▶ my $tool_name = $params->{name} // '';
Condition50%1/2
$params->{"name"} // ""
l!l
20
MC/DC0%0/1
$params->{"name"} // ""
$params->{"name"}
Truth table50%1/2
A
A= $params->{"name"}
Aresult
11
00
979 2 ▶ my $arguments = $params->{arguments} // {};
Condition50%1/2
$params->{"arguments"} // {}
l!l
20
MC/DC0%0/1
$params->{"arguments"} // {}
$params->{"arguments"}
Truth table50%1/2
A
A= $params->{"arguments"}
Aresult
11
00
980  
981 2 my $tool = $self->tools->{$tool_name};
982 2 ▶ unless ($tool && $tool->{_handler}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tool and $tool->{"_handler"}) 1 1 2
Condition66%2/3
$tool and $tool->{"_handler"}
!ll&&!rl&&r
101
MC/DC50%1/2
$tool and $tool->{"_handler"}
$tool $tool->{"_handler"}
Truth table66%2/3
A and B
A= $toolB= $tool->{"_handler"}
ABresult
0X0
100
111
983 1 return _mcp_error($req_id, -32602, "Unknown tool: $tool_name");
984 }
985  
986 1 my $result = eval {
987 1 my $raw_data = {
988 function => $tool_name,
989 argument => { parsed => [$arguments] },
990 };
991 1 $tool->{_handler}->($arguments, $raw_data);
992 };
993  
994 1 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
995 return {
996 0 jsonrpc => '2.0', id => $req_id,
997 result => {
998 content => [{ type => 'text', text => "Error: $@" }],
999 isError => JSON::true,
1000 },
1001 };
1002 }
1003  
1004 1 my $response_text = '';
1005 1 ▶ if (blessed($result) && $result->can('to_hash')) {
Branch: 3 branches
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->can('to_hash')) { } 1 0 1
elsif (ref $result eq 'HASH') { } 0 0 0
elsif (defined $result) { } 0 0 0
Condition33%1/3
builtin::blessed($result) and $result->can("to_hash")
!ll&&!rl&&r
001
MC/DC0%0/2
builtin::blessed($result) and $result->can("to_hash")
builtin::blessed($result) $result->can("to_hash")
Truth table33%1/3
A and B
A= builtin::blessed($result)B= $result->can("to_hash")
ABresult
0X0
100
111
1006 1 my $h = $result->to_hash;
1007 1 ▶ $response_text = $h->{response} // '';
Condition50%1/2
$h->{"response"} // ""
l!l
10
MC/DC0%0/1
$h->{"response"} // ""
$h->{"response"}
Truth table50%1/2
A
A= $h->{"response"}
Aresult
11
00
1008 } elsif (ref $result eq 'HASH') {
1009 0 ▶ $response_text = $result->{response} // '';
Condition0%0/2
$result->{"response"} // ""
l!l
00
MC/DC0%0/1
$result->{"response"} // ""
$result->{"response"}
Truth table0%0/2
A
A= $result->{"response"}
Aresult
11
00
1010 } elsif (defined $result) {
1011 0 $response_text = "$result";
1012 }
1013  
1014 return {
1015 1 jsonrpc => '2.0', id => $req_id,
1016 result => {
1017 content => [{ type => 'text', text => $response_text }],
1018 isError => JSON::false,
1019 },
1020 };
1021 }
1022  
1023 # Ping
1024 2 ▶ if ($method eq 'ping') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "ping") 1 1 2
1025 1 return { jsonrpc => '2.0', id => $req_id, result => {} };
1026 }
1027  
1028 1 return _mcp_error($req_id, -32601, "Method not found: $method");
1029 }
1030  
1031 3 ▶sub _mcp_error {
Subroutine _mcp_error: called CC=1 SCAR=0.0
1032 3 my ($req_id, $code, $message) = @_;
1033 return {
1034 3 jsonrpc => '2.0',
1035 id => $req_id,
1036 error => { code => $code, message => $message },
1037 };
1038 }
1039  
1040 # ---------- URL construction ----------
1041  
1042 72 ▶sub _build_webhook_url {
Subroutine _build_webhook_url: called CC=6 SCAR=17.9
1043 72 my ($self, $request_env) = @_;
1044 # If explicit override set, use it
1045 72 ▶ return $self->webhook_url if defined $self->webhook_url;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->webhook_url 1 71 72
1046  
1047 71 my $base = $self->_detect_proxy_url($request_env);
1048 71 ▶ my $route = $self->route eq '/' ? '' : $self->route;
Branch: 1 branch
BranchTrueFalseTotal
$self->route eq '/' ? : 59 12 71
1049 71 my $url = $base . $route . '/swaig';
1050  
1051 # Append query params
1052 71 ▶ if (%{ $self->swaig_query_params }) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->swaig_query_params;}) 1 70 71
1053 1 my @parts;
1054 1 for my $k (sort keys %{ $self->swaig_query_params }) {
1055 2 ▶ push @parts, "$k=" . ($self->swaig_query_params->{$k} // '');
Condition50%1/2
$self->swaig_query_params->{$k} // ""
l!l
20
MC/DC0%0/1
$self->swaig_query_params->{$k} // ""
$self->swaig_query_params->{$k}
Truth table50%1/2
A
A= $self->swaig_query_params->{$k}
Aresult
11
00
1056 }
1057 1 $url .= '?' . join('&', @parts);
1058 }
1059  
1060 71 return $url;
1061 }
1062  
1063 72 ▶sub _build_post_prompt_url {
Subroutine _build_post_prompt_url: called CC=3 SCAR=11.0
1064 72 my ($self, $request_env) = @_;
1065 72 ▶ return $self->post_prompt_url if defined $self->post_prompt_url;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->post_prompt_url 0 72 72
1066 72 my $base = $self->_detect_proxy_url($request_env);
1067 72 ▶ my $route = $self->route eq '/' ? '' : $self->route;
Branch: 1 branch
BranchTrueFalseTotal
$self->route eq '/' ? : 60 12 72
1068 72 return $base . $route . '/post_prompt';
1069 }
1070  
1071 146 ▶sub _detect_proxy_url {
Subroutine _detect_proxy_url: called CC=10 SCAR=24.4
1072 146 my ($self, $env) = @_;
1073  
1074 146 ▶ return $self->proxy_url_base if defined $self->proxy_url_base;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->proxy_url_base 0 146 146
1075  
1076 146 ▶ $env //= {};
Condition50%1/2
$env //= {}
l!l
1460
MC/DC0%0/1
$env //= {}
$env
Truth table50%1/2
A
A= $env
Aresult
11
00
1077  
1078 # Check X-Forwarded headers
1079 146 my $proto = $env->{HTTP_X_FORWARDED_PROTO};
1080 146 my $fhost = $env->{HTTP_X_FORWARDED_HOST};
1081 146 ▶ if ($proto && $fhost) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto and $fhost) 1 145 146
Condition66%2/3
$proto and $fhost
!ll&&!rl&&r
14501
MC/DC50%1/2
$proto and $fhost
$proto $fhost
Truth table66%2/3
A and B
A= $protoB= $fhost
ABresult
0X0
100
111
1082 1 return "${proto}://${fhost}";
1083 }
1084  
1085 # Check X-Original-URL
1086 145 my $orig = $env->{HTTP_X_ORIGINAL_URL};
1087 145 ▶ return $orig if $orig;
Branch: 1 branch
BranchTrueFalseTotal
if $orig 1 144 145
1088  
1089 # Fallback to server config
1090 144 ▶ my $scheme = ($env->{HTTPS} || $env->{'psgi.url_scheme'} || 'http');
Condition40%2/5
$env->{'HTTPS'} || $env->{'psgi.url_scheme'} || 'http'
l!l
0144
$env->{"HTTPS"} or $env->{"psgi.url_scheme"}
l!l&&r!l&&!r
00144
MC/DC0%0/2
$env->{'HTTPS'} || $env->{'psgi.url_scheme'} || 'http'
$env->{"HTTPS"} $env->{"psgi.url_scheme"}
Truth table33%1/3
A or B
A= $env->{"HTTPS"}B= $env->{"psgi.url_scheme"}
ABresult
1X1
011
000
1091 144 ▶ $scheme = 'https' if $scheme eq 'on';
Branch: 1 branch
BranchTrueFalseTotal
if $scheme eq "on" 0 144 144
1092 144 ▶ my $host = $env->{HTTP_HOST} || $self->host . ':' . $self->port;
Condition50%1/2
$env->{'HTTP_HOST'} || $self->host . ':' . $self->port
l!l
0144
MC/DC0%0/1
$env->{'HTTP_HOST'} || $self->host . ':' . $self->port
$env->{'HTTP_HOST'}
Truth table50%1/2
A
A= $env->{'HTTP_HOST'}
Aresult
11
00
1093 144 return "${scheme}://${host}";
1094 }
1095  
1096 4 ▶sub get_full_url {
Subroutine get_full_url: called CC=4 SCAR=14.0
Pod undocumented
1097 4 my ($self, %opts) = @_;
1098 4 ▶ my $base = $self->proxy_url_base // ('http://' . $self->host . ':' . $self->port);
Condition50%1/2
$self->proxy_url_base // 'http://' . $self->host . ':' . $self->port
l!l
04
MC/DC0%0/1
$self->proxy_url_base // 'http://' . $self->host . ':' . $self->port
$self->proxy_url_base
Truth table50%1/2
A
A= $self->proxy_url_base
Aresult
11
00
1099 4 ▶ my $route = $self->route eq '/' ? '' : $self->route;
Branch: 1 branch
BranchTrueFalseTotal
$self->route eq '/' ? : 0 4 4
1100 4 my $url = $base . $route;
1101 4 ▶ if ($opts{include_auth}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"include_auth"}) 2 2 4
1102 2 my $user = $self->basic_auth_user;
1103 2 my $pass = $self->basic_auth_password;
1104 2 $url =~ s{^(https?://)}{$1${user}:${pass}\@};
1105 }
1106 4 return $url;
1107 }
1108  
1109 # ---------- render_swml (5-phase pipeline) ----------
1110  
1111 72 ▶sub render_swml {
Subroutine render_swml: called CC=8 SCAR=20.8
Pod undocumented
1112 72 my ($self, $request_env) = @_;
1113 72 ▶ $request_env //= {};
Condition100%2/2
$request_env //= {}
l!l
765
MC/DC100%1/1
$request_env //= {}
$request_env
Truth table100%2/2
A
A= $request_env
Aresult
11
00
1114  
1115 72 my $webhook_url = $self->_build_webhook_url($request_env);
1116 72 my $post_prompt_url = $self->_build_post_prompt_url($request_env);
1117  
1118 # Embed auth credentials in webhook URL
1119 72 my $auth_user = $self->basic_auth_user;
1120 72 my $auth_pass = $self->basic_auth_password;
1121 72 ▶ $webhook_url =~ s{^(https?://)}{$1${auth_user}:${auth_pass}\@}
Branch: 1 branch
BranchTrueFalseTotal
unless $webhook_url =~ /\@/ 72 0 72
1122 unless $webhook_url =~ /\@/;
1123 72 ▶ $post_prompt_url =~ s{^(https?://)}{$1${auth_user}:${auth_pass}\@}
Branch: 1 branch
BranchTrueFalseTotal
unless $post_prompt_url =~ /\@/ 72 0 72
1124 unless $post_prompt_url =~ /\@/;
1125  
1126 72 my @main_section;
1127  
1128 # Phase 1: Pre-answer verbs
1129 72 push @main_section, @{ $self->pre_answer_verbs };
1130  
1131 # Phase 2: Answer verb
1132 72 ▶ if ($self->auto_answer) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_answer) 71 1 72
1133 71 my %answer_params = (max_duration => 14400);
1134 71 ▶ %answer_params = (%answer_params, %{ $self->answer_config }) if %{ $self->answer_config };
Branch: 1 branch
BranchTrueFalseTotal
if %{$self->answer_config;} 1 70 71
1135 71 push @main_section, { answer => \%answer_params };
1136 }
1137  
1138 # Record call if enabled
1139 72 ▶ if ($self->record_call) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->record_call) 4 68 72
1140 4 ▶ push @main_section, { record_call => {
Branch: 1 branch
BranchTrueFalseTotal
$self->record_stereo ? : 3 1 4
1141 format => $self->record_format,
1142 stereo => $self->record_stereo ? JSON::true : JSON::false,
1143 }};
1144 }
1145  
1146 # Phase 3: Post-answer verbs
1147 72 push @main_section, @{ $self->post_answer_verbs };
1148  
1149 # Phase 4: AI verb
1150 72 my $ai = $self->_build_ai_verb($webhook_url, $post_prompt_url);
1151 72 push @main_section, { ai => $ai };
1152  
1153 # Phase 5: Post-AI verbs
1154 72 push @main_section, @{ $self->post_ai_verbs };
1155  
1156 72 my $doc = {
1157 version => '1.0.0',
1158 sections => { main => \@main_section },
1159 };
1160  
1161 72 return $doc;
1162 }
1163  
1164 72 ▶sub _build_ai_verb {
Subroutine _build_ai_verb: called CC=31 SCAR=34.5
1165 72 my ($self, $webhook_url, $post_prompt_url) = @_;
1166  
1167 72 my %ai;
1168  
1169 # Prompt
1170 72 my $prompt = $self->get_prompt;
1171 72 ▶ if (ref $prompt eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $prompt eq 'ARRAY') { } 22 50 72
1172 # POM mode
1173 22 $ai{prompt} = { pom => $prompt };
1174 } else {
1175 50 ▶ $ai{prompt} = { text => $prompt } if $prompt;
Branch: 1 branch
BranchTrueFalseTotal
if $prompt 6 44 50
1176 }
1177  
1178 # Merge prompt LLM params
1179 72 ▶ if (%{ $self->prompt_llm_params }) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->prompt_llm_params;}) 3 69 72
1180 3 ▶ $ai{prompt} //= {};
Condition50%1/2
$ai{"prompt"} //= {}
l!l
30
MC/DC0%0/1
$ai{"prompt"} //= {}
$ai{"prompt"}
Truth table50%1/2
A
A= $ai{"prompt"}
Aresult
11
00
1181 3 for my $k (keys %{ $self->prompt_llm_params }) {
1182 5 $ai{prompt}{$k} = $self->prompt_llm_params->{$k};
1183 }
1184 }
1185  
1186 # Post prompt
1187 72 ▶ if ($self->post_prompt && $self->post_prompt ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->post_prompt and $self->post_prompt ne "") 4 68 72
Condition66%2/3
$self->post_prompt and $self->post_prompt ne ""
!ll&&!rl&&r
6804
MC/DC50%1/2
$self->post_prompt and $self->post_prompt ne ""
$self->post_prompt $self->post_prompt ne ""
Truth table66%2/3
A and B
A= $self->post_promptB= $self->post_prompt ne ""
ABresult
0X0
100
111
1188 4 $ai{post_prompt} = { text => $self->post_prompt };
1189 4 ▶ if (%{ $self->post_prompt_llm_params }) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$self->post_prompt_llm_params;}) 1 3 4
1190 1 for my $k (keys %{ $self->post_prompt_llm_params }) {
1191 1 $ai{post_prompt}{$k} = $self->post_prompt_llm_params->{$k};
1192 }
1193 }
1194 }
1195  
1196 72 ▶ $ai{post_prompt_url} = $post_prompt_url if $post_prompt_url;
Branch: 1 branch
BranchTrueFalseTotal
if $post_prompt_url 72 0 72
1197  
1198 # Params
1199 72 ▶ $ai{params} = { %{ $self->params } } if %{ $self->params };
Branch: 1 branch
BranchTrueFalseTotal
if %{$self->params;} 3 69 72
1200  
1201 # Hints
1202 72 my @all_hints = @{ $self->hints };
1203 72 push @all_hints, @{ $self->pattern_hints };
1204 72 ▶ $ai{hints} = \@all_hints if @all_hints;
Branch: 1 branch
BranchTrueFalseTotal
if @all_hints 6 66 72
1205  
1206 # Languages
1207 72 ▶ $ai{languages} = $self->languages if @{ $self->languages };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->languages;} 2 70 72
1208  
1209 # Pronunciations
1210 72 ▶ $ai{pronounce} = $self->pronunciations if @{ $self->pronunciations };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->pronunciations;} 1 71 72
1211  
1212 # SWAIG
1213 72 my $swaig = {};
1214  
1215 # Build function list
1216 72 my @functions;
1217 72 for my $fname (@{ $self->tool_order }) {
1218 20 my $tool = $self->tools->{$fname};
1219 20 ▶ next unless $tool;
Branch: 1 branch
BranchTrueFalseTotal
unless $tool 0 20 20
1220 20 my %func = %$tool;
1221 20 delete $func{_handler}; # Don't include handler in SWML
1222 20 ▶ $func{web_hook_url} //= $webhook_url;
Condition33%1/3
$func{"web_hook_url"} //= $webhook_url
l!l&&r!l&&!r
0200
MC/DC0%0/2
$func{"web_hook_url"} //= $webhook_url
$func{"web_hook_url"} $webhook_url
Truth table33%1/3
A //= B
A= $func{"web_hook_url"}B= $webhook_url
ABresult
1X1
011
000
1223 20 push @functions, \%func;
1224 }
1225 72 ▶ $swaig->{functions} = \@functions if @functions;
Branch: 1 branch
BranchTrueFalseTotal
if @functions 17 55 72
1226  
1227 # Native functions
1228 $swaig->{native_functions} = $self->native_functions
1229 72 ▶ if @{ $self->native_functions };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->native_functions;} 2 70 72
1230  
1231 # Includes
1232 $swaig->{includes} = $self->function_includes
1233 72 ▶ if @{ $self->function_includes };
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->function_includes;} 2 70 72
1234  
1235 72 ▶ $ai{SWAIG} = $swaig if %$swaig;
Branch: 1 branch
BranchTrueFalseTotal
if %$swaig 21 51 72
1236  
1237 # Global data
1238 10 $ai{global_data} = { %{ $self->global_data } }
1239 72 ▶ if %{ $self->global_data };
Branch: 1 branch
BranchTrueFalseTotal
if %{$self->global_data;} 10 62 72
1240  
1241 # Internal fillers
1242 72 ▶ if (defined $self->internal_fillers) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->internal_fillers) 2 70 72
1243 2 ▶ $ai{params} //= {};
Condition50%1/2
$ai{"params"} //= {}
l!l
02
MC/DC0%0/1
$ai{"params"} //= {}
$ai{"params"}
Truth table50%1/2
A
A= $ai{"params"}
Aresult
11
00
1244 2 $ai{params}{internal_fillers} = $self->internal_fillers;
1245 }
1246  
1247 # Debug events
1248 72 ▶ if ($self->debug_events_level > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->debug_events_level > 0) 2 70 72
1249 2 ▶ $ai{params} //= {};
Condition50%1/2
$ai{"params"} //= {}
l!l
02
MC/DC0%0/1
$ai{"params"} //= {}
$ai{"params"}
Truth table50%1/2
A
A= $ai{"params"}
Aresult
11
00
1250 2 $ai{params}{debug_events} = $self->debug_events_level;
1251 }
1252  
1253 # Contexts — go under ai.prompt.contexts per Python's
1254 # PromptManager.to_dict() behavior (signalwire-python /core/swml_handler.py
1255 # build_config:172, /core/agent/prompt/manager.py:_contexts).
1256 72 ▶ if ($self->context_builder && $self->context_builder->has_contexts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->context_builder and $self->context_builder->has_contexts) 1 71 72
Condition66%2/3
$self->context_builder and $self->context_builder->has_contexts
!ll&&!rl&&r
0711
MC/DC50%1/2
$self->context_builder and $self->context_builder->has_contexts
$self->context_builder $self->context_builder->has_contexts
Truth table66%2/3
A and B
A= $self->context_builderB= $self->context_builder->has_contexts
ABresult
0X0
100
111
1257 1 ▶ $ai{prompt} //= {};
Condition50%1/2
$ai{"prompt"} //= {}
l!l
01
MC/DC0%0/1
$ai{"prompt"} //= {}
$ai{"prompt"}
Truth table50%1/2
A
A= $ai{"prompt"}
Aresult
11
00
1258 1 $ai{prompt}{contexts} = $self->context_builder->to_hash;
1259 }
1260  
1261 # MCP servers
1262 72 ▶ if (@{ $self->mcp_servers }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->mcp_servers;}) 1 71 72
1263 1 $ai{mcp_servers} = [ @{ $self->mcp_servers } ];
1264 }
1265  
1266 72 return \%ai;
1267 }
1268  
1269 # ---------- PSGI / Plack ----------
1270  
1271 22 ▶sub psgi_app {
Subroutine psgi_app: called CC=1 SCAR=0.0
Pod undocumented
1272 22 my ($self) = @_;
1273 22 return $self->_build_psgi_app;
1274 }
1275  
1276 22 ▶sub _build_psgi_app {
Subroutine _build_psgi_app: called CC=9 SCAR=25.8
1277 22 my ($self) = @_;
1278 22 require Plack::Request;
1279  
1280 22 my $route = $self->route;
1281 22 ▶ $route = '' if $route eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $route eq "/" 13 9 22
1282  
1283 22 my $agent = $self;
1284  
1285 # Build the core app as a plain PSGI sub
1286 20 ▶ my $core_app = sub {
Subroutine __ANON__: called CC=22 SCAR=37.0
1287 20 my $env = shift;
1288 20 my $req = Plack::Request->new($env);
1289 20 my $path = $req->path_info;
1290  
1291 # Normalize path
1292 20 ▶ $path =~ s{/+$}{} unless $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
unless $path eq "/" 10 10 20
1293  
1294 # Health/ready endpoints (no auth)
1295 20 ▶ if ($path eq '/health') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/health") 4 16 20
1296 4 return [200, ['Content-Type' => 'application/json'],
1297 [encode_json({ status => 'healthy', agent => $agent->name })]];
1298 }
1299 16 ▶ if ($path eq '/ready') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/ready") 2 14 16
1300 2 return [200, ['Content-Type' => 'application/json'],
1301 [encode_json({ status => 'ready' })]];
1302 }
1303  
1304 # Auth check for protected routes
1305 14 ▶ my $expected_route = $route eq '' ? '/' : $route;
Branch: 1 branch
BranchTrueFalseTotal
$route eq '' ? : 11 3 14
1306 14 my $is_swaig = ($path eq "$route/swaig");
1307 14 my $is_post_prompt = ($path eq "$route/post_prompt");
1308 14 my $is_mcp = ($path eq "$route/mcp");
1309 14 ▶ my $is_main = ($path eq $expected_route || ($route ne '' && $path eq "$route/"));
Condition50%3/6
$path eq $expected_route || $route ne '' && $path eq "$route/"
l!l&&r!l&&!r
1301
$route ne "" and $path eq "$route/"
!ll&&!rl&&r
100
MC/DC33%1/3
$path eq $expected_route || $route ne '' && $path eq "$route/"
$path eq $expected_route $route ne "" $path eq "$route/"
Truth table50%2/4
A || B and C
A= $path eq $expected_routeB= $route ne ""C= $path eq "$route/"
ABCresult
1XX1
0111
00X0
0100
1310  
1311 # Root agent: treat '/' as main
1312 14 ▶ if ($route eq '' && $path eq '/') {
Branch: 1 branch
BranchTrueFalseTotal
if ($route eq "" and $path eq "/") 10 4 14
Condition100%3/3
$route eq "" and $path eq "/"
!ll&&!rl&&r
3110
MC/DC100%2/2
$route eq "" and $path eq "/"
$route eq "" $path eq "/"
Truth table100%3/3
A and B
A= $route eq ""B= $path eq "/"
ABresult
0X0
100
111
1313 10 $is_main = 1;
1314 }
1315  
1316 14 ▶ if ($is_main || $is_swaig || $is_post_prompt) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_main or $is_swaig or $is_post_prompt) 14 0 14
Condition50%3/6
$is_main or $is_swaig or $is_post_prompt
l!l&&r!l&&!r
1400
$is_main or $is_swaig
l!l&&r!l&&!r
1310
MC/DC0%0/3
$is_main or $is_swaig or $is_post_prompt
$is_main $is_swaig $is_post_prompt
Truth table50%2/4
A or B or C
A= $is_mainB= $is_swaigC= $is_post_prompt
ABCresult
1XX1
01X1
0011
0000
1317 14 my $auth_ok = $agent->_check_auth($env);
1318 14 ▶ unless ($auth_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($auth_ok) 6 8 14
1319 6 return [401,
1320 ['Content-Type' => 'text/plain', 'WWW-Authenticate' => 'Basic realm="SignalWire Agent"'],
1321 ['Unauthorized']];
1322 }
1323 }
1324  
1325 # Route dispatch
1326 8 ▶ if ($is_main && ($req->method eq 'GET' || $req->method eq 'POST')) {
Branch: 4 branches
BranchTrueFalseTotal
if ($is_main and $req->method eq 'GET' || $req->method eq 'POST') { } 7 1 8
elsif ($is_swaig and $req->method eq 'POST') { } 1 0 1
elsif ($is_post_prompt and $req->method eq 'POST') { } 0 0 0
elsif ($is_mcp and $req->method eq 'POST') { } 0 0 0
Condition50%3/6
$is_main and $req->method eq "GET" || $req->method eq "POST"
!ll&&!rl&&r
107
$req->method eq "GET" or $req->method eq "POST"
l!l&&r!l&&!r
700
MC/DC33%1/3
$is_main and $req->method eq "GET" || $req->method eq "POST"
$is_main $req->method eq "GET" $req->method eq "POST"
Truth table50%2/4
A and B or C
A= $is_mainB= $req->method eq "GET"C= $req->method eq "POST"
ABCresult
0XX0
1000
11X1
1011
1327 7 return $agent->_handle_swml($env, $req);
1328 }
1329 ▶ elsif ($is_swaig && $req->method eq 'POST') {
Condition33%1/3
$is_swaig and $req->method eq "POST"
!ll&&!rl&&r
001
MC/DC0%0/2
$is_swaig and $req->method eq "POST"
$is_swaig $req->method eq "POST"
Truth table33%1/3
A and B
A= $is_swaigB= $req->method eq "POST"
ABresult
0X0
100
111
1330 1 return $agent->_handle_swaig($env, $req);
1331 }
1332 ▶ elsif ($is_post_prompt && $req->method eq 'POST') {
Condition0%0/3
$is_post_prompt and $req->method eq "POST"
!ll&&!rl&&r
000
MC/DC0%0/2
$is_post_prompt and $req->method eq "POST"
$is_post_prompt $req->method eq "POST"
Truth table0%0/3
A and B
A= $is_post_promptB= $req->method eq "POST"
ABresult
0X0
100
111
1333 0 return $agent->_handle_post_prompt($env, $req);
1334 }
1335 ▶ elsif ($is_mcp && $req->method eq 'POST') {
Condition0%0/3
$is_mcp and $req->method eq "POST"
!ll&&!rl&&r
000
MC/DC0%0/2
$is_mcp and $req->method eq "POST"
$is_mcp $req->method eq "POST"
Truth table0%0/3
A and B
A= $is_mcpB= $req->method eq "POST"
ABresult
0X0
100
111
1336 0 return $agent->_handle_mcp_endpoint($env, $req);
1337 }
1338  
1339 0 return [404, ['Content-Type' => 'text/plain'], ['Not Found']];
1340 22 };
1341  
1342 # Maximum request body size: 1MB
1343 22 my $max_body_size = 1_048_576;
1344  
1345 # Wrap with body size limit and security headers middleware
1346 20 ▶ my $app_with_middleware = sub {
Subroutine __ANON__: called CC=7 SCAR=19.7
1347 20 my $env = shift;
1348  
1349 # Enforce body size limit by actually reading the body
1350 20 ▶ if ($env->{REQUEST_METHOD} eq 'POST' || $env->{REQUEST_METHOD} eq 'PUT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($env->{"REQUEST_METHOD"} eq "POST" or $env->{"REQUEST_METHOD"} eq "PUT") 1 19 20
Condition66%2/3
$env->{"REQUEST_METHOD"} eq "POST" or $env->{"REQUEST_METHOD"} eq "PUT"
l!l&&r!l&&!r
1019
MC/DC50%1/2
$env->{"REQUEST_METHOD"} eq "POST" or $env->{"REQUEST_METHOD"} eq "PUT"
$env->{"REQUEST_METHOD"} eq "POST" $env->{"REQUEST_METHOD"} eq "PUT"
Truth table66%2/3
A or B
A= $env->{"REQUEST_METHOD"} eq "POST"B= $env->{"REQUEST_METHOD"} eq "PUT"
ABresult
1X1
011
000
1351 1 my $input = $env->{'psgi.input'};
1352 1 ▶ if ($input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input) 1 0 1
1353 1 my $body = '';
1354 1 my $total = 0;
1355 1 my $buf;
1356 1 ▶ while (my $read = $input->read($buf, 8192)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $read = $input->read($buf, 8192)) 1 1 2
1357 1 $total += $read;
1358 1 ▶ if ($total > $max_body_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($total > $max_body_size) 0 1 1
1359 0 return [413, ['Content-Type' => 'application/json',
1360 'X-Content-Type-Options' => 'nosniff',
1361 'X-Frame-Options' => 'DENY',
1362 'Cache-Control' => 'no-store'],
1363 [encode_json({ error => 'Request body too large' })]];
1364 }
1365 1 $body .= $buf;
1366 }
1367 # Replace psgi.input with the buffered content so handlers can re-read
1368 1 open my $new_input, '<', \$body;
1369 1 $env->{'psgi.input'} = $new_input;
1370 1 $env->{CONTENT_LENGTH} = length($body);
1371 }
1372 }
1373  
1374 20 my $res = $core_app->($env);
1375 20 ▶ if (ref $res eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $res eq "ARRAY") 20 0 20
1376 20 push @{ $res->[1] },
1377 'X-Content-Type-Options' => 'nosniff',
1378 'X-Frame-Options' => 'DENY',
1379 'Cache-Control' => 'no-store';
1380 }
1381 20 return $res;
1382 22 };
1383  
1384 # Signed-webhook gate — wraps the entire app so unsigned / invalid
1385 # requests on POST /, POST $route/swaig, POST $route/post_prompt
1386 # are rejected with 403 before any other handling. Passthrough when
1387 # signing_key is empty (the startup-warning code below logs once
1388 # so callers know validation is disabled).
1389 22 my $signing_key = $self->signing_key;
1390 22 ▶ if (defined $signing_key && $signing_key ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $signing_key and $signing_key ne '') { } 0 22 22
Condition33%1/3
defined $signing_key and $signing_key ne ""
!ll&&!rl&&r
2200
MC/DC0%0/2
defined $signing_key and $signing_key ne ""
defined $signing_key $signing_key ne ""
Truth table33%1/3
A and B
A= defined $signing_keyB= $signing_key ne ""
ABresult
0X0
100
111
1391 0 require SignalWire::Security::WebhookMiddleware;
1392 0 ▶ my $main_path = ($route eq '' || $route eq '/') ? '/' : $route;
Branch: 1 branch
BranchTrueFalseTotal
$route eq '' || $route eq '/' ? : 0 0 0
Condition0%0/3
$route eq "" or $route eq "/"
l!l&&r!l&&!r
000
MC/DC0%0/2
$route eq "" or $route eq "/"
$route eq "" $route eq "/"
Truth table0%0/3
A or B
A= $route eq ""B= $route eq "/"
ABresult
1X1
011
000
1393 0 my @gated_paths = ($main_path);
1394 0 ▶ push @gated_paths, "$route/swaig", "$route/post_prompt"
Branch: 1 branch
BranchTrueFalseTotal
if $route ne "" 0 0 0
1395 if $route ne '';
1396 0 ▶ push @gated_paths, '/swaig', '/post_prompt'
Branch: 1 branch
BranchTrueFalseTotal
if $route eq "" or $route eq "/" 0 0 0
Condition0%0/3
$route eq "" or $route eq "/"
l!l&&r!l&&!r
000
MC/DC0%0/2
$route eq "" or $route eq "/"
$route eq "" $route eq "/"
Truth table0%0/3
A or B
A= $route eq ""B= $route eq "/"
ABresult
1X1
011
000
1397 if $route eq '' || $route eq '/';
1398 # De-dup
1399 0 my %seen;
1400 0 @gated_paths = grep { !$seen{$_}++ } @gated_paths;
1401  
1402 0 my $signed_app = SignalWire::Security::WebhookMiddleware->wrap(
1403 app => $app_with_middleware,
1404 signing_key => $signing_key,
1405 paths => \@gated_paths,
1406 methods => ['POST'],
1407 trust_proxy => 1,
1408 );
1409 0 return $signed_app;
1410 }
1411 else {
1412 22 $self->_warn_signing_key_disabled_once;
1413 }
1414  
1415 22 return $app_with_middleware;
1416 }
1417  
1418 # Emit a one-time startup warning when signing_key is unset. Mirrors
1419 # the Python and Node SDKs: webhook signature validation is OFF unless
1420 # you pass signing_key or set SIGNALWIRE_SIGNING_KEY.
1421 22 ▶sub _warn_signing_key_disabled_once {
Subroutine _warn_signing_key_disabled_once: called CC=2 SCAR=7.0
1422 22 my ($self) = @_;
1423 22 ▶ return if $self->{_signing_warning_emitted};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_signing_warning_emitted"} 0 22 22
1424 22 $self->{_signing_warning_emitted} = 1;
1425 22 carp "[signalwire] webhook signature validation is disabled — "
1426 . "set signing_key or SIGNALWIRE_SIGNING_KEY to enable";
1427 }
1428  
1429 14 ▶sub _check_auth {
Subroutine _check_auth: called CC=8 SCAR=20.8
1430 14 my ($self, $env) = @_;
1431 14 ▶ my $auth_header = $env->{HTTP_AUTHORIZATION} // '';
Condition100%2/2
$env->{"HTTP_AUTHORIZATION"} // ""
l!l
122
MC/DC100%1/1
$env->{"HTTP_AUTHORIZATION"} // ""
$env->{"HTTP_AUTHORIZATION"}
Truth table100%2/2
A
A= $env->{"HTTP_AUTHORIZATION"}
Aresult
11
00
1432 14 ▶ return 0 unless $auth_header =~ /^Basic\s+(.+)$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $auth_header =~ /^Basic\s+(.+)$/i 3 11 14
1433 11 ▶ my $decoded = eval { decode_base64($1) } // '';
Condition50%1/2
eval { do { &decode_base64($1) } } // ""
l!l
110
MC/DC0%0/1
eval { do { &decode_base64($1) } } // ""
eval { do { &decode_base64($1) } }
Truth table50%1/2
A
A= eval { do { &decode_base64($1) } }
Aresult
11
00
1434 11 my ($user, $pass) = split(/:/, $decoded, 2);
1435 11 ▶ return 0 unless defined $user && defined $pass;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $user and defined $pass 1 10 11
Condition66%2/3
defined $user and defined $pass
!ll&&!rl&&r
0110
MC/DC50%1/2
defined $user and defined $pass
defined $user defined $pass
Truth table66%2/3
A and B
A= defined $userB= defined $pass
ABresult
0X0
100
111
1436  
1437 # Timing-safe comparison using HMAC (constant-time, no length leak)
1438 10 my $expected_user = $self->basic_auth_user;
1439 10 my $expected_pass = $self->basic_auth_password;
1440  
1441 10 my $user_ok = _timing_safe_eq($user, $expected_user);
1442 10 my $pass_ok = _timing_safe_eq($pass, $expected_pass);
1443  
1444 10 ▶ return ($user_ok && $pass_ok) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$user_ok && $pass_ok ? : 8 2 10
Condition100%3/3
$user_ok and $pass_ok
!ll&&!rl&&r
118
MC/DC100%2/2
$user_ok and $pass_ok
$user_ok $pass_ok
Truth table100%3/3
A and B
A= $user_okB= $pass_ok
ABresult
0X0
100
111
1445 }
1446  
1447 27 ▶sub _timing_safe_eq {
Subroutine _timing_safe_eq: called CC=1 SCAR=0.0
1448 27 my ($a, $b) = @_;
1449 # HMAC-based constant-time comparison: no length leak
1450 27 my $key = 'signalwire-timing-safe-comparison';
1451 27 my $hmac_a = hmac_sha256_hex($a, $key);
1452 27 my $hmac_b = hmac_sha256_hex($b, $key);
1453 27 return $hmac_a eq $hmac_b;
1454 }
1455  
1456 7 ▶sub _handle_swml {
Subroutine _handle_swml: called CC=6 SCAR=18.3
1457 7 my ($self, $env, $req) = @_;
1458  
1459 7 my $agent = $self;
1460  
1461 # If dynamic config callback is set, clone and apply
1462 7 ▶ if ($self->dynamic_config_callback) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dynamic_config_callback) 1 6 7
1463 1 $agent = $self->_clone_for_request;
1464 1 my $query_params = $req->query_parameters->as_hashref_mixed;
1465 1 my $body_params = {};
1466 1 ▶ if ($req->method eq 'POST' && $req->content_length) {
Branch: 1 branch
BranchTrueFalseTotal
if ($req->method eq "POST" and $req->content_length) 0 1 1
Condition33%1/3
$req->method eq "POST" and $req->content_length
!ll&&!rl&&r
100
MC/DC0%0/2
$req->method eq "POST" and $req->content_length
$req->method eq "POST" $req->content_length
Truth table33%1/3
A and B
A= $req->method eq "POST"B= $req->content_length
ABresult
0X0
100
111
1467 0 eval { $body_params = decode_json($req->content) };
1468 }
1469 1 my $headers = {};
1470 1 for my $k (keys %$env) {
1471 10 ▶ if ($k =~ /^HTTP_(.+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /^HTTP_(.+)/) 1 9 10
1472 1 $headers->{lc($1)} = $env->{$k};
1473 }
1474 }
1475 1 $self->dynamic_config_callback->($query_params, $body_params, $headers, $agent);
1476 }
1477  
1478 7 my $swml = $agent->render_swml($env);
1479 7 my $json = encode_json($swml);
1480  
1481 7 return [200, ['Content-Type' => 'application/json'], [$json]];
1482 }
1483  
1484 1 ▶sub _handle_swaig {
Subroutine _handle_swaig: called CC=14 SCAR=35.8
1485 1 my ($self, $env, $req) = @_;
1486  
1487 1 my $body = eval { decode_json($req->content) };
1488 1 ▶ unless ($body && ref $body eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body and ref $body eq "HASH") 0 1 1
Condition33%1/3
$body and ref $body eq "HASH"
!ll&&!rl&&r
001
MC/DC0%0/2
$body and ref $body eq "HASH"
$body ref $body eq "HASH"
Truth table33%1/3
A and B
A= $bodyB= ref $body eq "HASH"
ABresult
0X0
100
111
1489 0 return [400, ['Content-Type' => 'application/json'],
1490 [encode_json({ error => 'Invalid JSON' })]];
1491 }
1492  
1493 1 my $func_name = $body->{function};
1494 1 ▶ unless ($func_name && exists $self->tools->{$func_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($func_name and exists $self->tools->{$func_name}) 0 1 1
Condition33%1/3
$func_name and exists $self->tools->{$func_name}
!ll&&!rl&&r
001
MC/DC0%0/2
$func_name and exists $self->tools->{$func_name}
$func_name exists $self->tools->{$func_name}
Truth table33%1/3
A and B
A= $func_nameB= exists $self->tools->{$func_name}
ABresult
0X0
100
111
1495 0 return [404, ['Content-Type' => 'application/json'],
1496 [encode_json({ error => 'Function not found' })]];
1497 }
1498  
1499 # Extract args
1500 1 my $args = {};
1501 1 ▶ if ($body->{argument} && ref $body->{argument}{parsed} eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
if ($body->{"argument"} and ref $body->{"argument"}{"parsed"} eq "ARRAY" and @{$body->{"argument"}{"parsed"};}) 1 0 1
Condition33%2/6
$body->{"argument"} and ref $body->{"argument"}{"parsed"} eq "ARRAY" and @{$body->{"argument"}{"parsed"};}
!ll&&!rl&&r
001
$body->{"argument"} and ref $body->{"argument"}{"parsed"} eq "ARRAY"
!ll&&!rl&&r
001
MC/DC0%0/3
$body->{"argument"} and ref $body->{"argument"}{"parsed"} eq "ARRAY" and @{$body->{"argument"}{"parsed"};}
$body->{"argument"} ref $body->{"argument"}{"parsed"} eq "ARRAY" @{$body->{"argument"}{"parsed"};}
Truth table25%1/4
A and B and C
A= $body->{"argument"}B= ref $body->{"argument"}{"parsed"} eq "ARRAY"C= @{$body->{"argument"}{"parsed"};}
ABCresult
0XX0
10X0
1100
1111
1502 1 && @{ $body->{argument}{parsed} }) {
1503 1 ▶ $args = $body->{argument}{parsed}[0] // {};
Condition50%1/2
$body->{"argument"}{"parsed"}[0] // {}
l!l
10
MC/DC0%0/1
$body->{"argument"}{"parsed"}[0] // {}
$body->{"argument"}{"parsed"}[0]
Truth table50%1/2
A
A= $body->{"argument"}{"parsed"}[0]
Aresult
11
00
1504 }
1505  
1506 1 my $result = $self->on_function_call($func_name, $args, $body);
1507 1 ▶ unless (defined $result) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result) 0 1 1
1508 0 return [500, ['Content-Type' => 'application/json'],
1509 [encode_json({ error => 'Handler returned no result' })]];
1510 }
1511  
1512 # Serialize result
1513 1 my $response;
1514 1 ▶ if (blessed($result) && $result->can('to_hash')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->can('to_hash')) { } 0 1 1
elsif (ref $result eq 'HASH') { } 1 0 1
Condition33%1/3
builtin::blessed($result) and $result->can("to_hash")
!ll&&!rl&&r
100
MC/DC0%0/2
builtin::blessed($result) and $result->can("to_hash")
builtin::blessed($result) $result->can("to_hash")
Truth table33%1/3
A and B
A= builtin::blessed($result)B= $result->can("to_hash")
ABresult
0X0
100
111
1515 0 $response = $result->to_hash;
1516 } elsif (ref $result eq 'HASH') {
1517 1 $response = $result;
1518 } else {
1519 # Neither a FunctionResult-like object nor a hashref. Warn and
1520 # fall back to wrapping the stringified value, matching Python's
1521 # web_mixin / serverless_mixin / tool_mixin behavior.
1522 0 ▶ my $type = ref($result) || 'SCALAR';
Condition0%0/2
ref $result || 'SCALAR'
l!l
00
MC/DC0%0/1
ref $result || 'SCALAR'
ref $result
Truth table0%0/2
A
A= ref $result
Aresult
11
00
1523 0 carp "unexpected_function_result_type: function=\"$func_name\" "
1524 . "result_type=\"$type\". SWAIG function returned a value "
1525 . "that is neither a FunctionResult (blessed with to_hash) "
1526 . "nor a hashref; falling back to wrapping the stringified "
1527 . "value. The AI will see the stringified value as its "
1528 . "tool response. Return a "
1529 . "SignalWire::SWAIG::FunctionResult object or a hashref "
1530 . "with at least a 'response' key.";
1531 0 $response = { response => "$result" };
1532 }
1533  
1534 1 return [200, ['Content-Type' => 'application/json'], [encode_json($response)]];
1535 }
1536  
1537 0 ▶sub _handle_post_prompt {
Subroutine _handle_post_prompt: not called CC=5 SCAR=34.0
1538 0 my ($self, $env, $req) = @_;
1539  
1540 0 my $body = eval { decode_json($req->content) };
1541 0 ▶ $body //= {};
Condition0%0/2
$body //= {}
l!l
00
MC/DC0%0/1
$body //= {}
$body
Truth table0%0/2
A
A= $body
Aresult
11
00
1542  
1543 0 ▶ if ($self->summary_callback) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->summary_callback) 0 0 0
1544 0 my $summary = undef;
1545 0 ▶ if ($body->{post_prompt_data}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body->{"post_prompt_data"}) 0 0 0
1546 $summary = $body->{post_prompt_data}{parsed}
1547 0 ▶ // $body->{post_prompt_data}{raw};
Condition0%0/3
$body->{"post_prompt_data"}{"parsed"} // $body->{"post_prompt_data"}{"raw"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$body->{"post_prompt_data"}{"parsed"} // $body->{"post_prompt_data"}{"raw"}
$body->{"post_prompt_data"}{"parsed"} $body->{"post_prompt_data"}{"raw"}
Truth table0%0/3
A // B
A= $body->{"post_prompt_data"}{"parsed"}B= $body->{"post_prompt_data"}{"raw"}
ABresult
1X1
011
000
1548 }
1549 0 $self->summary_callback->($summary, $body);
1550 }
1551  
1552 0 return [200, ['Content-Type' => 'application/json'],
1553 [encode_json({ status => 'ok' })]];
1554 }
1555  
1556 0 ▶sub _handle_mcp_endpoint {
Subroutine _handle_mcp_endpoint: not called CC=4 SCAR=30.0
1557 0 my ($self, $env, $req) = @_;
1558  
1559 0 ▶ unless ($self->mcp_server_enabled) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->mcp_server_enabled) 0 0 0
1560 0 return [404, ['Content-Type' => 'application/json'],
1561 [encode_json({ error => 'MCP server not enabled' })]];
1562 }
1563  
1564 0 my $body = eval { decode_json($req->content) };
1565 0 ▶ unless ($body && ref $body eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body and ref $body eq "HASH") 0 0 0
Condition0%0/3
$body and ref $body eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$body and ref $body eq "HASH"
$body ref $body eq "HASH"
Truth table0%0/3
A and B
A= $bodyB= ref $body eq "HASH"
ABresult
0X0
100
111
1566 0 return [400, ['Content-Type' => 'application/json'],
1567 [encode_json(_mcp_error(undef, -32700, 'Parse error'))]];
1568 }
1569  
1570 0 my $resp = $self->_handle_mcp_request($body);
1571 0 return [200, ['Content-Type' => 'application/json'], [encode_json($resp)]];
1572 }
1573  
1574 # ---------- Clone for dynamic config ----------
1575  
1576 3 ▶sub _clone_for_request {
Subroutine _clone_for_request: called CC=3 SCAR=11.0
1577 3 my ($self) = @_;
1578 3 my %init;
1579 3 for my $attr (qw(name route host port auto_answer record_call record_format
1580 record_stereo prompt_text post_prompt use_pom
1581 debug_events_level)) {
1582 36 $init{$attr} = $self->$attr;
1583 }
1584 # Deep copy complex attributes
1585 3 $init{pom_sections} = dclone($self->pom_sections);
1586 3 $init{tools} = dclone($self->tools);
1587 3 $init{tool_order} = [ @{ $self->tool_order } ];
1588 3 $init{hints} = [ @{ $self->hints } ];
1589 3 $init{pattern_hints} = [ @{ $self->pattern_hints } ];
1590 3 $init{languages} = dclone($self->languages);
1591 3 $init{pronunciations} = dclone($self->pronunciations);
1592 3 $init{params} = { %{ $self->params } };
1593 3 $init{global_data} = dclone($self->global_data);
1594 3 $init{native_functions} = [ @{ $self->native_functions } ];
1595 3 $init{function_includes} = dclone($self->function_includes);
1596 3 $init{prompt_llm_params} = { %{ $self->prompt_llm_params } };
1597 3 $init{post_prompt_llm_params} = { %{ $self->post_prompt_llm_params } };
1598 3 $init{pre_answer_verbs} = dclone($self->pre_answer_verbs);
1599 3 $init{post_answer_verbs} = dclone($self->post_answer_verbs);
1600 3 $init{post_ai_verbs} = dclone($self->post_ai_verbs);
1601 3 $init{answer_config} = { %{ $self->answer_config } };
1602 3 $init{swaig_query_params} = { %{ $self->swaig_query_params } };
1603 3 $init{basic_auth_user} = $self->basic_auth_user;
1604 3 $init{basic_auth_password} = $self->basic_auth_password;
1605 3 $init{webhook_url} = $self->webhook_url;
1606 3 $init{post_prompt_url} = $self->post_prompt_url;
1607 3 $init{proxy_url_base} = $self->proxy_url_base;
1608 3 ▶ $init{internal_fillers} = defined $self->internal_fillers
Branch: 1 branch
BranchTrueFalseTotal
defined $self->internal_fillers ? : 0 3 3
1609 ? dclone($self->internal_fillers) : undef;
1610 3 $init{session_manager} = $self->session_manager;
1611 3 $init{mcp_servers} = dclone($self->mcp_servers);
1612 3 $init{mcp_server_enabled} = $self->mcp_server_enabled;
1613  
1614 3 my $clone = (ref $self)->new(%init);
1615 3 return $clone;
1616 }
1617  
1618 # ---------- run / serve ----------
1619  
1620 0 ▶sub run {
Subroutine run: not called CC=1 SCAR=6.9
Pod undocumented
1621 0 my ($self, %opts) = @_;
1622 0 $self->serve(%opts);
1623 }
1624  
1625 0 ▶sub serve {
Subroutine serve: not called CC=3 SCAR=24.8
Pod undocumented
1626 0 my ($self, %opts) = @_;
1627 0 my $app = $self->psgi_app;
1628 0 ▶ my $host = $opts{host} // $self->host;
Condition0%0/3
$opts{"host"} // $self->host
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{"host"} // $self->host
$opts{"host"} $self->host
Truth table0%0/3
A // B
A= $opts{"host"}B= $self->host
ABresult
1X1
011
000
1629 0 ▶ my $port = $opts{port} // $self->port;
Condition0%0/3
$opts{"port"} // $self->port
l!l&&r!l&&!r
000
MC/DC0%0/2
$opts{"port"} // $self->port
$opts{"port"} $self->port
Truth table0%0/3
A // B
A= $opts{"port"}B= $self->port
ABresult
1X1
011
000
1630  
1631 0 require Plack::Runner;
1632 0 my $runner = Plack::Runner->new;
1633 0 $runner->parse_options(
1634 '--host' => $host,
1635 '--port' => $port,
1636 '--server' => 'HTTP::Server::PSGI',
1637 );
1638 0 $runner->run($app);
1639 }
1640  
1641 # ---------- helpers ----------
1642  
1643 67 ▶sub _generate_random_password {
Subroutine _generate_random_password: called CC=4 SCAR=15.5
1644 # Use /dev/urandom for cryptographically secure random bytes.
1645 # Die on failure rather than falling back to a weak password.
1646 67 my $bytes = '';
1647 67 ▶ if (open my $fh, '<:raw', '/dev/urandom') {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, "<:raw", "/dev/urandom") 67 0 67
1648 67 my $read = read($fh, $bytes, 32);
1649 67 close $fh;
1650 67 ▶ if (defined $read && $read == 32) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $read and $read == 32) 67 0 67
Condition33%1/3
defined $read and $read == 32
!ll&&!rl&&r
0067
MC/DC0%0/2
defined $read and $read == 32
defined $read $read == 32
Truth table33%1/3
A and B
A= defined $readB= $read == 32
ABresult
0X0
100
111
1651 # Convert to hex string (64 chars)
1652 67 return unpack('H*', $bytes);
1653 }
1654 }
1655 0 die "FATAL: Cannot generate secure random password - /dev/urandom unavailable or read failed. "
1656 . "Set SWML_BASIC_AUTH_PASSWORD environment variable instead.\n";
1657 }
1658  
1659 0 ▶sub extract_sip_username {
Subroutine extract_sip_username: not called CC=8 SCAR=42.8
Pod undocumented
1660 0 my ($class_or_self, $body) = @_;
1661 # Extract SIP username from a request body (hashref).
1662 # Looks in standard SignalWire fields for the SIP caller identity.
1663 0 ▶ return undef unless ref $body eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $body eq "HASH" 0 0 0
1664  
1665 # Check call.from field (e.g., "sip:user@domain")
1666 my $from = $body->{call}{from}
1667 // $body->{sip_from}
1668 // $body->{from}
1669 0 ▶ // '';
Condition0%0/8
(($body->{"call"}{"from"} // $body->{"sip_from"}) // $body->{"from"}) // ""
l!l
00
($body->{"call"}{"from"} // $body->{"sip_from"}) // $body->{"from"}
l!l&&r!l&&!r
000
$body->{"call"}{"from"} // $body->{"sip_from"}
l!l&&r!l&&!r
000
MC/DC0%0/3
(($body->{"call"}{"from"} // $body->{"sip_from"}) // $body->{"from"}) // ""
$body->{"call"}{"from"} $body->{"sip_from"} $body->{"from"}
Truth table0%0/4
A // B // C
A= $body->{"call"}{"from"}B= $body->{"sip_from"}C= $body->{"from"}
ABCresult
1XX1
01X1
0011
0000
1670  
1671 0 ▶ if ($from =~ m{^sip:([^@]+)\@}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from =~ /^sip:([^\@]+)\@/i) 0 0 0
1672 0 return $1;
1673 }
1674  
1675 # Check for a direct caller_id_number
1676 0 ▶ if (my $cid = $body->{call}{caller_id_number} // $body->{caller_id_number}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cid = $body->{"call"}{"caller_id_number"} // $body->{"caller_id_number"}) 0 0 0
Condition0%0/3
$body->{"call"}{"caller_id_number"} // $body->{"caller_id_number"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$body->{"call"}{"caller_id_number"} // $body->{"caller_id_number"}
$body->{"call"}{"caller_id_number"} $body->{"caller_id_number"}
Truth table0%0/3
A // B
A= $body->{"call"}{"caller_id_number"}B= $body->{"caller_id_number"}
ABresult
1X1
011
000
1677 0 return $cid;
1678 }
1679  
1680 0 return undef;
1681 }
1682  
1683 37 1;
« scripts/enumerate_surface.pl ↑ Summary blib/lib/SignalWire/Relay/Action.pm »