-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclass-wp-agent-tool-declaration.php
More file actions
679 lines (577 loc) · 20.8 KB
/
Copy pathclass-wp-agent-tool-declaration.php
File metadata and controls
679 lines (577 loc) · 20.8 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
<?php
/**
* Runtime tool declaration validator.
*
* Runtime tools are declared by a client or transport for one agent run and
* are executed by the client. This class only validates the declaration
* shape; it intentionally does not register, expose, or execute those tools.
*
* @package AgentsAPI
*/
namespace AgentsAPI\AI\Tools;
defined( 'ABSPATH' ) || exit;
/**
* Validates scoped runtime tool declarations before policy integration.
*/
// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Validation exceptions are not rendered output.
class WP_Agent_Tool_Declaration {
public const SOURCE_CLIENT = 'client';
public const EXECUTOR_CLIENT = 'client';
public const EXECUTOR_HOST = 'host';
public const SCOPE_RUN = 'run';
/**
* Top-level declaration field naming the WordPress capability an
* ability-backed tool requires.
*
* When a host/ability tool declaration sets this field, the ability tool
* executor asks the authorization policy whether the execution principal's
* capability ceiling permits the capability before dispatching the ability.
* Absent or empty means no capability gate, preserving the default behavior.
*
* This is a declarative, product-neutral convention: the substrate never
* special-cases consumer tool names. The capability vocabulary is owned by
* WordPress core and the host.
*/
public const REQUIRED_CAPABILITY = 'required_capability';
/**
* Fields owned by the canonical declaration envelope.
*/
private const CANONICAL_FIELDS = array(
'name' => true,
'source' => true,
'description' => true,
'parameters' => true,
'executor' => true,
'scope' => true,
'runtime' => true,
);
/**
* Generic runtime metadata key for duplicate-call behavior.
*/
public const RUNTIME_DUPLICATE_POLICY = 'duplicate_policy';
/**
* Generic runtime metadata key for progress/completion signaling.
*/
public const RUNTIME_COMPLETION_SIGNAL = 'completion_signal';
/**
* Generic runtime metadata key for where a tool may be exposed.
*/
public const RUNTIME_CAPABILITY_SCOPE = 'capability_scope';
/**
* Tool may be exposed inside a delegated runtime.
*/
public const CAPABILITY_SCOPE_RUNTIME_LOCAL = 'runtime_local';
/**
* Tool belongs to the parent/control-plane runtime.
*/
public const CAPABILITY_SCOPE_CONTROL_PLANE = 'control_plane';
/**
* Generic runtime metadata key for the target execution environment.
*/
public const RUNTIME_ENVIRONMENT = 'environment';
/**
* Tool declaration targets a delegated runtime.
*/
public const ENVIRONMENT_RUNTIME_LOCAL = 'runtime_local';
/**
* Tool declaration targets a parent/control-plane runtime.
*/
public const ENVIRONMENT_CONTROL_PLANE = 'control_plane';
/**
* Normalize a runtime tool declaration or throw a field-scoped error.
*
* @param array<mixed> $declaration Raw runtime tool declaration.
* @return array<mixed> Normalized declaration.
*/
public static function normalize( array $declaration ): array {
$errors = self::validate( $declaration );
if ( ! empty( $errors ) ) {
$message = sprintf(
'invalid_runtime_tool_declaration: %s',
implode( ', ', self::sanitizeErrorKeys( $errors ) )
);
throw new \InvalidArgumentException(
$message
);
}
$name = is_string( $declaration['name'] ?? null ) ? $declaration['name'] : '';
$source = self::sourceFromName( $name );
if ( '' === $source && is_string( $declaration['source'] ?? null ) ) {
$source = trim( $declaration['source'] );
}
if ( '' === $source ) {
$source = self::SOURCE_CLIENT;
}
$description = $declaration['description'] ?? '';
$normalized = array(
'name' => $name,
'source' => $source,
'description' => is_string( $description ) ? trim( $description ) : '',
'parameters' => $declaration['parameters'] ?? array(),
'executor' => self::EXECUTOR_CLIENT,
'scope' => self::SCOPE_RUN,
);
$provider_safe_name = self::providerSafeName( $name );
if ( $provider_safe_name !== $name ) {
$normalized['provider_safe_name'] = $provider_safe_name;
}
$runtime = self::normalizeRuntimeMetadata( $declaration['runtime'] ?? array() );
if ( ! empty( $runtime ) ) {
$normalized['runtime'] = $runtime;
}
$normalized = array_merge( $normalized, self::normalizeExtensionFields( $declaration ), self::normalizeParameterBindingFields( $declaration ) );
return $normalized;
}
/**
* Normalize a conversation-request tool declaration.
*
* Client runtime tools keep the strict `normalize()` contract. Host-owned
* declarations are request/replay catalog entries for tools executed by the
* host runtime rather than the client transport.
*
* @param array<mixed> $declaration Raw request tool declaration.
* @return array<mixed> Normalized declaration.
*/
public static function normalizeForConversationRequest( array $declaration ): array {
$name = is_string( $declaration['name'] ?? null ) ? $declaration['name'] : '';
$executor = $declaration['executor'] ?? null;
if ( self::EXECUTOR_CLIENT === $executor || self::SOURCE_CLIENT === self::sourceFromName( $name ) ) {
$declaration = self::applyClientRequestDefaults( $declaration );
return self::normalize( $declaration );
}
try {
return self::normalizeForServer( $declaration );
} catch ( \InvalidArgumentException $error ) {
throw new \InvalidArgumentException(
str_replace( 'invalid_server_tool_declaration:', 'invalid_conversation_tool_declaration:', $error->getMessage() )
);
}
}
/**
* Normalize a host/server-mediated tool declaration.
*
* Server declarations describe model-facing tools that the host mediates via
* `WP_Agent_Tool_Executor`. The declaration is intentionally neutral: Agents
* API validates the envelope, while the host still owns concrete execution,
* authorization, and product-specific routing.
*
* @param array<mixed> $declaration Raw server tool declaration.
* @return array<mixed> Normalized declaration.
*/
public static function normalizeForServer( array $declaration ): array {
$declaration = self::applyServerDefaults( $declaration );
$errors = self::validateServerDeclaration( $declaration );
if ( ! empty( $errors ) ) {
$message = sprintf(
'invalid_server_tool_declaration: %s',
implode( ', ', self::sanitizeErrorKeys( $errors ) )
);
throw new \InvalidArgumentException(
$message
);
}
$name = is_string( $declaration['name'] ?? null ) ? $declaration['name'] : '';
$source = $declaration['source'] ?? '';
$description = $declaration['description'] ?? '';
$normalized = array(
'name' => $name,
'source' => is_string( $source ) ? trim( $source ) : '',
'description' => is_string( $description ) ? trim( $description ) : '',
'parameters' => $declaration['parameters'] ?? array(),
'executor' => self::EXECUTOR_HOST,
'scope' => self::SCOPE_RUN,
);
$provider_safe_name = self::providerSafeName( $name );
if ( $provider_safe_name !== $name ) {
$normalized['provider_safe_name'] = $provider_safe_name;
}
$runtime = self::normalizeRuntimeMetadata( $declaration['runtime'] ?? array() );
if ( ! empty( $runtime ) ) {
$normalized['runtime'] = $runtime;
}
$normalized = array_merge( $normalized, self::normalizeExtensionFields( $declaration ), self::normalizeParameterBindingFields( $declaration ) );
$required_capability = self::requiredCapability( $declaration );
if ( '' !== $required_capability ) {
$normalized[ self::REQUIRED_CAPABILITY ] = $required_capability;
} else {
unset( $normalized[ self::REQUIRED_CAPABILITY ] );
}
return $normalized;
}
/**
* Resolve the required WordPress capability for a tool declaration.
*
* Returns the trimmed capability string, or an empty string when the
* declaration does not declare one. The empty-string sentinel means "no
* capability gate," so consumers can distinguish an unset gate from a real
* capability without a separate null check.
*
* @param array<mixed> $tool_declaration Normalized (or raw) tool declaration.
* @return string Trimmed capability name, or empty string when unset/non-string.
*/
public static function requiredCapability( array $tool_declaration ): string {
$value = $tool_declaration[ self::REQUIRED_CAPABILITY ] ?? null;
if ( ! is_string( $value ) ) {
return '';
}
$value = trim( $value );
return '' === $value ? '' : $value;
}
/**
* Validate a runtime tool declaration without throwing.
*
* @param array<mixed> $declaration Raw runtime tool declaration.
* @return string[] Machine-readable invalid field names.
*/
public static function validate( array $declaration ): array {
$errors = array();
$name = $declaration['name'] ?? null;
if ( ! is_string( $name ) || '' === $name || ! self::isValidHostToolName( $name ) ) {
$errors[] = 'name';
}
$source = is_string( $name ) ? self::sourceFromName( $name ) : '';
if ( '' === $source && is_string( $declaration['source'] ?? null ) ) {
$source = trim( $declaration['source'] );
}
if ( '' === $source ) {
$source = self::SOURCE_CLIENT;
}
if ( self::SOURCE_CLIENT !== $source ) {
$errors[] = 'source';
}
if (
isset( $declaration['source'] )
&& $declaration['source'] !== $source
) {
$errors[] = 'source';
}
$description = $declaration['description'] ?? null;
if ( ! is_string( $description ) || '' === trim( $description ) ) {
$errors[] = 'description';
}
if (
isset( $declaration['parameters'] )
&& ! is_array( $declaration['parameters'] )
) {
$errors[] = 'parameters';
}
if ( ( $declaration['executor'] ?? null ) !== self::EXECUTOR_CLIENT ) {
$errors[] = 'executor';
}
if ( ( $declaration['scope'] ?? null ) !== self::SCOPE_RUN ) {
$errors[] = 'scope';
}
if ( isset( $declaration['runtime'] ) && ! is_array( $declaration['runtime'] ) ) {
$errors[] = 'runtime';
}
$errors = array_merge( $errors, self::validateParameterBindingFields( $declaration ) );
return array_values( array_unique( $errors ) );
}
/**
* Validate a host-owned request/replay tool declaration without throwing.
*
* @param array<mixed> $declaration Raw host declaration.
* @return string[] Machine-readable invalid field names.
*/
public static function validateServerDeclaration( array $declaration ): array {
$errors = array();
$name = $declaration['name'] ?? null;
if ( ! is_string( $name ) || '' === $name || ! self::isValidHostToolName( $name ) ) {
$errors[] = 'name';
}
if ( self::SOURCE_CLIENT === ( is_string( $name ) ? self::sourceFromName( $name ) : '' ) ) {
$errors[] = 'source';
}
$source = $declaration['source'] ?? null;
if (
! is_string( $source )
|| '' === $source
|| ! preg_match( '/^[a-z][a-z0-9_-]*$/', $source )
) {
$errors[] = 'source';
}
$description = $declaration['description'] ?? null;
if ( ! is_string( $description ) || '' === trim( $description ) ) {
$errors[] = 'description';
}
if (
isset( $declaration['parameters'] )
&& ! is_array( $declaration['parameters'] )
) {
$errors[] = 'parameters';
}
if ( ( $declaration['executor'] ?? null ) !== self::EXECUTOR_HOST ) {
$errors[] = 'executor';
}
if ( ( $declaration['scope'] ?? null ) !== self::SCOPE_RUN ) {
$errors[] = 'scope';
}
if ( isset( $declaration['runtime'] ) && ! is_array( $declaration['runtime'] ) ) {
$errors[] = 'runtime';
}
$errors = array_merge( $errors, self::validateParameterBindingFields( $declaration ) );
return array_values( array_unique( $errors ) );
}
/**
* Apply server declaration defaults before validation.
*
* @param array<mixed> $declaration Raw declaration.
* @return array<mixed> Declaration with server defaults.
*/
private static function applyServerDefaults( array $declaration ): array {
$name = is_string( $declaration['name'] ?? null ) ? $declaration['name'] : '';
if ( ! isset( $declaration['source'] ) || ! is_string( $declaration['source'] ) || '' === $declaration['source'] ) {
$declaration['source'] = self::sourceFromName( $name ) ?: 'host';
}
if ( ! isset( $declaration['parameters'] ) ) {
$declaration['parameters'] = array();
}
if ( ! isset( $declaration['executor'] ) || self::EXECUTOR_CLIENT !== $declaration['executor'] ) {
$declaration['executor'] = self::EXECUTOR_HOST;
}
if ( ! isset( $declaration['scope'] ) ) {
$declaration['scope'] = self::SCOPE_RUN;
}
return $declaration;
}
/**
* Apply compatibility defaults for existing client tools at request/catalog boundaries.
*
* The low-level `normalize()` contract remains strict. Conversation/request
* ingestion accepts older `client/*` catalog declarations that omitted fields
* already implied by the tool name and loop context.
*
* @param array<mixed> $declaration Raw declaration.
* @return array<mixed> Declaration with request/catalog defaults.
*/
private static function applyClientRequestDefaults( array $declaration ): array {
$name = is_string( $declaration['name'] ?? null ) ? $declaration['name'] : '';
if ( ! isset( $declaration['source'] ) ) {
$declaration['source'] = self::SOURCE_CLIENT;
}
if ( ! isset( $declaration['description'] ) || ! is_string( $declaration['description'] ) || '' === trim( $declaration['description'] ) ) {
$declaration['description'] = $name;
}
if ( ! isset( $declaration['parameters'] ) ) {
$declaration['parameters'] = array();
}
if ( ! isset( $declaration['executor'] ) ) {
$declaration['executor'] = self::EXECUTOR_CLIENT;
}
if ( ! isset( $declaration['scope'] ) ) {
$declaration['scope'] = self::SCOPE_RUN;
}
return $declaration;
}
/**
* Preserve JSON-friendly, non-envelope fields used by generic tool mediation.
*
* @param array<mixed> $declaration Raw declaration.
* @return array<string, mixed> Normalized extension fields.
*/
private static function normalizeExtensionFields( array $declaration ): array {
$extensions = array();
foreach ( $declaration as $key => $value ) {
if ( ! is_string( $key ) || isset( self::CANONICAL_FIELDS[ $key ] ) ) {
continue;
}
if ( 'parameter_bindings' === $key || 'parameter_defaults' === $key ) {
continue;
}
$normalized_value = self::normalizeRuntimeMetadataValue( $value );
if ( null !== $normalized_value ) {
$extensions[ $key ] = $normalized_value;
}
}
return $extensions;
}
/**
* Validate parameter binding/default metadata.
*
* @param array<mixed> $declaration Raw declaration.
* @return string[] Machine-readable invalid field names.
*/
private static function validateParameterBindingFields( array $declaration ): array {
$errors = array();
try {
WP_Agent_Tool_Parameters::normalizeParameterBindings( $declaration );
} catch ( \InvalidArgumentException $error ) {
unset( $error );
$errors[] = array_key_exists( 'parameter_bindings', $declaration ) ? 'parameter_bindings' : 'client_context_bindings';
}
try {
WP_Agent_Tool_Parameters::normalizeParameterDefaults( $declaration );
} catch ( \InvalidArgumentException $error ) {
unset( $error );
$errors[] = 'parameter_defaults';
}
return $errors;
}
/**
* Normalize validated parameter binding/default metadata.
*
* @param array<mixed> $declaration Raw declaration.
* @return array<string,mixed> Normalized parameter metadata.
*/
private static function normalizeParameterBindingFields( array $declaration ): array {
$fields = array();
$bindings = WP_Agent_Tool_Parameters::normalizeParameterBindings( $declaration );
if ( ! empty( $bindings ) ) {
$fields['parameter_bindings'] = $bindings;
}
$defaults = WP_Agent_Tool_Parameters::normalizeParameterDefaults( $declaration );
if ( ! empty( $defaults ) ) {
$fields['parameter_defaults'] = $defaults;
}
return $fields;
}
/**
* Normalize optional product-neutral runtime metadata.
*
* Runtime metadata is a JSON-friendly object used by agent loops and hosts to
* make generic execution decisions without hardcoding product tool names. The
* canonical keys are `duplicate_policy` and `completion_signal`, but callers
* may include additional product-neutral scalar/list values for future policy.
*
* @param mixed $runtime Raw runtime metadata.
* @return array<string, mixed> Normalized runtime metadata.
*/
public static function normalizeRuntimeMetadata( $runtime ): array {
if ( ! is_array( $runtime ) ) {
return array();
}
$normalized = array();
foreach ( $runtime as $key => $value ) {
if ( ! is_string( $key ) || '' === $key ) {
continue;
}
if ( WP_Agent_Tool_Parameters::sensitiveKey( $key ) ) {
$normalized[ $key ] = WP_Agent_Tool_Parameters::REDACTED_VALUE;
continue;
}
$normalized_value = self::normalizeRuntimeMetadataValue( $value );
if ( null === $normalized_value ) {
continue;
}
$normalized[ $key ] = $normalized_value;
}
return $normalized;
}
/**
* Normalize one JSON-friendly runtime metadata value.
*
* @param mixed $value Raw metadata value.
* @return mixed|null Normalized value, or null when unsupported.
*/
private static function normalizeRuntimeMetadataValue( $value ) {
if ( is_string( $value ) || is_int( $value ) || is_float( $value ) || is_bool( $value ) ) {
return $value;
}
if ( ! is_array( $value ) ) {
return null;
}
$normalized = array();
foreach ( $value as $key => $item ) {
$normalized_item = self::normalizeRuntimeMetadataValue( $item );
if ( null === $normalized_item ) {
continue;
}
if ( is_string( $key ) ) {
$normalized[ $key ] = $normalized_item;
} else {
$normalized[] = $normalized_item;
}
}
return $normalized;
}
/**
* Build a namespaced runtime tool name.
*
* @param string $source Runtime tool source slug.
* @param string $tool_slug Tool slug local to the source.
* @return string Namespaced tool name.
*/
public static function namespacedName( string $source, string $tool_slug ): string {
return $source . '/' . $tool_slug;
}
/**
* Build a provider-safe alias for a canonical tool name.
*
* Some provider APIs reject namespaced names containing `/`. The alias is not
* canonical; it is a transport-safe identifier that callers can map back to the
* normalized declaration before executing a tool.
*
* @param string $name Canonical tool name.
* @return string Provider-safe tool alias.
*/
public static function providerSafeName( string $name ): string {
$alias = preg_replace( '/[^A-Za-z0-9_]+/', '__', trim( $name ) );
$alias = is_string( $alias ) ? trim( $alias, '_' ) : '';
if ( '' === $alias ) {
return 'tool';
}
return 1 === preg_match( '/^[A-Za-z]/', $alias ) ? $alias : 'tool_' . $alias;
}
/**
* Resolve a provider-emitted tool name to the canonical declaration name.
*
* @param string $tool_name Tool name from the provider or caller.
* @param array<mixed> $available_tools Normalized tool declarations keyed by canonical name.
* @return string Canonical tool name when found, otherwise the original name.
*/
public static function canonicalNameForProviderToolName( string $tool_name, array $available_tools ): string {
if ( isset( $available_tools[ $tool_name ] ) && is_array( $available_tools[ $tool_name ] ) ) {
return $tool_name;
}
foreach ( $available_tools as $canonical_name => $tool_definition ) {
if ( ! is_string( $canonical_name ) || ! is_array( $tool_definition ) ) {
continue;
}
$aliases = array( $tool_definition['provider_safe_name'] ?? self::providerSafeName( $canonical_name ) );
if ( is_array( $tool_definition['provider_aliases'] ?? null ) ) {
$aliases = array_merge( $aliases, $tool_definition['provider_aliases'] );
}
foreach ( $aliases as $alias ) {
if ( is_string( $alias ) && $tool_name === $alias ) {
return $canonical_name;
}
}
}
return $tool_name;
}
/**
* Extract the source prefix from a namespaced runtime tool name.
*
* @param string $name Runtime tool name.
* @return string Source prefix, or empty string when unnamespaced.
*/
public static function sourceFromName( string $name ): string {
$parts = explode( '/', $name, 2 );
return count( $parts ) === 2 ? $parts[0] : '';
}
/**
* Whether a host-mediated tool name is valid.
*
* @param string $name Tool name.
* @return bool Whether the name is valid.
*/
private static function isValidHostToolName( string $name ): bool {
return 1 === preg_match( '/^[a-z][a-z0-9_-]*$/', $name )
|| 1 === preg_match( '/^[a-z][a-z0-9_-]*\/[a-z][a-z0-9_-]*$/', $name );
}
/**
* Sanitize validator field names without requiring WordPress functions.
*
* @param string[] $errors Raw validator field names.
* @return string[] Sanitized field names.
*/
private static function sanitizeErrorKeys( array $errors ): array {
return array_map(
static function ( string $error ): string {
$sanitized = preg_replace( '/[^a-z0-9_-]/', '', strtolower( $error ) );
return is_string( $sanitized ) ? $sanitized : '';
},
$errors
);
}
}