blib/lib/App/karr/Foundation/Agents.pm untested

filter: Statementstmt 0.0% 0 / 176 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 56 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 384 CC 40 SCAR 34.2
CC
40
Cov
0%
_build_definitions
110.0
_claude_code_command
42.0
_mutate
30.0
CRAP 30.6
1 # ABSTRACT: karr-foundation agent definitions, invocation contract and availability
2  
3 package App::karr::Foundation::Agents;
4 our $VERSION = '0.602';
5 use Moo;
6 use Path::Tiny;
7 use Fcntl qw( LOCK_EX );
8 use App::karr::Error qw( user_error clean_error );
9 use App::karr::Encoding qw( json_encode json_decode );
10 use Try::Tiny;
11  
12  
13  
14 has foundation => (
15 is => 'ro',
16 weak_ref => 1,
17 required => 1,
18 );
19  
20 # How long to wait before trying an agent that stopped working, when nobody
21 # said. Short enough that a five-minute blip does not park a fleet for an hour,
22 # long enough that a hard rate limit is not hammered once a minute. An operator
23 # who knows the real rhythm writes probe_every and stops guessing.
24 our $DEFAULT_PROBE_SECONDS = 600;
25  
26 # How many recoveries are kept per agent. The record exists so somebody can see
27 # a rhythm in it; an unbounded list in a state file is a leak, and twenty
28 # outages are already more shape than anyone needs.
29 our $MAX_RECOVERIES = 20;
30  
31 # The invocation contracts karr knows. 'shell' is the historical `command:` --
32 # a complete shell template karr appends nothing to, because it has no idea
33 # what the thing at the other end understands. 'claude-code' is the one
34 # contract it does know.
35 my %KIND = map { $_ => 1 } qw( shell claude-code );
36  
37 # The roles a definition may carry, which is how karr-foundation finds the one
38 # agent that is its judgement layer (App::karr::Foundation::Coordinator). A
39 # marker on a definition rather than a second config key naming an agent that
40 # is already named: two names for one thing are two things to keep in step.
41 # An unknown role is a hard error for the same reason an unknown kind is --
42 # `role: coordinater` would leave a fleet with no judgement layer at all and
43 # say nothing about it, on every tick, quietly.
44 my %ROLE = map { $_ => 1 } qw( coordinator );
45  
46 # Keys a definition may carry. Not a schema for its own sake: a typo in
47 # 'description' silently drops the one thing that decides where work goes, and
48 # there is no other feedback loop -- an agent definition is never "run" until
49 # something goes wrong. Unknown keys warn rather than die, so a config written
50 # for a newer karr still starts.
51 my %KNOWN_KEY = map { $_ => 1 } qw(
52 command kind probe_every description concurrent role
53 permission_mode max_turns allowed_tools
54 );
55  
56 # ---------------------------------------------------------------------------
57 # Definitions
58 # ---------------------------------------------------------------------------
59  
60  
61 has definitions => (
62 is => 'lazy',
63 builder => '_build_definitions',
64 );
65  
66 sub _build_definitions {
67 my ( $self ) = @_;
68 my $raw = $self->foundation->_config_data->{agents};
69 return {} unless defined $raw;
70 user_error("Config key 'agents' must be a mapping of name => definition")
71 unless ref $raw eq 'HASH';
72  
73 my %defs;
74 for my $name ( sort keys %$raw ) {
75 my $def = $raw->{$name};
76 user_error("Agent '$name' must be a mapping") unless ref $def eq 'HASH';
77 my %d = %$def;
78  
79 my $cmd = $d{command};
80 user_error("Agent '$name' has no command") unless defined $cmd && length $cmd;
81  
82 my $kind = $d{kind} // 'shell';
83 user_error(
84 "Agent '$name' has unknown kind '$kind' "
85 . '(expected: ' . join( ' or ', sort keys %KIND ) . ')' )
86 unless $KIND{$kind};
87 $d{kind} = $kind;
88  
89 if ( defined( my $role = $d{role} ) ) {
90 user_error(
91 "Agent '$name' has unknown role '$role' "
92 . '(expected: ' . join( ' or ', sort keys %ROLE ) . ')' )
93 unless $ROLE{$role};
94 }
95  
96 $d{probe_seconds} = defined $d{probe_every}
97 ? _duration( "Agent '$name' probe_every", $d{probe_every} )
98 : undef;
99  
100 my @unknown = grep { !$KNOWN_KEY{$_} && $_ ne 'probe_seconds' } sort keys %d;
101 warn "karr-foundation: agent '$name': unknown key(s): @unknown\n" if @unknown;
102  
103 $defs{$name} = \%d;
104 }
105 return \%defs;
106 }
107  
108 # A duration as a config writes one: 45, 90s, 15m, 2h, 1d. Bare numbers are
109 # seconds. Anything else is a config error, not a default -- a probe_every of
110 # "15min" silently meaning ten minutes is exactly the kind of quiet wrong
111 # answer this file exists to avoid.
112 sub _duration {
113 my ( $what, $value ) = @_;
114 user_error("$what must be a duration, not a structure") if ref $value;
115 my $v = "$value";
116 $v =~ s/\A\s+//;
117 $v =~ s/\s+\z//;
118 return $v + 0 if $v =~ /\A[0-9]+\z/;
119 my ( $n, $unit ) = $v =~ /\A([0-9]+)\s*([smhd])\z/i
120 or user_error("$what: cannot read '$value' as a duration (e.g. 90s, 15m, 2h, 1d)");
121 my %mult = ( s => 1, m => 60, h => 3600, d => 86400 );
122 return $n * $mult{ lc $unit };
123 }
124  
125  
126 sub definition {
127 my ( $self, $name ) = @_;
128 my $def = $self->definitions->{$name}
129 or user_error( "No agent named '$name' is defined"
130 . ( %{ $self->definitions }
131 ? ' (known: ' . join( ', ', sort keys %{ $self->definitions } ) . ')'
132 : " (the config has no 'agents:' section)" ) );
133 return $def;
134 }
135  
136  
137 sub names { return sort keys %{ $_[0]->definitions } }
138  
139 # ---------------------------------------------------------------------------
140 # The invocation contract
141 # ---------------------------------------------------------------------------
142  
143  
144 # Everything foundation needs to run one named agent: the assembled shell
145 # command, the name to log it under, and how to render its live output.
146 sub invocation {
147 my ( $self, $name ) = @_;
148 my $def = $self->definition( $name );
149 my $kind = $def->{kind};
150 return {
151 name => $name,
152 kind => $kind,
153 command => $kind eq 'claude-code'
154 ? $self->_claude_code_command( $def )
155 : $def->{command},
156 render => $kind eq 'claude-code' ? 'stream-json' : undef,
157 description => $def->{description},
158 };
159 }
160  
161 # `kind: claude-code` -- the one contract karr knows how to append arguments
162 # to. The definition's `command` stays a template karr does not quote (it may
163 # be `claude`, a wrapper, or `env FOO=1 claude --model x`, exactly as
164 # claude_bin always could); everything appended after it is karr's, and every
165 # value that came out of the config is quoted, because a permission mode with a
166 # space in it must not become two arguments.
167 #
168 # --output-format is the reason this is a contract rather than a flag list. The
169 # run's own report (App::karr::Foundation::Runner::_run_result) is only there to
170 # read when the agent emits one, so a claude-code agent has to be asked for
171 # structured output. Plain `--output-format json` would buy that by printing
172 # nothing at all until the run ends, which silently breaks the live output this
173 # module's own documentation promises for a TTY. `stream-json` ends with the
174 # same result object AND streams on the way, so the Runner renders it (render =>
175 # 'stream-json' above) and both halves survive. --verbose is not optional next
176 # to it: claude refuses `-p --output-format stream-json` without it.
177 #
178 # The assignment of a ticket-mode run is deliberately NOT appended here. claude
179 # has no flag for it, so the id keeps travelling the way #185 sends it -- as a
180 # closing sentence in $PROMPT and as $KARR_TASK in the environment.
181 sub _claude_code_command {
182 my ( $self, $def ) = @_;
183 my @argv = ( $def->{command}, '-p', '"$PROMPT"' );
184 push @argv, '--output-format', 'stream-json', '--verbose',
185 '--include-partial-messages';
186 push @argv, '--permission-mode',
187 _shq( $def->{permission_mode} // 'bypassPermissions' );
188 # max_turns: 0 drops the flag, the same "no limit" spelling max_runtime uses.
189 my $turns = exists $def->{max_turns} ? $def->{max_turns} : 30;
190 push @argv, '--max-turns', _shq( $turns ) if $turns;
191 if ( defined( my $tools = $def->{allowed_tools} ) ) {
192 my @tools = grep { defined && length } ref $tools eq 'ARRAY' ? @$tools : ( $tools );
193 push @argv, '--allowed-tools', _shq( join ',', @tools ) if @tools;
194 }
195 return join ' ', @argv;
196 }
197  
198 # Single-quote a config value for /bin/sh, and only when it needs it -- an
199 # unquoted 30 and bypassPermissions keep .karr.log's START line readable, which
200 # is what an operator reads it for.
201 sub _shq {
202 my ( $v ) = @_;
203 $v = defined $v ? "$v" : '';
204 return $v if length $v && $v =~ m{\A[A-Za-z0-9_.:,/=+-]+\z};
205 $v =~ s/'/'\\''/g;
206 return "'$v'";
207 }
208  
209 # ---------------------------------------------------------------------------
210 # Availability
211 # ---------------------------------------------------------------------------
212  
213 # WHERE THIS LIVES, and why it is neither of the two obvious places.
214 #
215 # Not .karr.state: that file is per repository, and an agent's availability is
216 # not a property of a repository. Two repos driven by the same agent have to
217 # share one piece of knowledge -- that the command stopped working -- or the
218 # second one spends its own window discovering it again, and a repo that has
219 # not been visited yet learns nothing at all.
220 #
221 # Not the board (refs/karr/config, where `karr disable` lives): that syncs, and
222 # this must not. An agent command that exists on one machine does not exist on
223 # the next, and a spent account limit belongs to a person, not to a project.
224 # Pushing "minimax is failing" to a shared remote parks a colleague's fleet on
225 # an outage that is not theirs.
226 #
227 # So it is machine-local and agent-scoped, and it lives beside the config file
228 # that defines the agents. That also makes it follow --config: a second fleet
229 # (or a test) pointed at another config gets its own availability and cannot
230 # write over the real one.
231  
232 has state_file => (
233 is => 'lazy',
234 builder => '_build_state_file',
235 );
236  
237 sub _build_state_file {
238 my ( $self ) = @_;
239 return $self->foundation->_config_path->sibling('agents.state');
240 }
241  
242 # Read fresh every time rather than cached in the object. The file is a few
243 # hundred bytes; what the read buys is that two foundation ticks that overlap
244 # (#162 is the same story for .karr.lock) see each other's outages, and that an
245 # operator who edits the file by hand is not talking to a copy taken minutes
246 # ago. A bare read takes no lock: the worst a torn read can produce is
247 # undecodable JSON, which yields {} and one cautious probe. The read that is
248 # part of a read-modify-write is a different matter and happens inside
249 # _mutate's lock.
250 sub _read_state {
251 my ( $self ) = @_;
252 my $file = $self->state_file;
253 return {} unless $file->exists;
254 my $data = try { json_decode( $file->slurp_utf8 ) } catch { undef };
255 return ref $data eq 'HASH' ? $data : {};
256 }
257  
258 sub _mutate {
259 my ( $self, $edit ) = @_;
260  
261 # A dry run writes nothing, so there is nothing to serialise.
262 if ( $self->foundation->dry_run ) {
263 $edit->( $self->_read_state );
264 return;
265 }
266  
267 my $file = $self->state_file;
268 my $dir_ok = try {
269 $file->parent->mkpath unless $file->parent->is_dir;
270 1;
271 } catch {
272 warn "karr-foundation: cannot create " . $file->parent . ': '
273 . clean_error($_) . "\n";
274 0;
275 };
276 return 0 unless $dir_ok;
277  
278 # Read AND write inside one exclusive lock (#186). This is a read-modify-
279 # write over a file every board on the machine shares, and the concurrent
280 # runner has several drains going at once: two of them read "minimax: ok",
281 # one records a failure and the other a success, and last-writer-wins throws
282 # one of the two away. Losing "it works again" is the expensive direction --
283 # it parks every board on that agent for another probe interval -- so the
284 # whole sequence is serialised, not just the write.
285 #
286 # The lock is a sibling file rather than agents.state itself, because
287 # spew_utf8 writes a temporary file and renames it over the target: an flock
288 # on the state file would be a lock on an inode that is about to be replaced.
289 my $guard = $self->_lock_state;
290 my $state = $self->_read_state;
291 $edit->( $state );
292 my $ok = try {
293 $file->spew_utf8( json_encode( $state ) );
294 1;
295 } catch {
296 warn "karr-foundation: cannot write $file: " . clean_error($_) . "\n";
297 0;
298 };
299 close $guard if $guard;
300 return $ok;
301 }
302  
303 # The exclusive lock around one read-modify-write of agents.state, returned as
304 # an open file handle the caller closes when it is done -- closing the handle
305 # is what drops an flock. undef when the lock file cannot be opened at all (a
306 # read-only config directory), in which case the update goes through
307 # unserialised: that is what this did before, and the write itself reports the
308 # real problem a moment later.
309 #
310 # The wait is blocking on purpose. The critical section is a few hundred bytes
311 # of JSON, and the kernel drops an flock when its holder dies, so there is no
312 # stuck holder to time out against -- a non-blocking attempt would only turn a
313 # microsecond of waiting back into the lost update this exists to prevent.
314 sub _lock_state {
315 my ( $self ) = @_;
316 my $file = $self->state_file;
317 my $lock = $file->sibling( $file->basename . '.lock' );
318 open( my $fh, '>>', "$lock" ) or return undef;
319 unless ( flock( $fh, LOCK_EX ) ) {
320 close $fh;
321 return undef;
322 }
323 return $fh;
324 }
325  
326 # What is known about one agent right now, as the three states the spec names:
327 # { state => 'ok' }
328 # { state => 'failing', failing_since => EPOCH, next_attempt => EPOCH, ... }
329 # Timestamps are epoch seconds, as .karr.state's cooldown_until is; rendering
330 # them for a human is --status's job.
331  
332 sub availability {
333 my ( $self, $name ) = @_;
334 my $rec = $self->_read_state->{$name};
335 return { state => 'ok' } unless ref $rec eq 'HASH';
336 return { %$rec, state => 'ok' } unless ( $rec->{state} // 'ok' ) eq 'failing';
337 return { %$rec };
338 }
339  
340 # May this agent be run right now? A failing agent whose next attempt has come
341 # round answers yes -- that IS the probe. There is no separate probing run:
342 # retrying the agent on the work that is waiting is the probe, and a probe that
343 # did not do the work would be a second kind of run to reason about.
344  
345 sub available {
346 my ( $self, $name ) = @_;
347 my $rec = $self->_read_state->{$name};
348 return 1 unless ref $rec eq 'HASH';
349 return 1 unless ( $rec->{state} // 'ok' ) eq 'failing';
350 return ( $rec->{next_attempt} // 0 ) <= time ? 1 : 0;
351 }
352  
353  
354 sub probe_seconds {
355 my ( $self, $name ) = @_;
356 my $def = $self->definitions->{$name};
357 return $def->{probe_seconds} if $def && defined $def->{probe_seconds};
358 return $self->default_probe_seconds;
359 }
360  
361  
362 has default_probe_seconds => (
363 is => 'lazy',
364 builder => '_build_default_probe_seconds',
365 );
366  
367 sub _build_default_probe_seconds {
368 my ( $self ) = @_;
369 my $cfg = $self->foundation->_config_data->{probe_every};
370 return $DEFAULT_PROBE_SECONDS unless defined $cfg;
371 return _duration( 'Config probe_every', $cfg );
372 }
373  
374 # The command stopped working. Which of the many reasons it can stop working is
375 # not asked: a rate limit, a spent budget, a revoked key and a wrapper that is
376 # not installed on this machine all present as "it does not work now", and the
377 # same fixed-interval retry is the right answer to all of them. $reason is kept
378 # verbatim so an operator (and --status) can see what it was, not so anything
379 # branches on it.
380  
381 sub record_failure {
382 my ( $self, $name, $reason ) = @_;
383 my $now = time;
384 my $wait = $self->probe_seconds( $name );
385 $self->_mutate( sub {
386 my ( $state ) = @_;
387 my $rec = $state->{$name} ||= {};
388 # failing_since is the START of the outage and survives every further
389 # failure: "failing since 09:12" is what a coordinator needs, and a value
390 # that moved forward on each attempt would only ever say "just now".
391 $rec->{failing_since} = $now
392 unless ( $rec->{state} // '' ) eq 'failing' && defined $rec->{failing_since};
393 $rec->{state} = 'failing';
394 $rec->{next_attempt} = $now + $wait;
395 if ( defined $reason && length $reason ) { $rec->{last_error} = $reason }
396 else { delete $rec->{last_error} }
397 } );
398 return;
399 }
400  
401 # It worked. For an agent that was already ok this writes nothing at all --
402 # every ordinary run would otherwise rewrite the file for no news.
403 #
404 # For one that was failing it records WHEN IT WORKED AGAIN, which is the whole
405 # point of the fixed-interval retry: karr does not learn the reset rhythm, it
406 # leaves a legible trail of outages for whoever (a person, the coordination
407 # agent) wants to read one out of it.
408  
409 sub record_success {
410 my ( $self, $name ) = @_;
411 my $rec = $self->_read_state->{$name};
412 return 0 unless ref $rec eq 'HASH' && ( $rec->{state} // 'ok' ) eq 'failing';
413 my $now = time;
414 $self->_mutate( sub {
415 my ( $state ) = @_;
416 my $old = $state->{$name} // $rec;
417 my $since = $old->{failing_since} // $now;
418 my @recovered = @{ $old->{recovered} // [] };
419 push @recovered, {
420 failing_since => $since,
421 recovered_at => $now,
422 seconds => $now - $since,
423 ( defined $old->{last_error} ? ( error => $old->{last_error} ) : () ),
424 };
425 shift @recovered while @recovered > $MAX_RECOVERIES;
426 $state->{$name} = { state => 'ok', recovered => \@recovered };
427 } );
428 return 1;
429 }
430  
431 1;
432  
433 __END__