| 1 | package Praxo::Runtime; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Exporter 'import'; | ||
| 6 | use Cwd qw(abs_path); | ||
| 7 | use File::Basename qw(basename dirname); | ||
| 8 | use File::Spec; | ||
| 9 | use Praxo::Json (); | ||
| 10 | use Praxo::Models (); | ||
| 11 | use Praxo::Errors qw(praxo_error); | ||
| 12 | |||
| 13 | our @EXPORT_OK = qw( | ||
| 14 | MultiSink FilterSink MemoryStore CheckpointAllowlist PathChecker | ||
| 15 | ContextBudget estimate_tokens truncate_to_tokens compact_context | ||
| 16 | ); | ||
| 17 | |||
| 18 | package Praxo::Runtime::MultiSink; | ||
| 19 | |||
| 20 | sub new { | ||
| 21 | my ($class, $sinks) = @_; | ||
| 22 | return bless { sinks => $sinks // [] }, $class; | ||
| 23 | } | ||
| 24 | |||
| 25 | sub emit { | ||
| 26 | my ($self, $event) = @_; | ||
| 27 | $_->emit($event) for @{ $self->{sinks} }; | ||
| 28 | } | ||
| 29 | |||
| 30 | package Praxo::Runtime::FilterSink; | ||
| 31 | |||
| 32 | sub new { | ||
| 33 | my ($class, $sink, $predicate) = @_; | ||
| 34 | return bless { sink => $sink, predicate => $predicate }, $class; | ||
| 35 | } | ||
| 36 | |||
| 37 | sub emit { | ||
| 38 | my ($self, $event) = @_; | ||
| 39 | $self->{sink}->emit($event) if $self->{predicate}->($event); | ||
| 40 | } | ||
| 41 | |||
| 42 | package Praxo::Runtime::MemoryStore; | ||
| 43 | |||
| 44 | sub new { | ||
| 45 | my ($class) = @_; | ||
| 46 | return bless { records => {}, sequence => 0 }, $class; | ||
| 47 | } | ||
| 48 | |||
| 49 | sub put { | ||
| 50 | my ($self, $session_id, $record) = @_; | ||
| 51 | if (!defined($record->{id}) || $record->{id} eq '') { | ||
| 52 | $record->{id} = 'mem-' . int(time() * 1000) . '-' . $self->{sequence}++; | ||
| 53 | } | ||
| 54 | if (!defined $record->{createdAt}) { | ||
| 55 | my @now = gmtime(); | ||
| 56 | $record->{createdAt} = sprintf( | ||
| 57 | '%04d-%02d-%02dT%02d:%02d:%02dZ', | ||
| 58 | $now[5] + 1900, $now[4] + 1, $now[3], $now[2], $now[1], $now[0], | ||
| 59 | ); | ||
| 60 | } | ||
| 61 | push @{ $self->{records}{$session_id} //= [] }, $record; | ||
| 62 | return $record; | ||
| 63 | } | ||
| 64 | |||
| 65 | sub search { | ||
| 66 | my ($self, $session_id, $query, $limit) = @_; | ||
| 67 | my $needle = lc($query // ''); | ||
| 68 | $needle =~ s/^\s+|\s+$//g; | ||
| 69 | my @matches = grep { | ||
| 70 | $needle eq '' || index(lc($_->{content} // ''), $needle) >= 0 | ||
| 71 | } @{ $self->{records}{$session_id} // [] }; | ||
| 72 | @matches = sort { | ||
| 73 | ($b->{createdAt} // '') cmp ($a->{createdAt} // '') | ||
| 74 | } @matches; | ||
| 75 | @matches = @matches[0 .. $limit - 1] if $limit > 0 && @matches > $limit; | ||
| 76 | return @matches; | ||
| 77 | } | ||
| 78 | |||
| 79 | package Praxo::Runtime::CheckpointAllowlist; | ||
| 80 | |||
| 81 | sub new { | ||
| 82 | my ($class) = @_; | ||
| 83 | return bless { registered => {} }, $class; | ||
| 84 | } | ||
| 85 | |||
| 86 | sub register { | ||
| 87 | my ($self, $type) = @_; | ||
| 88 | Praxo::Errors::praxo_error('CHECKPOINT_ERROR', 'checkpoint: type is required') | ||
| 89 | unless defined($type) && length($type); | ||
| 90 | $self->{registered}{$type} = 1; | ||
| 91 | } | ||
| 92 | |||
| 93 | sub marshal { | ||
| 94 | my ($self, $type, $value) = @_; | ||
| 95 | Praxo::Errors::praxo_error('CHECKPOINT_TYPE_NOT_ALLOWED', "checkpoint: payload type not allowed: $type") | ||
| 96 | unless $self->{registered}{$type}; | ||
| 97 | return Praxo::Json::stringify({ type => $type, data => $value }); | ||
| 98 | } | ||
| 99 | |||
| 100 | sub unmarshal { | ||
| 101 | my ($self, $data) = @_; | ||
| 102 | my $envelope = Praxo::Json::parse($data); | ||
| 103 | Praxo::Errors::praxo_error('CHECKPOINT_ERROR', 'checkpoint: envelope must be an object') | ||
| 104 | unless ref($envelope) eq 'HASH'; | ||
| 105 | my $type = $envelope->{type} // ''; | ||
| 106 | Praxo::Errors::praxo_error('CHECKPOINT_TYPE_NOT_ALLOWED', "checkpoint: payload type not allowed: $type") | ||
| 107 | unless $self->{registered}{$type}; | ||
| 108 | return $envelope->{data}; | ||
| 109 | } | ||
| 110 | |||
| 111 | package Praxo::Runtime::PathChecker; | ||
| 112 | |||
| 113 | sub new { | ||
| 114 | my ($class, $grants) = @_; | ||
| 115 | my @normalized; | ||
| 116 | for my $grant (@{ $grants // [] }) { | ||
| 117 | push @normalized, { | ||
| 118 | root => _resolve_path($grant->{root} // ''), | ||
| 119 | access => $grant->{access} // 'read', | ||
| 120 | }; | ||
| 121 | } | ||
| 122 | return bless { grants => \@normalized }, $class; | ||
| 123 | } | ||
| 124 | |||
| 125 | sub check { | ||
| 126 | my ($self, $target, $need) = @_; | ||
| 127 | Praxo::Errors::praxo_error('POLICY_ERROR', 'policy: invalid access') | ||
| 128 | unless $need eq 'read' || $need eq 'write' || $need eq 'readwrite'; | ||
| 129 | return { allowed => 0, reason => 'no allowed roots' } unless @{ $self->{grants} }; | ||
| 130 | my $resolved = _resolve_path($target); | ||
| 131 | my $matched = undef; | ||
| 132 | for my $grant (@{ $self->{grants} }) { | ||
| 133 | next unless _within($grant->{root}, $resolved); | ||
| 134 | $matched = $grant->{root}; | ||
| 135 | if (_allows($grant->{access}, $need)) { | ||
| 136 | return { allowed => 1, reason => "path within $grant->{root}" }; | ||
| 137 | } | ||
| 138 | } | ||
| 139 | return { | ||
| 140 | allowed => 0, | ||
| 141 | reason => defined($matched) ? 'insufficient grant' : 'outside roots', | ||
| 142 | }; | ||
| 143 | } | ||
| 144 | |||
| 145 | sub allowed { | ||
| 146 | my ($self, $target, $need) = @_; | ||
| 147 | my $decision = eval { $self->check($target, $need) }; | ||
| 148 | return $decision ? $decision->{allowed} : 0; | ||
| 149 | } | ||
| 150 | |||
| 151 | sub _resolve_path { | ||
| 152 | my ($value) = @_; | ||
| 153 | return '' unless defined $value; | ||
| 154 | my $absolute = File::Spec->rel2abs($value); | ||
| 155 | my $real = Cwd::abs_path($absolute); | ||
| 156 | return $real if defined $real; | ||
| 157 | my ($volume, $directories, $file) = File::Spec->splitpath($absolute); | ||
| 158 | my $parent = File::Spec->catpath($volume, $directories, ''); | ||
| 159 | $parent =~ s{[\\/]+$}{}; | ||
| 160 | return $absolute if $parent eq ''; | ||
| 161 | my $resolved_parent = _resolve_path($parent); | ||
| 162 | return File::Spec->catfile($resolved_parent, $file); | ||
| 163 | } | ||
| 164 | |||
| 165 | sub _within { | ||
| 166 | my ($root, $target) = @_; | ||
| 167 | my $sep = File::Spec->catfile('', ''); | ||
| 168 | $root =~ s{[\\/]+$}{}; | ||
| 169 | $target =~ s{[\\/]+$}{}; | ||
| 170 | if ($^O eq 'MSWin32') { | ||
| 171 | $root = lc $root; | ||
| 172 | $target = lc $target; | ||
| 173 | } | ||
| 174 | return 1 if $target eq $root; | ||
| 175 | return index($target, $root . $sep) == 0 ? 1 : 0; | ||
| 176 | } | ||
| 177 | |||
| 178 | sub _allows { | ||
| 179 | my ($grant, $need) = @_; | ||
| 180 | return 1 if $need eq 'read' && ($grant eq 'read' || $grant eq 'readwrite'); | ||
| 181 | return 1 if $need eq 'write' && ($grant eq 'write' || $grant eq 'readwrite'); | ||
| 182 | return 1 if $need eq 'readwrite' && $grant eq 'readwrite'; | ||
| 183 | return 0; | ||
| 184 | } | ||
| 185 | |||
| 186 | package Praxo::Runtime::ContextBudget; | ||
| 187 | |||
| 188 | sub new { | ||
| 189 | my ($class, %args) = @_; | ||
| 190 | return bless { | ||
| 191 | maxTokens => $args{max_tokens} // 0, | ||
| 192 | keepRecent => $args{keep_recent} // 0, | ||
| 193 | }, $class; | ||
| 194 | } | ||
| 195 | |||
| 196 | sub max_tokens { $_[0]->{maxTokens} } | ||
| 197 | sub keep_recent { $_[0]->{keepRecent} } | ||
| 198 | |||
| 199 | sub compact { | ||
| 200 | my ($self, $messages) = @_; | ||
| 201 | my $max = $self->{maxTokens}; | ||
| 202 | return ($messages, 1) if $max <= 0 || Praxo::Runtime::estimate_tokens($messages) <= $max; | ||
| 203 | my (@system, @rest); | ||
| 204 | for my $message (@$messages) { | ||
| 205 | if (($message->{role} // '') eq Praxo::Models::SYSTEM) { | ||
| 206 | next if ($message->{content} // '') =~ /^\[context compacted:/; | ||
| 207 | push @system, $message; | ||
| 208 | } else { | ||
| 209 | push @rest, $message; | ||
| 210 | } | ||
| 211 | } | ||
| 212 | if (Praxo::Runtime::estimate_tokens(\@system) > $max) { | ||
| 213 | return ([], 0) unless @system; | ||
| 214 | my $first = { %{ $system[0] } }; | ||
| 215 | $first->{content} = Praxo::Runtime::truncate_to_tokens( | ||
| 216 | $system[0]{content} // '', $max - 4, | ||
| 217 | ); | ||
| 218 | @system = ($first); | ||
| 219 | return ([], 0) if Praxo::Runtime::estimate_tokens(\@system) > $max; | ||
| 220 | } | ||
| 221 | my $keep = $self->{keepRecent} > 0 ? $self->{keepRecent} : 4; | ||
| 222 | my $start = @rest - $keep; | ||
| 223 | $start = 0 if $start < 0; | ||
| 224 | $start-- while $start > 0 && ($rest[$start]{role} // '') eq Praxo::Models::TOOL; | ||
| 225 | my $marker = Praxo::Models::message_text( | ||
| 226 | Praxo::Models::SYSTEM, | ||
| 227 | "[context compacted: $start older messages omitted]", | ||
| 228 | ); | ||
| 229 | my @kept = @rest[$start .. $#rest]; | ||
| 230 | my $output = _build_compacted(\@system, $marker, $start > 0, \@kept); | ||
| 231 | while (Praxo::Runtime::estimate_tokens($output) > $max && @kept > 1) { | ||
| 232 | last if ($kept[1]{role} // '') eq Praxo::Models::TOOL; | ||
| 233 | shift @kept; | ||
| 234 | $output = _build_compacted(\@system, $marker, $start > 0, \@kept); | ||
| 235 | } | ||
| 236 | return ($output, Praxo::Runtime::estimate_tokens($output) <= $max ? 1 : 0); | ||
| 237 | } | ||
| 238 | |||
| 239 | sub _build_compacted { | ||
| 240 | my ($system, $marker, $include_marker, $kept) = @_; | ||
| 241 | my @output = @$system; | ||
| 242 | push @output, $marker if $include_marker; | ||
| 243 | push @output, @$kept; | ||
| 244 | return \@output; | ||
| 245 | } | ||
| 246 | |||
| 247 | package Praxo::Runtime; | ||
| 248 | |||
| 249 | sub estimate_tokens { | ||
| 250 | my ($messages) = @_; | ||
| 251 | my $total = 0; | ||
| 252 | for my $message (@$messages) { | ||
| 253 | $total += 4 + int(length($message->{content} // '') / 4) | ||
| 254 | + int(length($message->{toolId} // '') / 4); | ||
| 255 | for my $block (@{ $message->{contentBlocks} // [] }) { | ||
| 256 | $total += 4 + int(length($block->{text} // '') / 4) | ||
| 257 | + int(length($block->{image_url} // '') / 4) | ||
| 258 | + int(length($block->{data} // '') / 4); | ||
| 259 | } | ||
| 260 | for my $call (@{ $message->{toolCalls} // [] }) { | ||
| 261 | $total += 4 + int(length($call->{name} // '') / 4); | ||
| 262 | $total += int(length(Praxo::Json::stringify($call->{arguments} // {})) / 4); | ||
| 263 | } | ||
| 264 | } | ||
| 265 | return $total; | ||
| 266 | } | ||
| 267 | |||
| 268 | sub truncate_to_tokens { | ||
| 269 | my ($value, $tokens) = @_; | ||
| 270 | return '' if $tokens <= 0; | ||
| 271 | my $limit = $tokens * 4; | ||
| 272 | return $value if length($value) <= $limit; | ||
| 273 | return substr($value, 0, $limit) if $limit <= 16; | ||
| 274 | return substr($value, 0, $limit - 16) . "\n[truncated]"; | ||
| 275 | } | ||
| 276 | |||
| 277 | sub compact_context { | ||
| 278 | my ($budget, $messages) = @_; | ||
| 279 | return $budget->compact($messages); | ||
| 280 | } | ||
| 281 | |||
| 282 | 1; |