-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-wp-codebox-agent-sandbox-runner.php
More file actions
2490 lines (2144 loc) · 97.1 KB
/
class-wp-codebox-agent-sandbox-runner.php
File metadata and controls
2490 lines (2144 loc) · 97.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Host-side WP Codebox agent sandbox runner.
*
* @package WPCodebox
*/
defined( 'ABSPATH' ) || exit;
final class WP_Codebox_Agent_Sandbox_Runner {
private const SCHEMA = 'wp-codebox/agent-task-run/v1';
private const BATCH_SCHEMA = 'wp-codebox/agent-task-batch/v1';
private const FANOUT_PLAN_SCHEMA = 'wp-codebox/agent-fanout-plan/v1';
private const FANOUT_EVENT_SCHEMA = 'wp-codebox/agent-fanout-event/v1';
private const FANOUT_SCHEMA = 'wp-codebox/agent-fanout-result/v1';
private const DEFAULT_WORDPRESS_VERSION = 'latest';
private const FANOUT_MAX_CONCURRENCY = 8;
private const SESSION_SCHEMA = WP_Codebox_Agent_Task::SESSION_SCHEMA;
private const TASK_INPUT_SCHEMA = WP_Codebox_Agent_Task::INPUT_SCHEMA;
private const TOOL_DENIAL_SCHEMA = 'wp-codebox/tool-allowlist-denial/v1';
private const REMEDIATION_OUTCOME_SCHEMA = 'wp-codebox/agent-sandbox-remediation-outcome/v1';
private const COMPLETION_OUTCOME_SCHEMA = 'wp-codebox/sandbox-completion-outcome/v1';
private const AGENTS_API_RUN_OUTCOME_SCHEMA = 'agents-api.run-outcome';
private const SANDBOX_TOOL_POLICY_SCHEMA = 'wp-codebox/sandbox-tool-policy/v1';
private const AGENTS_API_RUNTIME_ENVIRONMENT = 'environment';
private const AGENTS_API_RUNTIME_CAPABILITY_SCOPE = 'capability_scope';
private const AGENTS_API_RUNTIME_LOCAL = 'runtime_local';
private const AGENTS_API_CONTROL_PLANE = 'control_plane';
/** @var array<string, callable> */
private array $callbacks;
private WP_Codebox_Host_Request_Normalizer $request_normalizer;
private WP_Codebox_Host_Tool_Policy_Validator $tool_policy_validator;
private WP_Codebox_Host_Recipe_Builder $recipe_builder;
private WP_Codebox_Host_Run_Result_Normalizer $run_result_normalizer;
private WP_Codebox_Parent_Site_Seed_Exporter $site_seed_exporter;
/**
* @param array<string, callable> $callbacks Test seams for pure-PHP smoke coverage.
*/
public function __construct( array $callbacks = array() ) {
$this->callbacks = $callbacks;
$this->request_normalizer = new WP_Codebox_Host_Request_Normalizer();
$this->tool_policy_validator = new WP_Codebox_Host_Tool_Policy_Validator();
$this->recipe_builder = new WP_Codebox_Host_Recipe_Builder();
$this->run_result_normalizer = new WP_Codebox_Host_Run_Result_Normalizer();
$this->site_seed_exporter = new WP_Codebox_Parent_Site_Seed_Exporter();
}
/**
* Run a task inside an isolated WP Codebox agent sandbox.
*
* @param array<string,mixed> $input Ability input.
* @return array<string,mixed>|WP_Error
*/
public function run( array $input ): array|WP_Error {
if ( ! $this->shell_available() ) {
return new WP_Error( 'wp_codebox_shell_unavailable', 'Shell execution is not available for WP Codebox.', array( 'status' => 500 ) );
}
$prepared = $this->prepare_agent_task_run( $input );
if ( is_wp_error( $prepared ) ) {
return $prepared;
}
$result = $this->run_command( (string) $prepared['command'], $prepared['process_secret_env'], (int) $prepared['timeout_seconds'] );
return $this->complete_agent_task_run( $prepared, $result );
}
/**
* Run multiple workers with bounded host-side concurrency.
*
* @param array<string,mixed> $input Ability input.
* @return array<string,mixed>|WP_Error
*/
public function run_fanout( array $input ): array|WP_Error {
if ( ! $this->shell_available() ) {
return new WP_Error( 'wp_codebox_shell_unavailable', 'Shell execution is not available for WP Codebox.', array( 'status' => 500 ) );
}
$workers = $this->fanout_workers( $input );
if ( is_wp_error( $workers ) ) {
return $workers;
}
$concurrency = $this->fanout_concurrency( $input );
if ( is_wp_error( $concurrency ) ) {
return $concurrency;
}
$parent_session_id = $this->sandbox_session_id( $input );
$base_artifacts = $this->clean_path( (string) ( $input['artifacts_path'] ?? $this->default_artifacts_path() ) );
$fanout_path = $base_artifacts . DIRECTORY_SEPARATOR . 'fanout';
$workers_path = $fanout_path . DIRECTORY_SEPARATOR . 'workers';
$aggregate_path = $fanout_path . DIRECTORY_SEPARATOR . 'aggregate';
foreach ( array( $workers_path, $aggregate_path . DIRECTORY_SEPARATOR . 'artifacts' ) as $path ) {
if ( ! $this->ensure_directory( $path ) ) {
return new WP_Error( 'wp_codebox_fanout_artifacts_unwritable', 'Could not create fanout artifact directories.', array( 'status' => 500, 'path' => $path ) );
}
}
$plan = array(
'schema' => self::FANOUT_PLAN_SCHEMA,
'session_id' => $parent_session_id,
'concurrency' => $concurrency,
'orchestrator' => is_array( $input['orchestrator'] ?? null ) ? $input['orchestrator'] : array(),
'workers' => array_map(
static fn( array $worker ): array => array(
'id' => (string) $worker['id'],
'agent' => (string) ( $worker['agent'] ?? $input['agent'] ?? '' ),
'goal' => (string) ( $worker['goal'] ?? '' ),
'artifact_namespace' => (string) $worker['id'],
),
$workers
),
);
$this->write_json_file( $fanout_path . DIRECTORY_SEPARATOR . 'plan.json', $plan );
$this->append_fanout_event( $fanout_path, array( 'event' => 'fanout.started', 'total' => count( $workers ), 'concurrency' => $concurrency ) );
$prepared_workers = array();
foreach ( $workers as $index => $worker ) {
$worker_id = (string) $worker['id'];
$worker_path = $workers_path . DIRECTORY_SEPARATOR . $worker_id;
$worker_input = $this->fanout_worker_input( $input, $worker, $parent_session_id, $worker_path );
$worker_prepare = $this->prepare_agent_task_run( $worker_input );
if ( is_wp_error( $worker_prepare ) ) {
$prepared_workers[] = array(
'id' => $worker_id,
'index' => $index,
'prepared' => null,
'error' => $worker_prepare,
'path' => $worker_path,
);
continue;
}
$prepared_workers[] = array(
'id' => $worker_id,
'index' => $index,
'prepared' => $worker_prepare,
'error' => null,
'path' => $worker_path,
);
}
$started_at = microtime( true );
$runs = $this->execute_prepared_fanout_workers( $prepared_workers, $concurrency, $fanout_path );
$ended_at = microtime( true );
ksort( $runs );
$runs = array_values( $runs );
$completed = count( array_filter( $runs, static fn( array $run ): bool => true === ( $run['success'] ?? false ) ) );
$cancelled = count( array_filter( $runs, static fn( array $run ): bool => 'cancelled' === ( $run['status'] ?? '' ) ) );
$failed = count( $runs ) - $completed - $cancelled;
$success = 0 === $failed && 0 === $cancelled;
$this->append_fanout_event( $fanout_path, array( 'event' => 'aggregation.started', 'completed' => $completed, 'failed' => $failed, 'cancelled' => $cancelled ) );
$result = array(
'success' => $success,
'schema' => self::FANOUT_SCHEMA,
'execution' => 'bounded-concurrent-isolated-sandboxes',
'session' => $this->fanout_parent_session( $parent_session_id, $success ? 'completed' : 'failed', $input, $fanout_path, $runs ),
'concurrency' => $concurrency,
'total' => count( $runs ),
'completed' => $completed,
'failed' => $failed,
'cancelled' => $cancelled,
'timings' => array(
'started_at' => gmdate( 'c', (int) $started_at ),
'ended_at' => gmdate( 'c', (int) $ended_at ),
'duration_ms' => (int) round( ( $ended_at - $started_at ) * 1000 ),
),
'artifacts' => array(
'schema' => 'wp-codebox/agent-fanout-artifacts/v1',
'path' => $fanout_path,
'plan' => 'plan.json',
'events' => 'events.jsonl',
'workers_path' => 'workers',
'aggregate_path' => 'aggregate',
'result' => 'result.json',
),
'orchestrator' => is_array( $input['orchestrator'] ?? null ) ? $input['orchestrator'] : array(),
'runs' => $runs,
'failures' => array_values( array_filter( $runs, static fn( array $run ): bool => true !== ( $run['success'] ?? false ) ) ),
);
$this->write_json_file( $aggregate_path . DIRECTORY_SEPARATOR . 'result.json', array( 'schema' => 'wp-codebox/agent-fanout-aggregate/v1', 'status' => $success ? 'completed' : 'failed', 'completed' => $completed, 'failed' => $failed, 'cancelled' => $cancelled ) );
$this->append_fanout_event( $fanout_path, array( 'event' => 'aggregation.completed', 'status' => $success ? 'completed' : 'failed' ) );
$this->write_json_file( $fanout_path . DIRECTORY_SEPARATOR . 'result.json', $result );
$this->append_fanout_event( $fanout_path, array( 'event' => $success ? 'fanout.completed' : 'fanout.failed', 'status' => $success ? 'completed' : 'failed', 'completed' => $completed, 'failed' => $failed, 'cancelled' => $cancelled ) );
return $result;
}
/** @param array<string,mixed> $input Ability input. @return array<string,mixed>|WP_Error */
private function prepare_agent_task_run( array $input ): array|WP_Error {
$input = $this->normalize_parent_task_request( $input );
if ( is_wp_error( $input ) ) {
return $input;
}
$task_input = $this->task_input( $input );
if ( is_wp_error( $task_input ) ) {
return $task_input;
}
$task = (string) $task_input['goal'];
$task_prompt = $this->task_input_prompt( $task_input );
$session_id = $this->sandbox_session_id( $input );
$raw_code_input = $this->reject_raw_code_input( $input );
if ( is_wp_error( $raw_code_input ) ) {
return $raw_code_input;
}
$paths = $this->resolve_component_paths( $input );
if ( is_wp_error( $paths ) ) {
return $paths;
}
$artifacts = $this->clean_path( (string) ( $input['artifacts_path'] ?? $this->default_artifacts_path() ) );
$wp_version = trim( (string) ( $input['wp'] ?? self::DEFAULT_WORDPRESS_VERSION ) );
if ( '' === $wp_version ) {
$wp_version = self::DEFAULT_WORDPRESS_VERSION;
}
$bin = trim( (string) ( $input['wp_codebox_bin'] ?? $this->default_bin() ) );
if ( '' === $bin || ! preg_match( '#^[A-Za-z0-9_./:@+-]+$#', $bin ) ) {
return new WP_Error( 'wp_codebox_bin_invalid', 'wp_codebox_bin must be a command name or path without shell metacharacters.', array( 'status' => 400 ) );
}
$command_prefix = $this->command_prefix( $bin );
if ( is_wp_error( $command_prefix ) ) {
return $command_prefix;
}
$preview_args = $this->preview_args( $input );
if ( is_wp_error( $preview_args ) ) {
return $preview_args;
}
$inheritance_payload = $this->inheritance_resolution_payload( $input );
$recipe_payload = $this->write_agent_recipe( $paths, $input, array( $task_prompt ), $wp_version, $inheritance_payload['inheritance_audit'] );
if ( is_wp_error( $recipe_payload ) ) {
return $recipe_payload;
}
$recipe_file = (string) $recipe_payload['path'];
$command = sprintf(
'%s recipe-run --recipe %s --artifacts %s --json',
$command_prefix,
escapeshellarg( $recipe_file ),
escapeshellarg( $artifacts )
);
$command .= $preview_args;
return array(
'input' => $input,
'task_input' => $task_input,
'task' => $task,
'session_id' => $session_id,
'paths' => $paths,
'artifacts' => $artifacts,
'wp_version' => $wp_version,
'command' => $command,
'process_secret_env' => $inheritance_payload['process_secret_env'],
'timeout_seconds' => $this->task_timeout_seconds( $input ),
'recipe_file' => $recipe_file,
'cleanup_paths' => $recipe_payload['cleanup_paths'],
);
}
/** @param array<string,mixed> $prepared Prepared run. @param array<string,mixed> $result Command result. @return array<string,mixed>|WP_Error */
private function complete_agent_task_run( array $prepared, array $result ): array|WP_Error {
return $this->run_result_normalizer->normalize(
$prepared,
$result,
array(
'bound_output' => fn( string $output ): string => $this->bound_output( $output ),
'decode_json_output' => fn( string $output ): array|WP_Error => $this->decode_json_output( $output ),
'strict_remediation_outcome' => fn( array $task_input ): bool => $this->strict_remediation_outcome( $task_input ),
'remediation_outcome' => fn( array $run, int $exit_code, string $output ): array => $this->remediation_outcome( $run, $exit_code, $output ),
'sandbox_session' => fn( string $session_id, string $status, array $input, array $run, string $artifacts ): array => $this->sandbox_session( $session_id, $status, $input, $run, $artifacts ),
'completion_outcome' => fn( array $run ): array => $this->completion_outcome( $run ),
'run_diagnostics' => fn( array $run, int $exit_code, ?array $outcome ): array => $this->run_diagnostics( $run, $exit_code, $outcome ),
'evidence_refs' => fn( array $session, array $run ): array => $this->evidence_refs( $session, $run ),
'run_metadata' => fn( string $session_id, array $input, string $wp_version, array $run ): array => $this->run_metadata( $session_id, $input, $wp_version, $run ),
)
);
}
/**
* Run multiple tasks, each in its own isolated WP Codebox agent sandbox.
*
* @param array<string,mixed> $input Ability input.
* @return array<string,mixed>|WP_Error
*/
public function run_batch( array $input ): array|WP_Error {
if ( ! $this->shell_available() ) {
return new WP_Error( 'wp_codebox_shell_unavailable', 'Shell execution is not available for WP Codebox.', array( 'status' => 500 ) );
}
$input = $this->normalize_parent_task_request( $input );
if ( is_wp_error( $input ) ) {
return $input;
}
$task_inputs = $this->task_inputs( $input );
if ( is_wp_error( $task_inputs ) ) {
return $task_inputs;
}
if ( empty( $task_inputs ) ) {
return new WP_Error( 'wp_codebox_tasks_missing', 'tasks must include at least one task.', array( 'status' => 400 ) );
}
$tasks = array_map( static fn( array $task_input ): string => (string) $task_input['goal'], $task_inputs );
$session_id = $this->sandbox_session_id( $input );
$paths = $this->resolve_component_paths( $input );
if ( is_wp_error( $paths ) ) {
return $paths;
}
$artifacts = $this->clean_path( (string) ( $input['artifacts_path'] ?? $this->default_artifacts_path() ) );
$wp_version = trim( (string) ( $input['wp'] ?? self::DEFAULT_WORDPRESS_VERSION ) );
if ( '' === $wp_version ) {
$wp_version = self::DEFAULT_WORDPRESS_VERSION;
}
$bin = trim( (string) ( $input['wp_codebox_bin'] ?? $this->default_bin() ) );
if ( '' === $bin || ! preg_match( '#^[A-Za-z0-9_./:@+-]+$#', $bin ) ) {
return new WP_Error( 'wp_codebox_bin_invalid', 'wp_codebox_bin must be a command name or path without shell metacharacters.', array( 'status' => 400 ) );
}
$runs = array();
foreach ( $task_inputs as $index => $task_input ) {
$task_input_request = array_merge( $input, $task_input );
unset( $task_input_request['tasks'], $task_input_request['task'], $task_input_request['concurrency'], $task_input_request['session_id'] );
if ( ! empty( $input['sandbox_session_id'] ) ) {
$task_input_request['sandbox_session_id'] = $session_id . ':' . ( $index + 1 );
}
$task_result = $this->run( $task_input_request );
if ( is_wp_error( $task_result ) ) {
$runs[] = array(
'index' => $index,
'task' => (string) $task_input['goal'],
'task_input' => $task_input,
'success' => false,
'status' => 'failed',
'error' => $this->error_payload( $task_result ),
);
continue;
}
$runs[] = array(
'index' => $index,
'task' => (string) $task_input['goal'],
'task_input' => $task_input,
'success' => true,
'status' => 'completed',
'exit_code' => (int) ( $task_result['exit_code'] ?? 0 ),
'session' => $task_result['session'] ?? array(),
'artifact_id' => (string) ( $task_result['session']['artifacts']['bundle_id'] ?? '' ),
'preview_url' => (string) ( $task_result['session']['artifacts']['preview_url'] ?? '' ),
'artifacts' => $task_result['session']['artifacts'] ?? array(),
'agent_result' => $task_result['agent_result'] ?? array(),
'agent_task_result' => $task_result['agent_task_result'] ?? array(),
'completion_outcome' => $task_result['completion_outcome'] ?? array(),
'run' => $task_result['run'] ?? array(),
);
}
$completed = count( array_filter( $runs, static fn( array $run ): bool => true === ( $run['success'] ?? false ) ) );
$failed = count( $runs ) - $completed;
return array(
'success' => 0 === $failed,
'schema' => self::BATCH_SCHEMA,
'session' => $this->sandbox_session( $session_id, 'completed', $input, array(), $artifacts ),
'tasks' => $tasks,
'task_inputs' => $task_inputs,
'execution' => 'sequential-isolated-sandboxes',
'total' => count( $runs ),
'completed' => $completed,
'failed' => $failed,
'wp' => $wp_version,
'paths' => $paths,
'artifacts' => $artifacts,
'runs' => $runs,
);
}
/** @param array<string,mixed> $input Ability input. @return array<int,array<string,mixed>>|WP_Error */
private function fanout_workers( array $input ): array|WP_Error {
$workers = is_array( $input['workers'] ?? null ) ? $input['workers'] : array();
if ( empty( $workers ) ) {
return new WP_Error( 'wp_codebox_fanout_workers_missing', 'workers must include at least one worker.', array( 'status' => 400 ) );
}
$normalized = array();
$seen = array();
foreach ( $workers as $index => $worker ) {
if ( ! is_array( $worker ) ) {
return new WP_Error( 'wp_codebox_fanout_worker_invalid', 'Each fanout worker must be an object.', array( 'status' => 400, 'index' => $index ) );
}
$id = trim( (string) ( $worker['id'] ?? '' ) );
if ( '' === $id || ! preg_match( '/^[A-Za-z0-9][A-Za-z0-9_.-]*$/', $id ) ) {
return new WP_Error( 'wp_codebox_fanout_worker_id_invalid', 'Each fanout worker requires a stable alphanumeric id.', array( 'status' => 400, 'index' => $index ) );
}
if ( isset( $seen[ $id ] ) ) {
return new WP_Error( 'wp_codebox_fanout_worker_id_duplicate', 'Fanout worker ids must be unique.', array( 'status' => 400, 'worker_id' => $id ) );
}
$goal = trim( (string) ( $worker['goal'] ?? '' ) );
if ( '' === $goal ) {
return new WP_Error( 'wp_codebox_fanout_worker_goal_missing', 'Each fanout worker requires goal.', array( 'status' => 400, 'worker_id' => $id ) );
}
$seen[ $id ] = true;
$worker['id'] = $id;
$worker['goal'] = $goal;
$normalized[] = $worker;
}
return $normalized;
}
private function fanout_concurrency( array $input ): int|WP_Error {
$concurrency = isset( $input['concurrency'] ) ? (int) $input['concurrency'] : 1;
$max = self::FANOUT_MAX_CONCURRENCY;
if ( function_exists( 'apply_filters' ) ) {
$max = max( 1, (int) apply_filters( 'wp_codebox_agent_fanout_max_concurrency', $max ) );
}
if ( $concurrency < 1 || $concurrency > $max ) {
return new WP_Error( 'wp_codebox_fanout_concurrency_invalid', 'Fanout concurrency must be between 1 and ' . $max . '.', array( 'status' => 400, 'max' => $max ) );
}
return $concurrency;
}
/** @param array<string,mixed> $parent Parent input. @param array<string,mixed> $worker Worker input. @return array<string,mixed> */
private function fanout_worker_input( array $parent, array $worker, string $parent_session_id, string $worker_path ): array {
$worker_artifacts_path = $worker_path . DIRECTORY_SEPARATOR . 'artifacts';
$this->ensure_directory( $worker_artifacts_path );
$input = array_merge( $parent, $worker );
unset( $input['workers'], $input['dependencies'], $input['aggregation'], $input['concurrency'] );
$input['goal'] = (string) $worker['goal'];
$input['sandbox_session_id'] = $parent_session_id . ':' . (string) $worker['id'];
$input['artifacts_path'] = $worker_artifacts_path;
$input['context'] = is_array( $input['context'] ?? null ) ? $input['context'] : array();
$input['context']['fanout'] = array(
'parent_session_id' => $parent_session_id,
'worker_id' => (string) $worker['id'],
'artifact_namespace' => (string) $worker['id'],
);
if ( isset( $worker['timeout_seconds'] ) && ! isset( $worker['task_timeout_seconds'] ) ) {
$input['task_timeout_seconds'] = (int) $worker['timeout_seconds'];
}
return $input;
}
/** @param array<int,array<string,mixed>> $prepared_workers Prepared workers. @return array<int,array<string,mixed>> */
private function execute_prepared_fanout_workers( array $prepared_workers, int $concurrency, string $fanout_path ): array {
$runs = array();
$active = array();
$next = 0;
$total = count( $prepared_workers );
while ( $next < $total || ! empty( $active ) ) {
while ( count( $active ) < $concurrency && $next < $total ) {
$item = $prepared_workers[ $next ];
++$next;
if ( is_wp_error( $item['error'] ?? null ) ) {
$runs[ (int) $item['index'] ] = $this->fanout_worker_error_result( $item, $item['error'], 0, 0 );
$this->write_json_file( (string) $item['path'] . DIRECTORY_SEPARATOR . 'result.json', $runs[ (int) $item['index'] ] );
continue;
}
$started = $this->start_prepared_fanout_worker( $item );
if ( is_wp_error( $started ) ) {
$runs[ (int) $item['index'] ] = $this->fanout_worker_error_result( $item, $started, 0, 0 );
$this->write_json_file( (string) $item['path'] . DIRECTORY_SEPARATOR . 'result.json', $runs[ (int) $item['index'] ] );
continue;
}
$active[] = $started;
$this->append_fanout_event( $fanout_path, array( 'event' => 'worker.started', 'worker_id' => (string) $item['id'], 'active' => count( $active ) ) );
}
foreach ( $active as $active_index => &$worker ) {
$worker['output'] .= (string) stream_get_contents( $worker['pipes'][1] );
$worker['error_output'] .= (string) stream_get_contents( $worker['pipes'][2] );
$status = proc_get_status( $worker['process'] );
$running = (bool) ( $status['running'] ?? false );
$elapsed = microtime( true ) - (float) $worker['started_at'];
$timeout = (int) ( $worker['prepared']['timeout_seconds'] ?? 0 );
if ( $running && $timeout > 0 && $elapsed >= $timeout ) {
proc_terminate( $worker['process'] );
$worker['timed_out'] = true;
$running = false;
}
if ( $running ) {
continue;
}
$worker['output'] .= (string) stream_get_contents( $worker['pipes'][1] );
$worker['error_output'] .= (string) stream_get_contents( $worker['pipes'][2] );
fclose( $worker['pipes'][1] );
fclose( $worker['pipes'][2] );
$exit_code = proc_close( $worker['process'] );
if ( true === ( $worker['timed_out'] ?? false ) ) {
$exit_code = 124;
}
$result = array(
'exit_code' => $exit_code,
'output' => trim( (string) $worker['output'] . "\n" . (string) $worker['error_output'] ),
);
if ( true === ( $worker['timed_out'] ?? false ) ) {
$result['timed_out'] = true;
$result['timeout_seconds'] = $timeout;
}
$completed = $this->complete_agent_task_run( $worker['prepared'], $result );
$runs[ (int) $worker['index'] ] = is_wp_error( $completed ) ? $this->fanout_worker_error_result( $worker, $completed, (float) $worker['started_at'], microtime( true ) ) : $this->fanout_worker_success_result( $worker, $completed, (float) $worker['started_at'], microtime( true ) );
$this->write_json_file( (string) $worker['path'] . DIRECTORY_SEPARATOR . 'result.json', $runs[ (int) $worker['index'] ] );
$this->append_fanout_event( $fanout_path, array( 'event' => true === ( $runs[ (int) $worker['index'] ]['success'] ?? false ) ? 'worker.completed' : 'worker.failed', 'worker_id' => (string) $worker['id'], 'status' => (string) $runs[ (int) $worker['index'] ]['status'] ) );
unset( $active[ $active_index ] );
}
unset( $worker );
$active = array_values( $active );
if ( ! empty( $active ) ) {
usleep( 50000 );
}
}
return $runs;
}
/** @param array<string,mixed> $item Prepared worker item. @return array<string,mixed>|WP_Error */
private function start_prepared_fanout_worker( array $item ): array|WP_Error {
if ( ! function_exists( 'proc_open' ) ) {
return new WP_Error( 'wp_codebox_proc_open_unavailable', 'Fanout execution requires proc_open support.', array( 'status' => 500 ) );
}
$prepared = is_array( $item['prepared'] ?? null ) ? $item['prepared'] : array();
$descriptor_spec = array(
1 => array( 'pipe', 'w' ),
2 => array( 'pipe', 'w' ),
);
$current_env = getenv();
$secret_env = is_array( $prepared['process_secret_env'] ?? null ) ? $prepared['process_secret_env'] : array();
$process = proc_open( (string) $prepared['command'], $descriptor_spec, $pipes, null, array_merge( is_array( $current_env ) ? $current_env : array(), $_ENV, $secret_env ) );
if ( ! is_resource( $process ) ) {
return new WP_Error( 'wp_codebox_fanout_worker_start_failed', 'Could not start fanout worker process.', array( 'status' => 500, 'worker_id' => (string) $item['id'] ) );
}
stream_set_blocking( $pipes[1], false );
stream_set_blocking( $pipes[2], false );
return array_merge(
$item,
array(
'process' => $process,
'pipes' => $pipes,
'started_at' => microtime( true ),
'output' => '',
'error_output' => '',
)
);
}
/** @param array<string,mixed> $worker Worker metadata. @param array<string,mixed> $result Worker result. @return array<string,mixed> */
private function fanout_worker_success_result( array $worker, array $result, float $started_at, float $ended_at ): array {
$session = is_array( $result['session'] ?? null ) ? $result['session'] : array();
$artifacts = is_array( $session['artifacts'] ?? null ) ? $session['artifacts'] : array();
return array(
'worker_id' => (string) $worker['id'],
'index' => (int) $worker['index'],
'success' => true,
'status' => 'completed',
'agent' => (string) ( $worker['prepared']['input']['agent'] ?? '' ),
'exit_code' => (int) ( $result['exit_code'] ?? 0 ),
'session' => $session,
'artifacts' => array_merge( $artifacts, array( 'namespace' => (string) $worker['id'], 'result' => 'result.json' ) ),
'diagnostics' => is_array( $result['diagnostics'] ?? null ) ? $result['diagnostics'] : array(),
'evidence_refs' => is_array( $result['evidence_refs'] ?? null ) ? $result['evidence_refs'] : array(),
'completion_outcome' => is_array( $result['completion_outcome'] ?? null ) ? $result['completion_outcome'] : array(),
'timings' => array(
'started_at' => gmdate( 'c', (int) $started_at ),
'ended_at' => gmdate( 'c', (int) $ended_at ),
'duration_ms' => (int) round( ( $ended_at - $started_at ) * 1000 ),
),
);
}
/** @param array<string,mixed> $worker Worker metadata. */
private function fanout_worker_error_result( array $worker, WP_Error $error, float $started_at, float $ended_at ): array {
$prepared = is_array( $worker['prepared'] ?? null ) ? $worker['prepared'] : array();
$input = is_array( $prepared['input'] ?? null ) ? $prepared['input'] : array();
$artifacts = (string) ( $prepared['artifacts'] ?? ( (string) $worker['path'] . DIRECTORY_SEPARATOR . 'artifacts' ) );
return array(
'worker_id' => (string) $worker['id'],
'index' => (int) $worker['index'],
'success' => false,
'status' => 'failed',
'agent' => (string) ( $input['agent'] ?? '' ),
'session' => array_filter(
array(
'schema' => self::SESSION_SCHEMA,
'id' => (string) ( $prepared['session_id'] ?? '' ),
'status' => 'failed',
),
static fn( mixed $value ): bool => '' !== $value
),
'artifacts' => array(
'path' => $artifacts,
'namespace' => (string) $worker['id'],
'result' => 'result.json',
),
'error' => $this->error_payload( $error ),
'timings' => array_filter(
array(
'started_at' => $started_at > 0 ? gmdate( 'c', (int) $started_at ) : '',
'ended_at' => $ended_at > 0 ? gmdate( 'c', (int) $ended_at ) : '',
'duration_ms' => $started_at > 0 && $ended_at > 0 ? (int) round( ( $ended_at - $started_at ) * 1000 ) : null,
),
static fn( mixed $value ): bool => null !== $value && '' !== $value
),
);
}
/** @param array<string,mixed> $input Ability input. @param array<int,array<string,mixed>> $runs Worker runs. */
private function fanout_parent_session( string $session_id, string $status, array $input, string $fanout_path, array $runs ): array {
$children = array_map(
static fn( array $run ): array => array_filter(
array(
'worker_id' => (string) ( $run['worker_id'] ?? '' ),
'session_id' => (string) ( $run['session']['id'] ?? '' ),
'status' => (string) ( $run['status'] ?? '' ),
'artifacts' => is_array( $run['artifacts'] ?? null ) ? $run['artifacts'] : array(),
),
static fn( mixed $value ): bool => '' !== $value && array() !== $value
),
$runs
);
$session = WP_Codebox_Agent_Task::session(
$session_id,
$status,
$input,
array(
'path' => $fanout_path,
'plan' => 'plan.json',
'events' => 'events.jsonl',
'result' => 'result.json',
'aggregate' => 'aggregate/result.json',
)
);
$session['children'] = $children;
return $session;
}
private function ensure_directory( string $path ): bool {
return is_dir( $path ) || mkdir( $path, 0777, true );
}
/** @param array<string,mixed> $data Data to write. */
private function write_json_file( string $path, array $data ): void {
$this->ensure_directory( dirname( $path ) );
$encoded = function_exists( 'wp_json_encode' ) ? wp_json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) : json_encode( $data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
if ( is_string( $encoded ) ) {
file_put_contents( $path, $encoded . "\n" );
}
}
/** @param array<string,mixed> $event Event data. */
private function append_fanout_event( string $fanout_path, array $event ): void {
$event = array_merge( array( 'schema' => self::FANOUT_EVENT_SCHEMA, 'time' => gmdate( 'c' ) ), $event );
$encoded = function_exists( 'wp_json_encode' ) ? wp_json_encode( $event, JSON_UNESCAPED_SLASHES ) : json_encode( $event, JSON_UNESCAPED_SLASHES );
if ( is_string( $encoded ) ) {
file_put_contents( $fanout_path . DIRECTORY_SEPARATOR . 'events.jsonl', $encoded . "\n", FILE_APPEND );
}
}
/**
* @param array<string,mixed> $input Ability input.
* @return array<int,array<string,mixed>>|WP_Error
*/
private function resolve_component_paths( array $input ): array|WP_Error {
$contracts = $this->component_contracts( $input );
foreach ( $contracts as $contract ) {
$path = (string) ( $contract['path'] ?? '' );
if ( '' === $path ) {
if ( ! empty( $contract['required'] ) ) {
return new WP_Error( 'wp_codebox_component_path_missing', sprintf( 'WP Codebox component path %s is missing or not a directory.', (string) ( $contract['slug'] ?? 'unknown' ) ), array( 'status' => 400 ) );
}
continue;
}
if ( ! is_dir( $path ) ) {
return new WP_Error( 'wp_codebox_component_path_missing', sprintf( 'WP Codebox component path %s is missing or not a directory.', (string) ( $contract['slug'] ?? 'unknown' ) ), array( 'status' => 400, 'slug' => (string) ( $contract['slug'] ?? '' ), 'path' => $path ) );
}
}
return $contracts;
}
/** @param array<string,mixed> $input Ability input. @return array<int,array<string,mixed>> */
private function component_contracts( array $input ): array {
$contracts = array();
foreach ( $this->configured_component_contracts() as $contract ) {
if ( is_array( $contract ) ) {
$contracts[] = $contract;
}
}
foreach ( is_array( $input['component_contracts'] ?? null ) ? $input['component_contracts'] : array() as $contract ) {
if ( is_array( $contract ) ) {
$contracts[] = $contract;
}
}
$normalized = array();
foreach ( $contracts as $contract ) {
$slug = $this->component_slug( (string) ( $contract['slug'] ?? $contract['component'] ?? $contract['name'] ?? '' ) );
if ( '' === $slug ) {
continue;
}
$path = $this->clean_path( (string) ( $contract['path'] ?? $contract['source'] ?? '' ) );
$normalized[ $slug ] = array_filter(
array_merge(
$contract,
array(
'slug' => $slug,
'path' => $path,
'activate' => (bool) ( $contract['activate'] ?? false ),
'loadAs' => (string) ( $contract['loadAs'] ?? 'mu-plugin' ),
)
),
static fn( mixed $value ): bool => null !== $value && '' !== $value
);
}
return array_values( $normalized );
}
/** @return array<int,array<string,mixed>> */
private function configured_component_contracts(): array {
$contracts = array();
$option = $this->config_option( 'wp_codebox_component_contracts', array() );
if ( is_array( $option ) ) {
$contracts = $option;
}
if ( function_exists( 'apply_filters' ) ) {
$contracts = apply_filters( 'wp_codebox_component_contracts', $contracts );
}
return is_array( $contracts ) ? $contracts : array();
}
private function component_slug( string $slug ): string {
$slug = strtolower( trim( $slug ) );
$slug = str_replace( '_', '-', $slug );
return preg_replace( '/[^a-z0-9-]+/', '', $slug ) ?? '';
}
private function shell_available(): bool {
if ( isset( $this->callbacks['shell_available'] ) ) {
return (bool) ( $this->callbacks['shell_available'] )();
}
return function_exists( 'exec' ) && function_exists( 'shell_exec' );
}
/** @param array<string,mixed> $input Ability input. @return true|WP_Error */
private function reject_raw_code_input( array $input ): true|WP_Error {
foreach ( array( 'code', 'code_file' ) as $field ) {
if ( ! array_key_exists( $field, $input ) ) {
continue;
}
$value = $input[ $field ];
if ( null === $value || '' === trim( (string) $value ) ) {
continue;
}
return new WP_Error(
'wp_codebox_raw_code_forbidden',
'Raw PHP code inputs are not accepted by wp-codebox/run-agent-task. Use the operator CLI debug path for raw PHP execution.',
array(
'status' => 400,
'field' => $field,
)
);
}
return true;
}
/** @param array<string,mixed> $input Ability input. @return array<string,mixed>|WP_Error */
private function normalize_parent_task_request( array $input ): array|WP_Error {
return $this->request_normalizer->normalize( $input );
}
private function agent_slug( array $input ): string {
$agent = trim( (string) ( $input['agent'] ?? '' ) );
if ( '' !== $agent ) {
return $agent;
}
if ( function_exists( 'apply_filters' ) ) {
$agent = (string) apply_filters( 'wp_codebox_default_agent', '' );
}
return '' !== trim( $agent ) ? trim( $agent ) : 'sandbox-agent';
}
private function mode( array $input ): string {
$mode = trim( (string) ( $input['mode'] ?? '' ) );
return '' !== $mode ? $mode : 'sandbox';
}
private function provider( array $input, ?array $inheritance = null ): string {
$provider = trim( (string) ( $input['provider'] ?? '' ) );
if ( '' !== $provider ) {
return $provider;
}
$inheritance_provider = $this->inheritance_provider( $input, $inheritance );
if ( '' !== $inheritance_provider ) {
return $inheritance_provider;
}
if ( function_exists( 'apply_filters' ) ) {
$provider = (string) apply_filters( 'wp_codebox_default_provider', '' );
}
return trim( $provider );
}
private function model( array $input, ?array $inheritance = null ): string {
$model = trim( (string) ( $input['model'] ?? '' ) );
if ( '' !== $model ) {
return $model;
}
$inheritance_model = $this->inheritance_model( $input, $inheritance );
if ( '' !== $inheritance_model ) {
return $inheritance_model;
}
if ( function_exists( 'apply_filters' ) ) {
$model = (string) apply_filters( 'wp_codebox_default_model', '' );
}
return trim( $model );
}
/** @param array<string,mixed> $input Ability input. @return string[] */
private function provider_plugin_paths( array $input, ?array $inheritance = null ): array {
$paths = is_array( $input['provider_plugin_paths'] ?? null ) ? $input['provider_plugin_paths'] : array();
$paths = array_merge( is_array( $paths ) ? $paths : array(), $this->inheritance_provider_plugin_paths( $input, $inheritance ) );
if ( ! is_array( $paths ) ) {
return array();
}
return array_values(
array_unique(
array_filter(
array_map(
fn( $path ): string => $this->clean_path( (string) $path ),
$paths
),
static fn( string $path ): bool => '' !== $path && is_dir( $path )
)
)
);
}
/** @param array<string,mixed> $input Ability input. @return string[] */
private function secret_env_names( array $input, ?array $inheritance = null ): array {
$names = is_array( $input['secret_env'] ?? null ) ? $input['secret_env'] : array();
$names = array_merge( $names, $this->inheritance_secret_env_names( $input, $inheritance ) );
if ( empty( $names ) && function_exists( 'apply_filters' ) ) {
$names = apply_filters( 'wp_codebox_default_secret_env', array() );
}
if ( ! is_array( $names ) ) {
return array();
}
return array_values(
array_unique(
array_filter(
array_map(
static fn( $name ): string => trim( (string) $name ),
$names
),
static fn( string $name ): bool => 1 === preg_match( '/^[A-Z_][A-Z0-9_]*$/', $name )
)
)
);
}
/** @param array<string,mixed> $input Ability input. @return array{connectors:string[],settings:string[]} */
private function inheritance_request( array $input ): array {
return WP_Codebox_Inheritance::request( $input );
}
/** @param array<string,mixed> $input Ability input. @return array{connectors:array<int,array<string,mixed>>,settings:array<int,array<string,mixed>>} */
private function inheritance_resolution( array $input ): array {
return $this->inheritance_resolution_payload( $input )['inheritance_audit'];
}
/** @param array<string,mixed> $input Ability input. @return array{inheritance_audit:array{connectors:array<int,array<string,mixed>>,settings:array<int,array<string,mixed>>},process_secret_env:array<string,string>} */
private function inheritance_resolution_payload( array $input ): array {
$payload = WP_Codebox_Inheritance::resolution_payload( $input, fn( string $path ): string => $this->clean_path( $path ) );
$secret_env_names = $this->secret_env_names( $input, $payload['inheritance'] );
return array(
'inheritance_audit' => $payload['inheritance'],
'process_secret_env' => array_merge(
$this->parent_process_secret_env_values( $secret_env_names ),
$this->inheritance_process_secret_env_values( $payload['resolution']['connectors'] ?? array() )
),
);
}
/** @param string[] $names Secret env names declared by the caller. @return array<string,string> */
private function parent_process_secret_env_values( array $names ): array {
$values = array();
foreach ( $names as $name ) {
$name = trim( (string) $name );
if ( 1 !== preg_match( '/^[A-Z_][A-Z0-9_]*$/', $name ) ) {
continue;
}
$value = getenv( $name );
if ( false === $value && isset( $_ENV[ $name ] ) ) {
$value = $_ENV[ $name ];
}
if ( false === $value && isset( $_SERVER[ $name ] ) ) {
$value = $_SERVER[ $name ];
}
$value = false === $value ? '' : (string) $value;
if ( '' !== $value ) {
$values[ $name ] = $value;
}
}
return $values;
}
/** @param array<int,mixed> $connectors Raw inheritance connector rows. @return array<string,string> */
private function inheritance_process_secret_env_values( array $connectors ): array {
$values = array();
foreach ( $connectors as $connector ) {
if ( ! is_array( $connector ) ) {
continue;
}
$values = array_merge( $values, $this->process_secret_env_values_from_connector( $connector ) );
}
return $values;
}
/** @param array<string,mixed> $connector Raw inheritance connector row. @return array<string,string> */
private function process_secret_env_values_from_connector( array $connector ): array {
$values = array();
foreach ( array( 'secret_env_values', 'secretEnvValues' ) as $field ) {
if ( is_array( $connector[ $field ] ?? null ) ) {
$values = array_merge( $values, $this->sanitize_process_secret_env_values( $connector[ $field ] ) );
}
}
$credentials = is_array( $connector['credentials'] ?? null ) ? $connector['credentials'] : array();
foreach ( is_array( $credentials['secrets'] ?? null ) ? $credentials['secrets'] : array() as $secret ) {
if ( ! is_array( $secret ) || ! isset( $secret['value'] ) ) {