forge-tool 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ """Public models and protocols for Forge ToolEndpoint implementations."""
2
+
3
+ from .exceptions import ToolEndpointError
4
+ from .models import (
5
+ EndpointRegistryOperation,
6
+ EndpointRegistryResponse,
7
+ EndpointRegistryResponseStatus,
8
+ EndpointState,
9
+ EndpointStatus,
10
+ ExecutionPhase,
11
+ ToolAccepted,
12
+ ToolContext,
13
+ ToolControlCommand,
14
+ ToolControlResponse,
15
+ ToolControlStatus,
16
+ ToolEndpointDescriptor,
17
+ ToolError,
18
+ ToolEvent,
19
+ ToolEventType,
20
+ ToolExecutionKey,
21
+ ToolExecutionStatus,
22
+ ToolOperationDescriptor,
23
+ ToolRequest,
24
+ ToolResult,
25
+ ToolResultResponse,
26
+ ToolResultResponseStatus,
27
+ ToolResultStatus,
28
+ ToolSemantics,
29
+ validate_execution_result,
30
+ )
31
+ from .protocol import (
32
+ ActionToolEndpoint,
33
+ QueryToolEndpoint,
34
+ SessionToolEndpoint,
35
+ ToolEventEmitter,
36
+ )
37
+
38
+ __all__ = [
39
+ "ActionToolEndpoint",
40
+ "EndpointRegistryOperation",
41
+ "EndpointRegistryResponse",
42
+ "EndpointRegistryResponseStatus",
43
+ "EndpointState",
44
+ "EndpointStatus",
45
+ "ExecutionPhase",
46
+ "QueryToolEndpoint",
47
+ "SessionToolEndpoint",
48
+ "ToolAccepted",
49
+ "ToolContext",
50
+ "ToolControlCommand",
51
+ "ToolControlResponse",
52
+ "ToolControlStatus",
53
+ "ToolEndpointDescriptor",
54
+ "ToolEndpointError",
55
+ "ToolError",
56
+ "ToolEvent",
57
+ "ToolEventEmitter",
58
+ "ToolEventType",
59
+ "ToolExecutionKey",
60
+ "ToolExecutionStatus",
61
+ "ToolOperationDescriptor",
62
+ "ToolRequest",
63
+ "ToolResult",
64
+ "ToolResultResponse",
65
+ "ToolResultResponseStatus",
66
+ "ToolResultStatus",
67
+ "ToolSemantics",
68
+ "validate_execution_result",
69
+ ]
@@ -0,0 +1,20 @@
1
+ """Structured exceptions raised while processing ToolEndpoint operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .models import ToolError
6
+
7
+
8
+ class ToolEndpointError(RuntimeError):
9
+ """A structured invoke rejection raised before execution is accepted.
10
+
11
+ Endpoint implementations must not use this exception after execution or side
12
+ effects begin. Query execution failures are terminal ``ToolResult`` values; protocol
13
+ and transport failures use ``tool.error``.
14
+ """
15
+
16
+ def __init__(self, error: ToolError) -> None:
17
+ if not isinstance(error, ToolError):
18
+ raise TypeError("error must be a ToolError")
19
+ self.error = error
20
+ super().__init__(f"{error.code}: {error.message}")
@@ -0,0 +1,550 @@
1
+ """Validated values shared by Forge ToolEndpoint implementations and bindings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Literal
9
+
10
+
11
+ type ToolSemantics = Literal["query", "action", "session"]
12
+ type EndpointState = Literal["ready", "busy", "degraded", "unavailable"]
13
+ type ExecutionPhase = Literal[
14
+ "accepted",
15
+ "running",
16
+ "stopping",
17
+ "completed",
18
+ "failed",
19
+ "cancelled",
20
+ "stopped",
21
+ "unknown",
22
+ ]
23
+ type ToolEventType = Literal[
24
+ "progress",
25
+ "heartbeat",
26
+ "executor_completed",
27
+ "executor_failed",
28
+ "cancelled",
29
+ "stopped",
30
+ ]
31
+ type ToolResultStatus = Literal[
32
+ "succeeded",
33
+ "failed",
34
+ "cancelled",
35
+ "stopped",
36
+ "unknown",
37
+ ]
38
+ type ToolResultResponseStatus = Literal["pending", "available", "not_found"]
39
+ type ToolControlCommand = Literal["cancel", "stop"]
40
+ type EndpointRegistryOperation = Literal["register", "unregister"]
41
+ type EndpointRegistryResponseStatus = Literal["accepted", "rejected"]
42
+ type ToolControlStatus = Literal[
43
+ "accepted",
44
+ "rejected",
45
+ "terminal",
46
+ "unsupported",
47
+ ]
48
+
49
+ _TOOL_SEMANTICS = frozenset(("query", "action", "session"))
50
+ _ENDPOINT_STATES = frozenset(("ready", "busy", "degraded", "unavailable"))
51
+ _EXECUTION_PHASES = frozenset(
52
+ (
53
+ "accepted",
54
+ "running",
55
+ "stopping",
56
+ "completed",
57
+ "failed",
58
+ "cancelled",
59
+ "stopped",
60
+ "unknown",
61
+ )
62
+ )
63
+ _TOOL_EVENT_TYPES = frozenset(
64
+ (
65
+ "progress",
66
+ "heartbeat",
67
+ "executor_completed",
68
+ "executor_failed",
69
+ "cancelled",
70
+ "stopped",
71
+ )
72
+ )
73
+ _TOOL_RESULT_STATUSES = frozenset(
74
+ ("succeeded", "failed", "cancelled", "stopped", "unknown")
75
+ )
76
+ _TOOL_RESULT_RESPONSE_STATUSES = frozenset(("pending", "available", "not_found"))
77
+ _TOOL_CONTROL_COMMANDS = frozenset(("cancel", "stop"))
78
+ _ENDPOINT_REGISTRY_OPERATIONS = frozenset(("register", "unregister"))
79
+ _ENDPOINT_REGISTRY_RESPONSE_STATUSES = frozenset(("accepted", "rejected"))
80
+ _TOOL_CONTROL_STATUSES = frozenset(("accepted", "rejected", "terminal", "unsupported"))
81
+ _TERMINAL_PHASE_RESULTS = {
82
+ "completed": "succeeded",
83
+ "failed": "failed",
84
+ "cancelled": "cancelled",
85
+ "stopped": "stopped",
86
+ "unknown": "unknown",
87
+ }
88
+ _MAX_SAFE_JSON_INTEGER = 9_007_199_254_740_991
89
+
90
+
91
+ def _is_unicode_whitespace(character: str) -> bool:
92
+ code_point = ord(character)
93
+ return (
94
+ 0x09 <= code_point <= 0x0D
95
+ or code_point
96
+ in {0x20, 0x85, 0xA0, 0x1680, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000}
97
+ or 0x2000 <= code_point <= 0x200A
98
+ )
99
+
100
+
101
+ def _is_blank(value: str) -> bool:
102
+ return not value or all(_is_unicode_whitespace(character) for character in value)
103
+
104
+
105
+ def _require_nonempty(value: str, field_name: str) -> None:
106
+ if not isinstance(value, str) or _is_blank(value):
107
+ raise ValueError(f"{field_name} must be a non-empty string")
108
+ if any(0xD800 <= ord(character) <= 0xDFFF for character in value):
109
+ raise ValueError(f"{field_name} must contain valid Unicode scalar values")
110
+
111
+
112
+ def _json_copy(value: Any, path: str, depth: int = 0) -> Any:
113
+ if depth > 64:
114
+ raise ValueError(f"{path} JSON nesting exceeds 64")
115
+ if value is None or isinstance(value, bool):
116
+ return value
117
+ if isinstance(value, str):
118
+ if any(0xD800 <= ord(character) <= 0xDFFF for character in value):
119
+ raise ValueError(f"{path} must contain valid Unicode scalar values")
120
+ return value
121
+ if isinstance(value, int):
122
+ if abs(value) > _MAX_SAFE_JSON_INTEGER:
123
+ raise ValueError(
124
+ f"{path} integer exceeds interoperable range ±{_MAX_SAFE_JSON_INTEGER}"
125
+ )
126
+ return value
127
+ if isinstance(value, float):
128
+ if not math.isfinite(value):
129
+ raise ValueError(f"{path} floating-point values must be finite")
130
+ return value
131
+ if isinstance(value, Mapping):
132
+ result: dict[str, Any] = {}
133
+ for key, nested in value.items():
134
+ if not isinstance(key, str):
135
+ raise TypeError(f"{path} keys must be strings")
136
+ if any(0xD800 <= ord(character) <= 0xDFFF for character in key):
137
+ raise ValueError(
138
+ f"{path} keys must contain valid Unicode scalar values"
139
+ )
140
+ result[key] = _json_copy(nested, f"{path}.{key}", depth + 1)
141
+ return result
142
+ if isinstance(value, (list, tuple)):
143
+ return [
144
+ _json_copy(nested, f"{path}[{index}]", depth + 1)
145
+ for index, nested in enumerate(value)
146
+ ]
147
+ raise TypeError(f"{path} contains unsupported JSON value: {type(value).__name__}")
148
+
149
+
150
+ def _mapping_copy(value: Mapping[str, Any], field_name: str) -> Mapping[str, Any]:
151
+ if not isinstance(value, Mapping):
152
+ raise TypeError(f"{field_name} must be a mapping")
153
+ return _json_copy(value, field_name)
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class ToolOperationDescriptor:
158
+ """One operation exposed by a logical ToolEndpoint."""
159
+
160
+ name: str
161
+ semantics: ToolSemantics
162
+ cancellable: bool = False
163
+ stoppable: bool = False
164
+ status_supported: bool = False
165
+ max_concurrency: int = 1
166
+
167
+ def __post_init__(self) -> None:
168
+ _require_nonempty(self.name, "name")
169
+ if not isinstance(self.semantics, str) or self.semantics not in _TOOL_SEMANTICS:
170
+ raise ValueError(f"unsupported tool semantics: {self.semantics!r}")
171
+ for field_name in ("cancellable", "stoppable", "status_supported"):
172
+ if not isinstance(getattr(self, field_name), bool):
173
+ raise TypeError(f"{field_name} must be a bool")
174
+ if self.semantics == "query" and (
175
+ self.cancellable or self.stoppable or self.status_supported
176
+ ):
177
+ raise ValueError("query operations do not support control or status")
178
+ if self.semantics == "action":
179
+ if self.stoppable:
180
+ raise ValueError("action operations must not be stoppable")
181
+ if not self.status_supported:
182
+ raise ValueError("action operations must support status")
183
+ if self.semantics == "session":
184
+ if self.cancellable:
185
+ raise ValueError("session operations must not be cancellable")
186
+ if not self.status_supported:
187
+ raise ValueError("session operations must support status")
188
+ if (
189
+ isinstance(self.max_concurrency, bool)
190
+ or not isinstance(self.max_concurrency, int)
191
+ or not 1 <= self.max_concurrency <= _MAX_SAFE_JSON_INTEGER
192
+ ):
193
+ raise ValueError(
194
+ f"max_concurrency must be in [1, {_MAX_SAFE_JSON_INTEGER}]"
195
+ )
196
+
197
+
198
+ @dataclass(frozen=True)
199
+ class ToolEndpointDescriptor:
200
+ """Operations registered under one stable logical endpoint ID."""
201
+
202
+ protocol_version: str
203
+ endpoint_id: str
204
+ operations: tuple[ToolOperationDescriptor, ...]
205
+
206
+ def __post_init__(self) -> None:
207
+ _require_nonempty(self.protocol_version, "protocol_version")
208
+ _require_nonempty(self.endpoint_id, "endpoint_id")
209
+ operations = tuple(self.operations)
210
+ if not operations:
211
+ raise ValueError("operations must not be empty")
212
+ if not all(
213
+ isinstance(operation, ToolOperationDescriptor) for operation in operations
214
+ ):
215
+ raise TypeError("operations must contain ToolOperationDescriptor values")
216
+ operation_names = [operation.name for operation in operations]
217
+ if len(operation_names) != len(set(operation_names)):
218
+ raise ValueError("operation names must be unique within an endpoint")
219
+ object.__setattr__(self, "operations", operations)
220
+
221
+
222
+ @dataclass(frozen=True)
223
+ class ToolExecutionKey:
224
+ """Runtime identity for one implementation attempt within an invocation."""
225
+
226
+ invocation_id: str
227
+ attempt_id: str
228
+
229
+ def __post_init__(self) -> None:
230
+ _require_nonempty(self.invocation_id, "invocation_id")
231
+ _require_nonempty(self.attempt_id, "attempt_id")
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class ToolContext:
236
+ """Runtime context for one Tool execution attempt.
237
+
238
+ ``deadline_ms`` is an absolute Unix epoch timestamp in milliseconds, not a
239
+ duration relative to request receipt. It is execution data, not an
240
+ observation timestamp.
241
+ """
242
+
243
+ execution_key: ToolExecutionKey
244
+ tool_id: str
245
+ implementation_id: str
246
+ endpoint_id: str
247
+ operation: str
248
+ caller_id: str | None = None
249
+ deadline_ms: int | None = None
250
+ metadata: Mapping[str, Any] = field(default_factory=dict)
251
+
252
+ def __post_init__(self) -> None:
253
+ if not isinstance(self.execution_key, ToolExecutionKey):
254
+ raise TypeError("execution_key must be a ToolExecutionKey")
255
+ for field_name in ("tool_id", "implementation_id", "endpoint_id", "operation"):
256
+ _require_nonempty(getattr(self, field_name), field_name)
257
+ if self.caller_id is not None:
258
+ _require_nonempty(self.caller_id, "caller_id")
259
+ if self.deadline_ms is not None and (
260
+ isinstance(self.deadline_ms, bool)
261
+ or not isinstance(self.deadline_ms, int)
262
+ or not 0 <= self.deadline_ms <= _MAX_SAFE_JSON_INTEGER
263
+ ):
264
+ raise ValueError(
265
+ "deadline_ms must be a non-negative Unix epoch millisecond "
266
+ f"not greater than {_MAX_SAFE_JSON_INTEGER}"
267
+ )
268
+ object.__setattr__(self, "metadata", _mapping_copy(self.metadata, "metadata"))
269
+
270
+ @property
271
+ def invocation_id(self) -> str:
272
+ """Return the invocation component of ``execution_key``."""
273
+ return self.execution_key.invocation_id
274
+
275
+ @property
276
+ def attempt_id(self) -> str:
277
+ """Return the attempt component of ``execution_key``."""
278
+ return self.execution_key.attempt_id
279
+
280
+
281
+ @dataclass(frozen=True)
282
+ class ToolRequest:
283
+ """JSON-like arguments supplied to a ToolEndpoint operation."""
284
+
285
+ arguments: Mapping[str, Any]
286
+
287
+ def __post_init__(self) -> None:
288
+ object.__setattr__(
289
+ self, "arguments", _mapping_copy(self.arguments, "arguments")
290
+ )
291
+
292
+
293
+ @dataclass(frozen=True)
294
+ class ToolError:
295
+ """Structured error returned by an endpoint execution."""
296
+
297
+ code: str
298
+ message: str
299
+ retryable: bool = False
300
+ details: Mapping[str, Any] = field(default_factory=dict)
301
+
302
+ def __post_init__(self) -> None:
303
+ _require_nonempty(self.code, "code")
304
+ _require_nonempty(self.message, "message")
305
+ if not isinstance(self.retryable, bool):
306
+ raise TypeError("retryable must be a bool")
307
+ object.__setattr__(self, "details", _mapping_copy(self.details, "details"))
308
+
309
+
310
+ @dataclass(frozen=True)
311
+ class EndpointRegistryResponse:
312
+ """Registry decision for one endpoint-management request.
313
+
314
+ ``lease_ttl_ms`` is a lease duration in milliseconds, not an observation
315
+ timestamp or absolute time.
316
+ """
317
+
318
+ operation: EndpointRegistryOperation
319
+ status: EndpointRegistryResponseStatus
320
+ registry_revision: int
321
+ lease_ttl_ms: int | None = None
322
+ error: ToolError | None = None
323
+
324
+ def __post_init__(self) -> None:
325
+ if (
326
+ not isinstance(self.operation, str)
327
+ or self.operation not in _ENDPOINT_REGISTRY_OPERATIONS
328
+ ):
329
+ raise ValueError(
330
+ f"unsupported endpoint registry operation: {self.operation!r}"
331
+ )
332
+ if (
333
+ not isinstance(self.status, str)
334
+ or self.status not in _ENDPOINT_REGISTRY_RESPONSE_STATUSES
335
+ ):
336
+ raise ValueError(
337
+ f"unsupported endpoint registry response status: {self.status!r}"
338
+ )
339
+ if (
340
+ isinstance(self.registry_revision, bool)
341
+ or not isinstance(self.registry_revision, int)
342
+ or not 0 <= self.registry_revision <= _MAX_SAFE_JSON_INTEGER
343
+ ):
344
+ raise ValueError(
345
+ f"registry_revision must be in [0, {_MAX_SAFE_JSON_INTEGER}]"
346
+ )
347
+ if self.lease_ttl_ms is not None and (
348
+ isinstance(self.lease_ttl_ms, bool)
349
+ or not isinstance(self.lease_ttl_ms, int)
350
+ or not 1 <= self.lease_ttl_ms <= _MAX_SAFE_JSON_INTEGER
351
+ ):
352
+ raise ValueError(
353
+ f"lease_ttl_ms must be in [1, {_MAX_SAFE_JSON_INTEGER}] when provided"
354
+ )
355
+ if self.error is not None and not isinstance(self.error, ToolError):
356
+ raise TypeError("error must be a ToolError or None")
357
+
358
+ if self.status == "rejected":
359
+ if self.lease_ttl_ms is not None:
360
+ raise ValueError(
361
+ "a rejected registry response must not contain lease_ttl_ms"
362
+ )
363
+ if self.error is None:
364
+ raise ValueError("a rejected registry response must contain an error")
365
+ else:
366
+ if self.error is not None:
367
+ raise ValueError(
368
+ "an accepted registry response must not contain an error"
369
+ )
370
+ if self.operation == "register":
371
+ if self.lease_ttl_ms is None:
372
+ raise ValueError(
373
+ "an accepted register response must contain lease_ttl_ms"
374
+ )
375
+ elif self.lease_ttl_ms is not None:
376
+ raise ValueError(
377
+ "an accepted unregister response must not contain lease_ttl_ms"
378
+ )
379
+
380
+
381
+ @dataclass(frozen=True)
382
+ class ToolResult:
383
+ """Authoritative terminal result payload for a query or accepted execution.
384
+
385
+ ``unknown`` means that the final execution outcome cannot be recovered. It
386
+ does not mean that a result lookup is merely pending or unavailable.
387
+ """
388
+
389
+ status: ToolResultStatus
390
+ outputs: Mapping[str, Any] = field(default_factory=dict)
391
+ error: ToolError | None = None
392
+
393
+ def __post_init__(self) -> None:
394
+ if not isinstance(self.status, str) or self.status not in _TOOL_RESULT_STATUSES:
395
+ raise ValueError(f"unsupported tool result status: {self.status!r}")
396
+ requires_error = self.status in ("failed", "unknown")
397
+ if requires_error and self.error is None:
398
+ raise ValueError(f"a {self.status} tool result must contain an error")
399
+ if not requires_error and self.error is not None:
400
+ raise ValueError(f"a {self.status} tool result must not contain an error")
401
+ if self.error is not None and not isinstance(self.error, ToolError):
402
+ raise TypeError("error must be a ToolError or None")
403
+ object.__setattr__(self, "outputs", _mapping_copy(self.outputs, "outputs"))
404
+
405
+
406
+ @dataclass(frozen=True)
407
+ class ToolResultResponse:
408
+ """Result lookup response for an active, terminal, or unknown execution key."""
409
+
410
+ status: ToolResultResponseStatus
411
+ result: ToolResult | None = None
412
+
413
+ def __post_init__(self) -> None:
414
+ if (
415
+ not isinstance(self.status, str)
416
+ or self.status not in _TOOL_RESULT_RESPONSE_STATUSES
417
+ ):
418
+ raise ValueError(f"unsupported result response status: {self.status!r}")
419
+ if self.status == "available" and self.result is None:
420
+ raise ValueError("an available result response must contain a result")
421
+ if self.status != "available" and self.result is not None:
422
+ raise ValueError("only an available result response may contain a result")
423
+ if self.result is not None and not isinstance(self.result, ToolResult):
424
+ raise TypeError("result must be a ToolResult or None")
425
+
426
+
427
+ @dataclass(frozen=True)
428
+ class ToolAccepted:
429
+ """Acknowledgement that an action or session was admitted for execution."""
430
+
431
+ details: Mapping[str, Any] = field(default_factory=dict)
432
+
433
+ def __post_init__(self) -> None:
434
+ object.__setattr__(self, "details", _mapping_copy(self.details, "details"))
435
+
436
+
437
+ @dataclass(frozen=True)
438
+ class ToolControlResponse:
439
+ """Immediate response to a cancel or stop request.
440
+
441
+ ``accepted`` means only that the control request was admitted. The caller
442
+ must observe status or result to determine whether execution has terminated.
443
+ ``terminal`` means execution was already terminal before the control request.
444
+ """
445
+
446
+ command: ToolControlCommand
447
+ status: ToolControlStatus
448
+ error: ToolError | None = None
449
+ details: Mapping[str, Any] = field(default_factory=dict)
450
+
451
+ def __post_init__(self) -> None:
452
+ if (
453
+ not isinstance(self.command, str)
454
+ or self.command not in _TOOL_CONTROL_COMMANDS
455
+ ):
456
+ raise ValueError(f"unsupported tool control command: {self.command!r}")
457
+ if (
458
+ not isinstance(self.status, str)
459
+ or self.status not in _TOOL_CONTROL_STATUSES
460
+ ):
461
+ raise ValueError(f"unsupported tool control status: {self.status!r}")
462
+ if self.status == "rejected" and self.error is None:
463
+ raise ValueError("a rejected control response must contain an error")
464
+ if self.status != "rejected" and self.error is not None:
465
+ raise ValueError("only a rejected control response may contain an error")
466
+ if self.error is not None and not isinstance(self.error, ToolError):
467
+ raise TypeError("error must be a ToolError or None")
468
+ object.__setattr__(self, "details", _mapping_copy(self.details, "details"))
469
+
470
+
471
+ @dataclass(frozen=True)
472
+ class ToolEvent:
473
+ """Low-rate event payload emitted through an execution-bound emitter."""
474
+
475
+ type: ToolEventType
476
+ data: Mapping[str, Any] = field(default_factory=dict)
477
+
478
+ def __post_init__(self) -> None:
479
+ if not isinstance(self.type, str) or self.type not in _TOOL_EVENT_TYPES:
480
+ raise ValueError(f"unsupported tool event type: {self.type!r}")
481
+ object.__setattr__(self, "data", _mapping_copy(self.data, "data"))
482
+
483
+
484
+ @dataclass(frozen=True)
485
+ class EndpointStatus:
486
+ """Current health and aggregate concurrency usage of an endpoint."""
487
+
488
+ endpoint_id: str
489
+ state: EndpointState
490
+ active_invocations: int = 0
491
+ details: Mapping[str, Any] = field(default_factory=dict)
492
+
493
+ def __post_init__(self) -> None:
494
+ _require_nonempty(self.endpoint_id, "endpoint_id")
495
+ if not isinstance(self.state, str) or self.state not in _ENDPOINT_STATES:
496
+ raise ValueError(f"unsupported endpoint state: {self.state!r}")
497
+ if (
498
+ isinstance(self.active_invocations, bool)
499
+ or not isinstance(self.active_invocations, int)
500
+ or not 0 <= self.active_invocations <= _MAX_SAFE_JSON_INTEGER
501
+ ):
502
+ raise ValueError(
503
+ f"active_invocations must be in [0, {_MAX_SAFE_JSON_INTEGER}]"
504
+ )
505
+ object.__setattr__(self, "details", _mapping_copy(self.details, "details"))
506
+
507
+
508
+ @dataclass(frozen=True)
509
+ class ToolExecutionStatus:
510
+ """Executor-side status payload for one accepted attempt.
511
+
512
+ ``completed`` means that the endpoint executor considers its work complete;
513
+ the Tool Runtime still owns final CompletionSpec evaluation.
514
+ """
515
+
516
+ phase: ExecutionPhase
517
+ error: ToolError | None = None
518
+ details: Mapping[str, Any] = field(default_factory=dict)
519
+
520
+ def __post_init__(self) -> None:
521
+ if not isinstance(self.phase, str) or self.phase not in _EXECUTION_PHASES:
522
+ raise ValueError(f"unsupported execution phase: {self.phase!r}")
523
+ requires_error = self.phase in ("failed", "unknown")
524
+ if requires_error and self.error is None:
525
+ raise ValueError(f"a {self.phase} execution status must contain an error")
526
+ if not requires_error and self.error is not None:
527
+ raise ValueError(
528
+ "only a failed or unknown execution status may contain an error"
529
+ )
530
+ if self.error is not None and not isinstance(self.error, ToolError):
531
+ raise TypeError("error must be a ToolError or None")
532
+ object.__setattr__(self, "details", _mapping_copy(self.details, "details"))
533
+
534
+
535
+ def validate_execution_result(
536
+ status: ToolExecutionStatus,
537
+ result: ToolResult,
538
+ ) -> None:
539
+ """Validate one terminal executor status/result snapshot pair."""
540
+ if not isinstance(status, ToolExecutionStatus):
541
+ raise TypeError("status must be a ToolExecutionStatus")
542
+ if not isinstance(result, ToolResult):
543
+ raise TypeError("result must be a ToolResult")
544
+ expected = _TERMINAL_PHASE_RESULTS.get(status.phase)
545
+ if expected is None:
546
+ raise ValueError(f"execution phase {status.phase!r} is not terminal")
547
+ if result.status != expected:
548
+ raise ValueError(
549
+ f"execution phase {status.phase!r} requires result status {expected!r}"
550
+ )