-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclass-wp-agent-conversation-loop.php
More file actions
2930 lines (2635 loc) · 112 KB
/
Copy pathclass-wp-agent-conversation-loop.php
File metadata and controls
2930 lines (2635 loc) · 112 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
/**
* Generic agent conversation loop facade.
*
* @package AgentsAPI
*/
namespace AgentsAPI\AI;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Call;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Declaration;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Execution_Core;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Executor;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Parameters;
use AgentsAPI\AI\Tools\WP_Agent_Tool_Result;
use AgentsAPI\Core\Database\Chat\WP_Agent_Conversation_Lock;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Sequences multi-turn agent execution around caller-owned adapters.
*
* The loop owns neutral transcript normalization, optional compaction,
* turn sequencing, result validation, stop-condition dispatch, optional
* tool-call mediation, completion policy, transcript persistence, and
* lifecycle event emission. Callers supply prompt assembly, provider/model
* dispatch, and concrete tool execution through adapters.
*/
class WP_Agent_Conversation_Loop {
/**
* Run a conversation loop.
*
* The turn runner receives `(array $messages, array $context)` and must return
* an array. Callers may also pass `provider_turn_adapter` in options; that
* adapter receives `WP_Agent_Provider_Turn_Request` and returns a normalized
* `WP_Agent_Provider_Turn_Result` shape while the loop keeps ownership of
* continuation and mediated tool execution. Provider-turn results may include
* `continuation_messages` to append caller-supplied follow-up messages before
* the next turn without taking over the whole runner. When tool mediation is
* enabled (`tool_executor` + `tool_declarations`), the turn runner or
* provider-turn adapter can return a `tool_calls` key (array of `{name,
* parameters}`) and the loop handles execution internally. Otherwise the turn
* runner must return an `WP_Agent_Conversation_Result`-compatible array as
* before.
*
* Supported options:
*
* - `max_turns` (int): Maximum turns to run. Defaults to 1.
* - `budgets` (WP_Agent_Iteration_Budget[]): Named iteration budgets for bounded execution.
* - `context` (array): Caller-owned context passed to adapters.
* - `should_continue` (callable|null): Caller-owned continuation policy.
* Defaults to `null` in the caller-managed path (which causes the loop to break
* after one turn unless the caller supplies a callback). When tool
* mediation is enabled (`tool_executor` + `tool_declarations` provided),
* defaults to a callable that returns `true` while the latest turn emitted
* `tool_calls` — so the loop stops on natural completion (empty `tool_calls`)
* and otherwise keeps going until `completion_policy` fires, `max_turns` is
* reached, or a budget is exceeded. Callers can pass `'__return_true'` to
* opt into the historical continue-always behavior.
* - `compaction_policy` (array|null): Optional compaction policy.
* - `summarizer` (callable|null): Optional compaction summarizer.
* - `provider_turn_adapter` (WP_Agent_Provider_Turn_Adapter|callable|null): Provider dispatch adapter.
* - `tool_executor` (WP_Agent_Tool_Executor|null): Tool execution adapter.
* - `tool_declarations` (array|null): Tool declarations keyed by name.
* - `pre_tool_mediator` (callable|null): Optional synchronous decision callback
* invoked after a mediated tool call is prepared and before execution. Receives
* one array context with transcript messages, raw/prepared tool call data,
* declaration, turn context, and prior mediated results. Return
* `{ action: 'proceed'|'reject'|'replace_result'|'pending', ... }`.
* - `post_tool_result_diagnostics` (callable|null): Optional synchronous callback
* for host diagnostics after mediated execution. Receives an audit-oriented
* context and returns metadata stored with the tool execution result.
* - `completion_policy` (WP_Agent_Conversation_Completion_Policy|null): Typed completion policy.
* - `spin_detector` (WP_Agent_Spin_Detector|null): Optional repeated tool-call detector.
* - `identical_failure_tracker` (WP_Agent_Identical_Failure_Tracker|null): Optional repeated failure nudger.
* - `tool_result_truncator` (WP_Agent_Tool_Result_Truncator|null): Optional mediated tool result truncator.
* - `interrupt_source` (callable|null): Optional source checked between turns. Returns a message array or null.
* - `transcript_lock` or `transcript_lock_store` (WP_Agent_Conversation_Lock|null): Optional transcript lock.
* - `transcript_session_id` (string): Session ID to lock when a lock store is provided.
* - `transcript_lock_ttl` (int): Lock TTL in seconds. Defaults to 300.
* - `transcript_persister` (WP_Agent_Transcript_Persister|null): Transcript persister.
* - `runtime_tool_request_store` (WP_Agent_Runtime_Tool_Request_Store|null): Optional durable store for pending runtime-tool requests.
* - `on_event` (callable|null): Caller-owned lifecycle event sink `fn(string $event, array $payload)`.
*
* @param array<int, array<string, mixed>> $messages Initial transcript messages.
* @param callable|null $turn_runner Caller-owned turn adapter.
* @param array<string, mixed> $options Loop options.
* @return array<string, mixed> Normalized conversation result.
*/
public static function run( array $messages, ?callable $turn_runner = null, array $options = array() ): array {
$runtime_overrides = self::resolve_runtime_overrides( $options );
$options = self::apply_runtime_overrides_to_options( $options, $runtime_overrides );
$max_turns = self::max_turns( $options['max_turns'] ?? 1 );
$context = self::normalize_assoc_array( $options['context'] ?? array() );
$tool_executor = self::resolve_tool_executor( $options );
$rejected_declarations = array();
$tool_declarations = self::resolve_tool_declarations( $options, $rejected_declarations );
$should_continue = self::resolve_should_continue( $options, $tool_executor, $tool_declarations );
$completion_policy = self::resolve_completion_policy( $options );
$transcript_persister = self::resolve_transcript_persister( $options );
$runtime_tool_store = self::resolve_runtime_tool_request_store( $options );
$transcript_lock = self::resolve_transcript_lock( $options );
$on_event = self::resolve_event_sink( $options );
$spin_detector = self::resolve_spin_detector( $options );
$failure_tracker = self::resolve_identical_failure_tracker( $options );
$result_truncator = self::resolve_tool_result_truncator( $options );
$tool_call_gate = self::resolve_tool_call_gate( $options );
$pre_tool_mediator = self::compose_tool_call_gate_mediator( $tool_call_gate, self::resolve_pre_tool_mediator( $options ) );
$post_tool_diagnostics = self::resolve_post_tool_result_diagnostics( $options );
$interrupt_source = self::resolve_interrupt_source( $options );
$request = self::resolve_request( $messages, $options );
$lock_session_id = self::resolve_lock_session_id( $options, $request );
$run_id = self::resolve_run_id( $options, $request );
$lock_ttl = self::resolve_lock_ttl( $options );
$lock_token = null;
$budget_resolution = self::resolve_budgets( $options, $max_turns );
$budgets = $budget_resolution['budgets'];
$has_explicit_turns = $budget_resolution['has_explicit_turns'];
$turn_runner = self::resolve_turn_runner( $turn_runner, $options, $tool_declarations, $run_id, $lock_session_id, $request, $budgets );
$wall_clock_started_at = microtime( true );
$wall_clock_initial = isset( $budgets['wall_clock_seconds'] ) ? $budgets['wall_clock_seconds']->current() : 0;
$mediation_enabled = null !== $tool_executor && ! empty( $tool_declarations );
self::emit_tool_declaration_diagnostics( $on_event, $rejected_declarations, $tool_declarations, $tool_executor );
$messages = self::normalize_messages( $messages );
if ( '' !== $run_id && '' !== $lock_session_id ) {
WP_Agent_Chat_Run_Control::start_run( $run_id, $lock_session_id, array( 'source' => 'conversation_loop' ) );
}
$events = array();
$tool_results = array();
$tool_events = self::normalize_array_list( array() );
$tool_audit_events = array();
$conversation_complete = false;
$exceeded_budget = null;
$stalled = null;
$approval_required = null;
$runtime_tool_pending = null;
$interrupted = null;
// Universal observability accumulators. Turn runners may report
// `usage` (token counts) and `request_metadata` (last provider request
// descriptor) in their per-turn return value; the loop accumulates
// these and exposes them in the final result so consumers don't have
// to track them out-of-band via mutable state.
$turns_run = 0;
$total_usage = array(
'prompt_tokens' => 0,
'completion_tokens' => 0,
'total_tokens' => 0,
);
$result_metadata = array();
$request_metadata = array();
$provider_diagnostics = array();
if ( null !== $transcript_lock && '' !== $lock_session_id ) {
$lock_token = $transcript_lock->acquire_session_lock( $lock_session_id, $lock_ttl );
if ( null === $lock_token || '' === $lock_token ) {
self::emit_event( $on_event, 'transcript_lock_contention', array(
'session_id' => $lock_session_id,
) );
return self::normalize_conversation_result( array(
'messages' => $messages,
'tool_execution_results' => array(),
'events' => array(),
'status' => 'transcript_lock_contention',
) );
}
}
try {
for ( $turn = 1; $turn <= $max_turns; ++$turn ) {
$wall_clock_exceeded = self::check_wall_clock_budget( $budgets, $wall_clock_started_at, $wall_clock_initial, $on_event );
if ( null !== $wall_clock_exceeded ) {
$exceeded_budget = $wall_clock_exceeded;
break;
}
$turns_run = $turn;
$force_continue = false;
$turn_context = $context;
$turn_context['turn'] = $turn;
$interrupt = self::check_runtime_cancellation( $run_id, $lock_session_id, $turn_context, $on_event );
if ( null !== $interrupt ) {
$messages[] = $interrupt['message'];
$events[] = self::interrupt_event( $interrupt );
$interrupted = $interrupt['metadata'];
break;
}
self::emit_event( $on_event, 'turn_started', array(
'turn' => $turn,
'max_turns' => $max_turns,
'message_count' => count( $messages ),
) );
$compaction = self::maybe_compact( $messages, $options );
$messages = $compaction['messages'];
$events = array_merge( $events, $compaction['events'] );
try {
$result = call_user_func( $turn_runner, $messages, $turn_context );
} catch ( \Throwable $error ) {
self::emit_event( $on_event, 'failed', array(
'turn' => $turn,
'error' => $error->getMessage(),
) );
$failure_result = self::failure_result(
$messages,
$tool_results,
$tool_events,
$tool_audit_events,
$events,
$error,
$turn,
$total_usage,
$request_metadata
);
if ( '' !== $run_id && '' !== $lock_session_id ) {
WP_Agent_Chat_Run_Control::finish_run( $run_id, WP_Agent_Chat_Run_Control::STATUS_FAILED );
}
self::persist_transcript( $transcript_persister, $messages, $options, $failure_result );
return $failure_result;
}
if ( ! is_array( $result ) ) {
$error = new \InvalidArgumentException( 'invalid_agent_conversation_loop: turn runner must return an array' );
self::emit_event( $on_event, 'failed', array(
'turn' => $turn,
'error' => $error->getMessage(),
) );
self::persist_transcript( $transcript_persister, $messages, $options, array(
'messages' => $messages,
'tool_execution_results' => $tool_results,
'tool_events' => $tool_events,
'tool_audit_events' => $tool_audit_events,
'events' => $events,
) );
throw $error;
}
$interrupt = self::check_runtime_cancellation( $run_id, $lock_session_id, $turn_context, $on_event );
if ( null !== $interrupt ) {
$messages[] = $interrupt['message'];
$events[] = self::interrupt_event( $interrupt );
$interrupted = $interrupt['metadata'];
break;
}
if ( isset( $result['provider_diagnostics'] ) && is_array( $result['provider_diagnostics'] ) ) {
$provider_diagnostics[] = self::normalize_assoc_array( $result['provider_diagnostics'] );
}
if ( isset( $result['failure'] ) && is_array( $result['failure'] ) ) {
$failure = self::normalize_provider_turn_failure( $result['failure'], $turn );
self::emit_event( $on_event, 'failed', array(
'turn' => $turn,
'error' => $failure['message'],
) );
$failure_result = self::normalize_conversation_result( array(
'messages' => $messages,
'tool_execution_results' => self::normalize_array_list( $tool_results ),
'tool_events' => self::normalize_array_list( $tool_events ),
'tool_audit_events' => self::normalize_array_list( $tool_audit_events ),
'events' => self::normalize_array_list( $events ),
'status' => 'failed',
'completed' => false,
'turn_count' => $turn,
'final_content' => self::extract_final_content( $messages ),
'usage' => $total_usage,
'request_metadata' => $request_metadata,
'provider_diagnostics' => $provider_diagnostics,
'failure' => $failure,
) );
if ( '' !== $run_id && '' !== $lock_session_id ) {
WP_Agent_Chat_Run_Control::finish_run( $run_id, WP_Agent_Chat_Run_Control::STATUS_FAILED );
}
self::persist_transcript( $transcript_persister, $messages, $options, $failure_result );
return $failure_result;
}
// Accumulate optional observability fields from the turn runner.
// `usage` is a per-turn token-count array that gets summed into
// `$total_usage`. `request_metadata` is the most recent provider
// request descriptor and overwrites on each turn — consumers
// typically only care about the last one.
if ( isset( $result['usage'] ) && is_array( $result['usage'] ) ) {
$total_usage = self::accumulate_usage( $total_usage, self::normalize_assoc_array( $result['usage'] ) );
}
if ( isset( $result['request_metadata'] ) && is_array( $result['request_metadata'] ) ) {
$request_metadata = self::normalize_assoc_array( $result['request_metadata'] );
}
if ( isset( $result['metadata'] ) && is_array( $result['metadata'] ) ) {
$result_metadata = array_merge( $result_metadata, self::normalize_assoc_array( $result['metadata'] ) );
}
// When mediation is enabled, the turn runner returns tool_calls
// and the loop handles execution. Otherwise, the caller-managed path applies.
if ( null !== $tool_executor && $mediation_enabled && isset( $result['tool_calls'] ) && is_array( $result['tool_calls'] ) ) {
$interrupt = self::check_runtime_cancellation( $run_id, $lock_session_id, $turn_context, $on_event );
if ( null !== $interrupt ) {
$messages[] = $interrupt['message'];
$events[] = self::interrupt_event( $interrupt );
$interrupted = $interrupt['metadata'];
break;
}
$mediation_result = WP_Agent_Tool_Mediation_Runner::run(
$messages,
self::normalize_assoc_array( $result ),
$tool_executor,
$tool_declarations,
array(
'completion_policy' => $completion_policy,
'turn_context' => $turn_context,
'turn' => $turn,
'on_event' => $on_event,
'budgets' => $budgets,
'identical_failure_tracker' => $failure_tracker,
'tool_result_truncator' => $result_truncator,
'pre_tool_mediator' => $pre_tool_mediator,
'prior_tool_results' => $tool_results,
'post_tool_result_diagnostics' => $post_tool_diagnostics,
'runtime_tool_request_store' => $runtime_tool_store,
)
);
$messages = $mediation_result['messages'];
$tool_results = array_merge( $tool_results, $mediation_result['tool_execution_results'] );
$tool_events = array_merge( $tool_events, $mediation_result['tool_events'] );
$tool_audit_events = array_merge( $tool_audit_events, $mediation_result['tool_audit_events'] );
$events = array_merge( $events, $mediation_result['events'] );
$conversation_complete = $mediation_result['conversation_complete'];
$exceeded_budget = $mediation_result['exceeded_budget'];
$approval_required = $mediation_result['approval_required'] ?? null;
$runtime_tool_pending = $mediation_result['runtime_tool_pending'] ?? null;
$stalled = self::check_spin_detector( $spin_detector, $mediation_result['spin_signatures'], $turn_context, $on_event );
$interrupt = self::check_runtime_cancellation( $run_id, $lock_session_id, $turn_context, $on_event );
if ( null !== $interrupt ) {
$messages[] = $interrupt['message'];
$events[] = self::interrupt_event( $interrupt );
$interrupted = $interrupt['metadata'];
break;
}
// Deterministic completion gate. When the model stops calling
// tools (natural completion) but a configured tool-call rule
// still requires a commit tool, the loop refuses to finish and
// re-prompts with a runtime-owned, model-visible reason. The
// enforcement is the loop's -- the model cannot opt out of it.
if (
null !== $tool_call_gate
&& $conversation_complete
&& empty( $result['tool_calls'] )
&& null === $exceeded_budget
&& null === $stalled
&& null === $approval_required
&& null === $runtime_tool_pending
) {
$completion_gate = $tool_call_gate->evaluate_completion( $messages );
if ( ! $completion_gate['allowed'] ) {
$conversation_complete = false;
$force_continue = true;
$messages[] = WP_Agent_Message::text(
'user',
$completion_gate['reason'],
array(
'type' => WP_Agent_Tool_Call_Gate::EVENT_COMPLETION_BLOCKED,
'tool_call_gate' => $completion_gate['context'],
)
);
$events[] = array(
'type' => WP_Agent_Tool_Call_Gate::EVENT_COMPLETION_BLOCKED,
'metadata' => $completion_gate['context'],
);
self::emit_event( $on_event, WP_Agent_Tool_Call_Gate::EVENT_COMPLETION_BLOCKED, $completion_gate['context'] );
}
}
} else {
// Caller-managed path: turn runner handles everything internally.
$result = self::normalize_conversation_result( $result );
$messages = self::normalize_messages( is_array( $result['messages'] ?? null ) ? $result['messages'] : array() );
$tool_results = array_merge( $tool_results, self::normalize_array_list( $result['tool_execution_results'] ) );
if ( isset( $result['tool_audit_events'] ) && is_array( $result['tool_audit_events'] ) ) {
$tool_audit_events = array_merge( $tool_audit_events, self::normalize_array_list( $result['tool_audit_events'] ) );
}
if ( isset( $result['tool_events'] ) && is_array( $result['tool_events'] ) ) {
$tool_events = array_merge( $tool_events, $result['tool_events'] );
}
$events = array_merge( $events, self::normalize_events( $result['events'] ?? array() ) );
if ( isset( $result['request_metadata'] ) && is_array( $result['request_metadata'] ) ) {
$request_metadata = self::normalize_assoc_array( $result['request_metadata'] );
}
// Apply completion policy to tool results from the turn runner
// when the loop owns policy but the turn runner handled execution.
if ( null !== $completion_policy && isset( $result['tool_execution_results'] ) && is_array( $result['tool_execution_results'] ) ) {
foreach ( $result['tool_execution_results'] as $tool_exec_result ) {
if ( ! is_array( $tool_exec_result ) ) {
continue;
}
$tool_name = is_string( $tool_exec_result['tool_name'] ?? null ) ? $tool_exec_result['tool_name'] : '';
$tool_def = '' !== $tool_name ? ( $tool_declarations[ $tool_name ] ?? null ) : null;
$decision = $completion_policy->recordToolResult(
$tool_name,
is_array( $tool_def ) ? $tool_def : null,
self::normalize_assoc_array( $tool_exec_result ),
$turn_context,
$turn
);
if ( $decision->isComplete() ) {
$conversation_complete = true;
break;
}
}
}
}
// Stop conditions: budget exceeded, completion policy, or caller should_continue.
if ( null !== $exceeded_budget ) {
break;
}
if ( null !== $stalled ) {
break;
}
if ( null !== $runtime_tool_pending ) {
break;
}
if ( $conversation_complete ) {
break;
}
$interrupt = self::check_interrupt_source( $interrupt_source, $messages, $options, $turn_context, $on_event );
if ( null === $interrupt ) {
$interrupt = self::check_runtime_cancellation( $run_id, $lock_session_id, $turn_context, $on_event );
}
if ( null !== $interrupt ) {
$messages[] = $interrupt['message'];
$events[] = self::interrupt_event( $interrupt );
if ( 'cancel' === $interrupt['action'] ) {
$interrupted = $interrupt['metadata'];
break;
}
}
// Increment the turns budget after a completed turn.
// Synthesized turns budgets (from max_turns) break the loop silently
// to preserve backwards compatibility. Explicit turns budgets signal
// budget_exceeded so callers know the stop reason.
$turns_exceeded = self::increment_budget( $budgets, 'turns', $has_explicit_turns ? $on_event : null );
if ( null !== $turns_exceeded ) {
if ( $has_explicit_turns ) {
$exceeded_budget = $turns_exceeded;
}
break;
}
// A blocked completion gate forces another turn so the model can
// satisfy the required commit tool, overriding the natural-completion
// stop signal the turn runner would otherwise trigger.
if ( ! $force_continue && ( ! is_callable( $should_continue ) || ! call_user_func( $should_continue, $result, $turn_context ) ) ) {
break;
}
}
$final_result_data = array(
'messages' => $messages,
'tool_execution_results' => $tool_results,
'tool_events' => $tool_events,
'tool_audit_events' => $tool_audit_events,
'events' => $events,
'turn_count' => $turns_run,
'final_content' => self::extract_final_content( $messages ),
'metadata' => $result_metadata,
'usage' => $total_usage,
'request_metadata' => $request_metadata,
'provider_diagnostics' => $provider_diagnostics,
'completed' => true,
);
if ( null !== $exceeded_budget ) {
$final_result_data['status'] = 'budget_exceeded';
$final_result_data['budget'] = $exceeded_budget;
$final_result_data['completed'] = false;
}
if ( null !== $stalled ) {
$final_result_data['status'] = 'stalled';
$final_result_data['stalled'] = $stalled;
$final_result_data['completed'] = false;
}
if ( null !== $approval_required ) {
$final_result_data['status'] = 'approval_required';
$final_result_data['approval_required'] = $approval_required;
$final_result_data['completed'] = false;
}
if ( null !== $runtime_tool_pending ) {
$final_result_data['status'] = WP_Agent_Runtime_Tool_Request::STATUS_PENDING;
$final_result_data['runtime_tool_pending'] = $runtime_tool_pending;
$final_result_data['completed'] = false;
}
if ( null !== $interrupted ) {
$final_result_data['status'] = 'interrupted';
$final_result_data['interrupted'] = $interrupted;
$final_result_data['completed'] = false;
}
$final_result = self::normalize_conversation_result( $final_result_data );
if ( '' !== $run_id && '' !== $lock_session_id ) {
WP_Agent_Chat_Run_Control::finish_run( $run_id, WP_Agent_Run_Outcome::run_control_status( $final_result ) );
}
self::persist_transcript( $transcript_persister, $messages, $options, $final_result );
self::emit_event( $on_event, 'completed', array(
'turn' => $turns_run,
'message_count' => count( $messages ),
'tool_results' => count( $tool_results ),
) );
return $final_result;
} finally {
if ( null !== $transcript_lock && null !== $lock_token && '' !== $lock_session_id ) {
try {
$transcript_lock->release_session_lock( $lock_session_id, $lock_token );
} catch ( \Throwable $error ) {
// Lock release failures must not change loop results.
unset( $error );
}
}
}
}
/**
* One-call conversation convenience that supplies the default adapter.
*
* Fulfills the {@see WP_Agent_Conversation_Runner} contract intent: a caller
* provides messages, tool declarations, and a provider/model, and the loop
* runs end-to-end through {@see WP_Agent_Default_Provider_Turn_Adapter}
* without the caller hand-building a turn runner.
*
* The adapter is supplied through the mediated path (as `provider_turn_adapter`),
* so when a `tool_executor` is provided the loop executes tools and assembles
* the canonical envelopes itself — the adapter never executes tools.
*
* Recognized `$options` keys (all optional):
*
* - `system_prompt` (string): Default system instruction for the adapter.
* - `temperature` (float) / `max_tokens` (int): Forwarded to the adapter.
* - `prompt_input_provider` (callable): Pluggable prompt-input strategy.
* - `tool_executor` (WP_Agent_Tool_Executor): Enables mediated tool execution.
* - `completion_policy`, `max_turns`, `context`, `should_continue`, and any
* other {@see WP_Agent_Conversation_Loop::run()} option are passed through.
*
* @param array<int, array<string, mixed>> $messages Initial transcript messages.
* @param array<mixed> $tool_declarations Tool declarations keyed by name.
* @param string $provider_id Provider identifier.
* @param string $model_id Model identifier.
* @param array<string, mixed> $options Loop and adapter options.
* @return array<string, mixed> Normalized conversation result.
*/
public static function run_conversation( array $messages, array $tool_declarations, string $provider_id, string $model_id, array $options = array() ): array {
$system_prompt = is_string( $options['system_prompt'] ?? null ) ? $options['system_prompt'] : '';
$adapter_options = array();
foreach ( array( 'temperature', 'max_tokens', 'prompt_input_provider' ) as $adapter_key ) {
if ( array_key_exists( $adapter_key, $options ) ) {
$adapter_options[ $adapter_key ] = $options[ $adapter_key ];
}
}
$adapter = new WP_Agent_Default_Provider_Turn_Adapter( $provider_id, $model_id, $system_prompt, $adapter_options );
$loop_options = $options;
$loop_options['provider_turn_adapter'] = $adapter;
$loop_options['tool_declarations'] = $tool_declarations;
unset( $loop_options['temperature'], $loop_options['max_tokens'], $loop_options['prompt_input_provider'], $loop_options['system_prompt'] );
if ( '' !== $system_prompt ) {
$context = self::normalize_assoc_array( $loop_options['context'] ?? array() );
$context['system_prompt'] = $context['system_prompt'] ?? $system_prompt;
$loop_options['context'] = $context;
}
return self::run( $messages, null, $loop_options );
}
/**
* Mediate tool calls extracted from the turn runner result.
*
* Handles the tool-call → validate → execute → message assembly cycle.
*
* @param array<string, mixed> $result Turn runner result with tool_calls.
* @param WP_Agent_Tool_Executor $executor Tool executor adapter.
* @param array<string, array<string, mixed>> $declarations Tool declarations keyed by name.
* @param WP_Agent_Conversation_Completion_Policy|null $policy Completion policy.
* @param array<string, mixed> $turn_context Turn context.
* @param int $turn Current turn number.
* @param callable|null $on_event Event sink.
* @param array<string, WP_Agent_Iteration_Budget> $budgets Named iteration budgets.
* @param WP_Agent_Identical_Failure_Tracker|null $failure_tracker Optional identical-failure tracker.
* @param WP_Agent_Tool_Result_Truncator|null $truncator Optional tool result truncator.
* @param array<int, array<string, mixed>> $prior_messages Transcript before this mediated turn.
* @param callable|null $pre_tool_mediator Optional pre-tool mediator.
* @param array<int, array<string, mixed>> $prior_tool_results Prior mediated tool results.
* @param callable|null $post_tool_diagnostics Optional post-result diagnostics callback.
* @param WP_Agent_Runtime_Tool_Request_Store|null $runtime_tool_store Optional durable runtime tool request store.
* @return array{messages: array<int, array<string, mixed>>, tool_execution_results: array<int, array<string, mixed>>, tool_events: array<int, array<string, mixed>>, tool_audit_events: array<int, array<string, mixed>>, events: array<int, array<string, mixed>>, conversation_complete: bool, exceeded_budget: string|null, approval_required: array<string, mixed>|null, runtime_tool_pending: array<string, mixed>|null, spin_signatures: array<int, WP_Agent_Spin_Signature>}
*/
public static function mediate_tool_calls(
array $result,
WP_Agent_Tool_Executor $executor,
array $declarations,
?WP_Agent_Conversation_Completion_Policy $policy,
array $turn_context,
int $turn,
?callable $on_event,
array $budgets = array(),
?WP_Agent_Identical_Failure_Tracker $failure_tracker = null,
?WP_Agent_Tool_Result_Truncator $truncator = null,
array $prior_messages = array(),
?callable $pre_tool_mediator = null,
array $prior_tool_results = array(),
?callable $post_tool_diagnostics = null,
?WP_Agent_Runtime_Tool_Request_Store $runtime_tool_store = null
): array {
$core = new WP_Agent_Tool_Execution_Core();
// Fall back to the prior turn's messages when the turn runner omits
// `messages` from its return — without this, mediation starts from an
// empty list and silently drops history between rounds.
$messages = isset( $result['messages'] ) && is_array( $result['messages'] )
? self::normalize_messages( $result['messages'] )
: $prior_messages;
$tool_calls = isset( $result['tool_calls'] ) && is_array( $result['tool_calls'] ) ? $result['tool_calls'] : array();
$tool_execution_results = array();
$tool_events = array();
$tool_audit_events = array();
$events = array();
$spin_signatures = array();
$complete = false;
$completion_stop_recorded = false;
$exceeded_budget = null;
$approval_required = null;
$runtime_tool_pending = null;
// If the turn runner returned text content, add it as an assistant message.
if ( isset( $result['content'] ) && is_string( $result['content'] ) && '' !== $result['content'] ) {
$messages[] = WP_Agent_Message::text( 'assistant', $result['content'] );
}
foreach ( $tool_calls as $index => $raw_call ) {
if ( ! is_array( $raw_call ) ) {
continue;
}
$raw_call = self::normalize_assoc_array( $raw_call );
$tool_name = $raw_call['name'] ?? $raw_call['tool_name'] ?? '';
$parameters = is_array( $raw_call['parameters'] ?? null ) ? $raw_call['parameters'] : array();
$parameters_for_policy = self::normalize_assoc_array( $parameters );
$sequence = is_int( $index ) ? $index + 1 : count( $spin_signatures ) + 1;
$tool_call_id = self::resolve_tool_call_id( $raw_call, $turn, $sequence );
if ( ! is_string( $tool_name ) || '' === $tool_name ) {
continue;
}
$spin_signatures[] = new WP_Agent_Spin_Signature( $tool_name, $parameters_for_policy );
// Prepare through WP_Agent_Tool_Execution_Core so callers can mediate
// with the same normalized tool-call shape the executor would receive.
$tool_context = $turn_context;
$tool_context['tool_call_id'] = $tool_call_id;
$prepared = $core->prepareWP_Agent_Tool_Call(
$tool_name,
$parameters,
$declarations,
$tool_context
);
$prepared_tool_call = self::array_or_empty( $prepared['tool_call'] ?? null );
$prepared_tool_def = isset( $prepared['tool_def'] ) && is_array( $prepared['tool_def'] ) ? $prepared['tool_def'] : array();
$tool_definition = self::associative_array_or_null( $prepared['tool_def'] ?? ( $declarations[ $tool_name ] ?? null ) );
$parameter_exposure = self::tool_parameter_exposure( $parameters_for_policy, $tool_definition );
self::emit_event( $on_event, 'tool_call', array_merge(
array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
),
$parameter_exposure
) );
$tool_events[] = self::tool_event( 'tool_call', $tool_name, $tool_call_id, $turn, array_merge( array( 'status' => 'called' ), $parameter_exposure ) );
// Add tool-call message to transcript. The structured info lives in
// metadata/payload, but generic transcripts receive only the redacted
// parameter envelope; in-process mediators and executors still receive raw
// parameters explicitly through their private context.
$messages[] = WP_Agent_Message::toolCall(
'',
$tool_name,
$parameter_exposure['parameters'],
$turn,
array(
'tool_call_id' => $tool_call_id,
'parameters_sha256' => $parameter_exposure['parameters_sha256'],
'parameters_redacted' => true,
)
);
$mediator_complete = false;
$mediation_context = array(
'messages' => $messages,
'raw_tool_call' => $raw_call,
'prepared_tool_call' => ! empty( $prepared['ready'] ) ? $prepared_tool_call : null,
'tool_declaration' => $tool_definition,
'tool_name' => $tool_name,
'parameters' => $parameters,
'tool_call_id' => $tool_call_id,
'turn_context' => $turn_context,
'turn' => $turn,
'prior_tool_results' => array_merge( $prior_tool_results, $tool_execution_results ),
'prior_mediated_results' => $tool_execution_results,
);
$mediator_decision = self::pre_tool_mediation_decision(
$pre_tool_mediator,
$mediation_context
);
if ( 'reject' === $mediator_decision['action'] ) {
$exec_result = $mediator_decision['result'];
$mediator_complete = $mediator_decision['complete'];
} elseif ( 'replace_result' === $mediator_decision['action'] ) {
$exec_result = $mediator_decision['result'];
$mediator_complete = $mediator_decision['complete'];
} elseif ( 'pending' === $mediator_decision['action'] ) {
$exec_result = $mediator_decision['result'];
$mediator_complete = true;
} elseif ( empty( $prepared['ready'] ) ) {
unset( $prepared['ready'] );
$exec_result = $prepared;
} else {
$exec_result = $core->executePreparedTool(
$prepared_tool_call,
$prepared_tool_def,
$executor,
$tool_context
);
}
$pending_request = self::runtime_tool_pending_request( $exec_result, $tool_name, $tool_call_id, $parameters_for_policy, $turn_context );
if ( null !== $pending_request ) {
$pending_request['metadata'] = array_merge(
self::normalize_assoc_array( $pending_request['metadata'] ?? array() ),
array( 'turn_count' => $turn )
);
if ( null !== $runtime_tool_store ) {
$pending_request = WP_Agent_Runtime_Tool_Lifecycle::create_pending_request(
$runtime_tool_store,
$pending_request,
array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'turn_context' => $turn_context,
)
);
}
$pending_request_json = self::json_encode_safe( $pending_request );
$runtime_tool_pending = $pending_request;
$messages[] = WP_Agent_Message::toolResult(
false !== $pending_request_json ? $pending_request_json : '',
$tool_name,
array(
'success' => false,
'status' => WP_Agent_Runtime_Tool_Request::STATUS_PENDING,
'result' => $pending_request,
),
array( 'tool_call_id' => $tool_call_id )
);
self::emit_event( $on_event, WP_Agent_Runtime_Tool_Request::STATUS_PENDING, array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'request_id' => $pending_request['request_id'],
) );
$tool_events[] = self::tool_event(
WP_Agent_Runtime_Tool_Request::STATUS_PENDING,
$tool_name,
$tool_call_id,
$turn,
array(
'status' => WP_Agent_Runtime_Tool_Request::STATUS_PENDING,
'request_id' => $pending_request['request_id'],
)
);
$complete = true;
break;
}
// Detect an approval_required envelope returned by an ability via the
// wp_pre_execute_ability bridge handler. The envelope replaces the
// tool_result message and halts mediation so the caller can surface
// the pending action and resume after the host records a decision.
$ability_envelope = is_array( $exec_result['result'] ?? null ) ? self::normalize_assoc_array( $exec_result['result'] ) : null;
if ( null !== $ability_envelope && WP_Agent_Message::TYPE_APPROVAL_REQUIRED === ( $ability_envelope['type'] ?? null ) ) {
$approval_required = $ability_envelope;
$messages[] = $ability_envelope;
self::emit_event( $on_event, 'approval_required', array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'action_id' => isset( $ability_envelope['payload'] ) && is_array( $ability_envelope['payload'] ) ? ( $ability_envelope['payload']['action_id'] ?? null ) : null,
) );
$complete = true;
break;
}
$original_exec_result = $exec_result;
$truncation = self::maybe_truncate_tool_result( $truncator, $exec_result, $tool_name, self::normalize_assoc_array( $tool_context ) );
$exec_result = $truncation['result'];
if ( $truncation['truncated'] ) {
$payload = array_merge(
$truncation['metadata'],
array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'original_result' => $original_exec_result,
)
);
self::emit_event( $on_event, 'tool_result_truncated', $payload );
$stored_payload = $payload;
unset( $stored_payload['original_result'] );
$events[] = array(
'type' => 'tool_result_truncated',
'metadata' => $stored_payload,
);
}
self::emit_event( $on_event, 'tool_result', array(
'turn' => $turn,
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'success' => (bool) ( $exec_result['success'] ?? false ),
) );
$tool_events[] = self::tool_event(
'tool_result',
$tool_name,
$tool_call_id,
$turn,
array(
'status' => ! empty( $exec_result['success'] ) ? 'success' : 'error',
'success' => (bool) ( $exec_result['success'] ?? false ),
)
);
// Build the tool_execution_results entry.
$execution_result = array(
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'result' => $exec_result,
'parameters' => $parameter_exposure['parameters'],
'parameters_sha256' => $parameter_exposure['parameters_sha256'],
'parameters_redacted' => true,
'turn_count' => $turn,
);
$runtime = isset( $exec_result['runtime'] ) && is_array( $exec_result['runtime'] ) ? $exec_result['runtime'] : array();
if ( ! empty( $runtime ) ) {
$execution_result['runtime'] = $runtime;
}
$diagnostics = self::post_tool_result_diagnostics(
$post_tool_diagnostics,
array(
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'turn' => $turn,
'turn_context' => $turn_context,
'tool_declaration' => $tool_definition,
'result' => $exec_result,
'success' => (bool) ( $exec_result['success'] ?? false ),
'parameters_sha256' => $parameter_exposure['parameters_sha256'],
)
);
if ( ! empty( $diagnostics ) ) {
$diagnostics_metadata = array_merge(
array(
'tool_name' => $tool_name,
'tool_call_id' => $tool_call_id,
'turn' => $turn,
),
$diagnostics
);
$execution_result['diagnostics'] = $diagnostics;
$events[] = array(
'type' => 'tool_result_diagnostics',
'metadata' => $diagnostics_metadata,
);
self::emit_event( $on_event, 'tool_result_diagnostics', $diagnostics_metadata );
}
$tool_execution_results[] = $execution_result;
$tool_audit_events[] = self::tool_audit_event(
$tool_name,
$tool_call_id,
$parameters_for_policy,
$exec_result,
$tool_definition,
$turn_context,
$turn
);
// Add tool-result message to transcript.
$result_content = ( $exec_result['success'] ?? false )
? self::json_encode_safe( $exec_result['result'] ?? array() )
: ( $exec_result['error'] ?? 'Tool execution failed.' );
$messages[] = WP_Agent_Message::toolResult(
is_string( $result_content ) ? $result_content : '',
$tool_name,
$exec_result,
array( 'tool_call_id' => $tool_call_id )
);
$nudge = self::check_identical_failure_tracker(
$failure_tracker,
$tool_name,
$parameters_for_policy,
$exec_result,
$turn_context,
$on_event
);
if ( null !== $nudge ) {
$nudge_message = is_string( $nudge['message'] ?? null ) || is_array( $nudge['message'] ?? null ) ? $nudge['message'] : '';
$messages[] = WP_Agent_Message::text(
'assistant',
$nudge_message,
array(
'type' => 'identical_failure_nudge',
'identical_failure_signature' => $nudge,
)
);
}
// Increment tool-call budgets: total and per-tool-name.
$exceeded_budget = self::increment_budget( $budgets, 'tool_calls', $on_event );
if ( null === $exceeded_budget ) {
$exceeded_budget = self::increment_budget( $budgets, 'tool_calls_' . $tool_name, $on_event );
}
if ( null !== $exceeded_budget ) {
$complete = true;
break;
}
if ( $mediator_complete ) {
$complete = true;
break;
}
// Consult completion policy. A complete decision stops future model turns,
// but the current provider turn may contain more tool calls that still
// require paired tool results before the transcript can be replayed.
// The policy is consulted for every same-turn tool result — even after a
// prior call in the batch marked the conversation complete — so its
// internal state stays consistent; the stop event is still recorded once.
if ( null !== $policy ) {
$decision = $policy->recordToolResult(
$tool_name,
$tool_definition,
$exec_result,
$turn_context,
$turn
);