agent-work-layer 0.5.0__tar.gz → 0.7.0__tar.gz
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.
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/PKG-INFO +39 -5
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/README.md +37 -3
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/pyproject.toml +2 -2
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/__init__.py +8 -3
- agent_work_layer-0.7.0/src/agent_work_layer/a2a.py +210 -0
- agent_work_layer-0.7.0/src/agent_work_layer/errors.py +22 -0
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/validate.py +31 -2
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/.gitignore +0 -0
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/models.py +0 -0
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/py.typed +0 -0
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/schemas/work-order.schema.json +0 -0
- {agent_work_layer-0.5.0 → agent_work_layer-0.7.0}/src/agent_work_layer/schemas/work-report.schema.json +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: agent-work-layer
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: Work Orders and Work Reports for AI agents: Pydantic models
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: Work Orders and Work Reports for AI agents: Pydantic models, the spec's validation rules and the A2A binding.
|
|
5
5
|
Project-URL: Homepage, https://github.com/probita-ai/agent-work-layer/tree/main/python#readme
|
|
6
6
|
Project-URL: Repository, https://github.com/probita-ai/agent-work-layer
|
|
7
7
|
Project-URL: Issues, https://github.com/probita-ai/agent-work-layer/issues
|
|
@@ -21,7 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
|
|
22
22
|
# agent-work-layer (Python)
|
|
23
23
|
|
|
24
|
-
**Work Orders and Work Reports for AI agents, in Python.** Pydantic models for both documents
|
|
24
|
+
**Work Orders and Work Reports for AI agents, in Python.** Pydantic models for both documents, every validation rule and the A2A binding from the [Agent Work Layer spec](https://github.com/probita-ai/agent-work-layer/blob/main/SPEC.md), with the same rule ids, kinds and paths as the TypeScript SDK.
|
|
25
25
|
|
|
26
26
|
A Work Order says what a job is and what it may use: goal, criteria, budget, deadline and allowed tools. A Work Report says what was done and proves it: evidence for each criterion, cost and tools used. The checks tell you whether a report holds up against its order.
|
|
27
27
|
|
|
@@ -66,7 +66,8 @@ if has_invalid(findings):
|
|
|
66
66
|
| Function | Rules |
|
|
67
67
|
|---|---|
|
|
68
68
|
| `validate_order(order)` | O1–O5 |
|
|
69
|
-
| `validate_report(report, order)` | R1–R12, R14–R16 |
|
|
69
|
+
| `validate_report(report, order, usage=None)` | R1–R12, R14–R16, and R17–R19 when `usage` (what the order's gateway measured) is given |
|
|
70
|
+
| `validate_usage(report, usage)` | R17–R19 only: the report agrees with the gateway's measurement, `{"tool_calls", "seconds"?, "tools_used", "refs"}` |
|
|
70
71
|
| `validate_child_order(child, parent)` | C1–C3 and C5: a sub-order may only narrow its parent's budget, tools and deadline, and may not allow a tool its parent stages |
|
|
71
72
|
| `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
|
|
72
73
|
| `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
|
|
@@ -103,6 +104,39 @@ assert validate_order(order) == [] # the validators accept models too
|
|
|
103
104
|
|
|
104
105
|
`WorkOrder.model_validate(data)` and `WorkReport.model_validate(data)` parse documents. The models catch obvious mistakes as you build. The `validate_*` functions are the checks the spec defines.
|
|
105
106
|
|
|
107
|
+
## Hand work over A2A
|
|
108
|
+
|
|
109
|
+
`agent_work_layer.a2a` is the A2A binding ([SPEC.md §9.2](https://github.com/probita-ai/agent-work-layer/blob/main/SPEC.md#92-a2a)): one order is one A2A task, orders, reports and reviews travel as A2A data parts, and the manager keeps the order's record. Parts and tasks are A2A v0.3's JSON as plain dicts, so it works with any A2A client or server.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from agent_work_layer import validate_report
|
|
113
|
+
from agent_work_layer.a2a import (
|
|
114
|
+
agent_card_extension, order_part, read_parts, report_part, review_part, task_actions, task_status,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Manager: send the order as the first message of a new task.
|
|
118
|
+
message = {"role": "user", "messageId": "m1", "parts": [order_part(order)]}
|
|
119
|
+
|
|
120
|
+
# Worker: list the extension in the Agent Card, read the order, and answer with a task.
|
|
121
|
+
card_extensions = [agent_card_extension()]
|
|
122
|
+
(received,) = read_parts(message["parts"]).orders # checked: raises AwlError if invalid
|
|
123
|
+
task = {
|
|
124
|
+
"id": "t1",
|
|
125
|
+
"status": task_status(received["id"], "submitted"),
|
|
126
|
+
"artifacts": [{"artifactId": "r1", "parts": [report_part(report)]}], # report carries "attempt": 1
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
# Manager: turn the worker's task into actions on the order's record, then review.
|
|
130
|
+
for action in task_actions(order, state="offered", attempts=0, task=task, worker=order.to):
|
|
131
|
+
if action.kind == "submit":
|
|
132
|
+
findings = validate_report(action.report, order)
|
|
133
|
+
... # apply "accept", "decline" or "submit" to your record
|
|
134
|
+
reply = {"role": "user", "messageId": "m2", "taskId": "t1",
|
|
135
|
+
"parts": [review_part({"order_id": order.id, "decision": "approve"})]}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`task_actions` runs the checks the TypeScript SDK's `recordTask` runs before it changes the desk: the peer is the order's worker, each report carries the next `attempt`, is for this order and from this worker, and seeing the same task twice asks for nothing new. This package has no desk, so it returns the actions (`accept`, `decline` with the status text as its reason, `submit` with the report) for you to apply. The caller must have authenticated the A2A peer as the worker.
|
|
139
|
+
|
|
106
140
|
## Matches the TypeScript SDK
|
|
107
141
|
|
|
108
142
|
Findings have the same rule ids, kinds and JSON Pointer paths as [`agent-work-layer`](https://www.npmjs.com/package/agent-work-layer) on npm, including its details:
|
|
@@ -115,7 +149,7 @@ The messages are worded differently, and schema findings (O1, R1, R11) can come
|
|
|
115
149
|
|
|
116
150
|
## Not here yet
|
|
117
151
|
|
|
118
|
-
The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents and the
|
|
152
|
+
The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents, the checks and the A2A binding.
|
|
119
153
|
|
|
120
154
|
## License
|
|
121
155
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# agent-work-layer (Python)
|
|
2
2
|
|
|
3
|
-
**Work Orders and Work Reports for AI agents, in Python.** Pydantic models for both documents
|
|
3
|
+
**Work Orders and Work Reports for AI agents, in Python.** Pydantic models for both documents, every validation rule and the A2A binding from the [Agent Work Layer spec](https://github.com/probita-ai/agent-work-layer/blob/main/SPEC.md), with the same rule ids, kinds and paths as the TypeScript SDK.
|
|
4
4
|
|
|
5
5
|
A Work Order says what a job is and what it may use: goal, criteria, budget, deadline and allowed tools. A Work Report says what was done and proves it: evidence for each criterion, cost and tools used. The checks tell you whether a report holds up against its order.
|
|
6
6
|
|
|
@@ -45,7 +45,8 @@ if has_invalid(findings):
|
|
|
45
45
|
| Function | Rules |
|
|
46
46
|
|---|---|
|
|
47
47
|
| `validate_order(order)` | O1–O5 |
|
|
48
|
-
| `validate_report(report, order)` | R1–R12, R14–R16 |
|
|
48
|
+
| `validate_report(report, order, usage=None)` | R1–R12, R14–R16, and R17–R19 when `usage` (what the order's gateway measured) is given |
|
|
49
|
+
| `validate_usage(report, usage)` | R17–R19 only: the report agrees with the gateway's measurement, `{"tool_calls", "seconds"?, "tools_used", "refs"}` |
|
|
49
50
|
| `validate_child_order(child, parent)` | C1–C3 and C5: a sub-order may only narrow its parent's budget, tools and deadline, and may not allow a tool its parent stages |
|
|
50
51
|
| `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
|
|
51
52
|
| `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
|
|
@@ -82,6 +83,39 @@ assert validate_order(order) == [] # the validators accept models too
|
|
|
82
83
|
|
|
83
84
|
`WorkOrder.model_validate(data)` and `WorkReport.model_validate(data)` parse documents. The models catch obvious mistakes as you build. The `validate_*` functions are the checks the spec defines.
|
|
84
85
|
|
|
86
|
+
## Hand work over A2A
|
|
87
|
+
|
|
88
|
+
`agent_work_layer.a2a` is the A2A binding ([SPEC.md §9.2](https://github.com/probita-ai/agent-work-layer/blob/main/SPEC.md#92-a2a)): one order is one A2A task, orders, reports and reviews travel as A2A data parts, and the manager keeps the order's record. Parts and tasks are A2A v0.3's JSON as plain dicts, so it works with any A2A client or server.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from agent_work_layer import validate_report
|
|
92
|
+
from agent_work_layer.a2a import (
|
|
93
|
+
agent_card_extension, order_part, read_parts, report_part, review_part, task_actions, task_status,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Manager: send the order as the first message of a new task.
|
|
97
|
+
message = {"role": "user", "messageId": "m1", "parts": [order_part(order)]}
|
|
98
|
+
|
|
99
|
+
# Worker: list the extension in the Agent Card, read the order, and answer with a task.
|
|
100
|
+
card_extensions = [agent_card_extension()]
|
|
101
|
+
(received,) = read_parts(message["parts"]).orders # checked: raises AwlError if invalid
|
|
102
|
+
task = {
|
|
103
|
+
"id": "t1",
|
|
104
|
+
"status": task_status(received["id"], "submitted"),
|
|
105
|
+
"artifacts": [{"artifactId": "r1", "parts": [report_part(report)]}], # report carries "attempt": 1
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
# Manager: turn the worker's task into actions on the order's record, then review.
|
|
109
|
+
for action in task_actions(order, state="offered", attempts=0, task=task, worker=order.to):
|
|
110
|
+
if action.kind == "submit":
|
|
111
|
+
findings = validate_report(action.report, order)
|
|
112
|
+
... # apply "accept", "decline" or "submit" to your record
|
|
113
|
+
reply = {"role": "user", "messageId": "m2", "taskId": "t1",
|
|
114
|
+
"parts": [review_part({"order_id": order.id, "decision": "approve"})]}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
`task_actions` runs the checks the TypeScript SDK's `recordTask` runs before it changes the desk: the peer is the order's worker, each report carries the next `attempt`, is for this order and from this worker, and seeing the same task twice asks for nothing new. This package has no desk, so it returns the actions (`accept`, `decline` with the status text as its reason, `submit` with the report) for you to apply. The caller must have authenticated the A2A peer as the worker.
|
|
118
|
+
|
|
85
119
|
## Matches the TypeScript SDK
|
|
86
120
|
|
|
87
121
|
Findings have the same rule ids, kinds and JSON Pointer paths as [`agent-work-layer`](https://www.npmjs.com/package/agent-work-layer) on npm, including its details:
|
|
@@ -94,7 +128,7 @@ The messages are worded differently, and schema findings (O1, R1, R11) can come
|
|
|
94
128
|
|
|
95
129
|
## Not here yet
|
|
96
130
|
|
|
97
|
-
The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents and the
|
|
131
|
+
The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents, the checks and the A2A binding.
|
|
98
132
|
|
|
99
133
|
## License
|
|
100
134
|
|
|
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "agent-work-layer"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "Work Orders and Work Reports for AI agents: Pydantic models
|
|
7
|
+
version = "0.7.0"
|
|
8
|
+
description = "Work Orders and Work Reports for AI agents: Pydantic models, the spec's validation rules and the A2A binding."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
11
11
|
authors = [{ name = "Probita" }]
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
"""Agent Work Layer for Python: Work Order and Work Report models and validation
|
|
1
|
+
"""Agent Work Layer for Python: Work Order and Work Report models and validation, and the A2A binding
|
|
2
|
+
in :mod:`agent_work_layer.a2a`.
|
|
2
3
|
|
|
3
4
|
See SPEC.md in https://github.com/probita-ai/agent-work-layer for the format.
|
|
4
5
|
"""
|
|
6
|
+
from .a2a import STATES
|
|
7
|
+
from .errors import AwlError
|
|
5
8
|
from .models import (
|
|
6
9
|
Amounts,
|
|
7
10
|
Artifact,
|
|
@@ -37,18 +40,20 @@ from .validate import (
|
|
|
37
40
|
validate_order,
|
|
38
41
|
validate_own_cost,
|
|
39
42
|
validate_report,
|
|
43
|
+
validate_usage,
|
|
40
44
|
work_order_schema,
|
|
41
45
|
work_report_schema,
|
|
42
46
|
)
|
|
43
47
|
|
|
44
|
-
__version__ = "0.
|
|
48
|
+
__version__ = "0.7.0"
|
|
45
49
|
|
|
46
50
|
__all__ = [
|
|
47
51
|
"Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Effect", "Evidence", "Handoff",
|
|
48
52
|
"WorkOrder", "WorkReport", "WorkResult",
|
|
53
|
+
"AwlError", "STATES",
|
|
49
54
|
"ORDER_SPEC", "ORDER_SPECS", "REPORT_SPEC", "REPORT_SPECS", "UNITS", "Finding",
|
|
50
55
|
"effect_references", "order_spec_for", "report_spec_for", "has_invalid", "held_by_sub_orders", "is_work_order", "is_work_report", "pattern_covered", "tool_allowed",
|
|
51
|
-
"validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report",
|
|
56
|
+
"validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report", "validate_usage",
|
|
52
57
|
"work_order_schema", "work_report_schema",
|
|
53
58
|
"__version__",
|
|
54
59
|
]
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""The A2A binding (SPEC.md §9.2): Work Orders, Work Reports and reviews as A2A data parts, AWL states
|
|
2
|
+
as A2A task states, and the actions a worker's A2A task asks of the manager's desk.
|
|
3
|
+
|
|
4
|
+
No A2A SDK: parts and tasks are A2A v0.3's JSON as plain dicts, so this works with any A2A
|
|
5
|
+
implementation. It matches ``agent-work-layer/a2a`` in the TypeScript SDK, except that this package
|
|
6
|
+
has no desk: :func:`task_actions` returns what to apply instead of applying it.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import copy
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence
|
|
13
|
+
|
|
14
|
+
from .errors import AwlError
|
|
15
|
+
from .validate import ORDER_SPECS, REPORT_SPECS, _plain, _report_shape, _schema_findings, validate_order
|
|
16
|
+
|
|
17
|
+
#: The URI an agent lists in its Agent Card's ``capabilities.extensions``, and a message in its ``extensions``.
|
|
18
|
+
AWL_A2A_EXTENSION = "https://github.com/probita-ai/agent-work-layer/blob/main/SPEC.md#92-a2a"
|
|
19
|
+
|
|
20
|
+
#: Media types of the AWL data parts, carried in each part's ``metadata.mediaType``.
|
|
21
|
+
AWL_MEDIA_TYPES: Mapping[str, str] = {
|
|
22
|
+
"order": "application/vnd.awl.work-order+json",
|
|
23
|
+
"report": "application/vnd.awl.work-report+json",
|
|
24
|
+
"review": "application/vnd.awl.review+json",
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
#: The order lifecycle states (SPEC.md §6).
|
|
28
|
+
STATES = ("offered", "accepted", "working", "blocked", "submitted", "approved", "declined", "expired", "cancelled")
|
|
29
|
+
|
|
30
|
+
State = Literal["offered", "accepted", "working", "blocked", "submitted", "approved", "declined", "expired", "cancelled"]
|
|
31
|
+
A2ATaskState = Literal[
|
|
32
|
+
"submitted", "working", "input-required", "completed", "canceled", "failed", "rejected", "auth-required", "unknown"
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
_TASK_STATE: Mapping[str, str] = {
|
|
36
|
+
"offered": "submitted",
|
|
37
|
+
"accepted": "working",
|
|
38
|
+
"working": "working",
|
|
39
|
+
"blocked": "input-required",
|
|
40
|
+
"submitted": "input-required",
|
|
41
|
+
"approved": "completed",
|
|
42
|
+
"declined": "rejected",
|
|
43
|
+
"expired": "failed",
|
|
44
|
+
"cancelled": "canceled",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _part(data: Any, media_type: str) -> Dict[str, Any]:
|
|
49
|
+
return {"kind": "data", "data": copy.deepcopy(_plain(data)), "metadata": {"mediaType": media_type}}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def order_part(order: Any) -> Dict[str, Any]:
|
|
53
|
+
"""A Work Order (a dict or a :class:`WorkOrder`) as an A2A data part."""
|
|
54
|
+
return _part(order, AWL_MEDIA_TYPES["order"])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def report_part(report: Any) -> Dict[str, Any]:
|
|
58
|
+
"""A Work Report (a dict or a :class:`WorkReport`) as an A2A data part."""
|
|
59
|
+
return _part(report, AWL_MEDIA_TYPES["report"])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def review_part(review: Mapping[str, Any]) -> Dict[str, Any]:
|
|
63
|
+
"""A review as an A2A data part. Raises ``AwlError("BAD_REQUEST")`` when it is not a valid review."""
|
|
64
|
+
check_review(review)
|
|
65
|
+
return _part(dict(review), AWL_MEDIA_TYPES["review"])
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def check_review(review: Any) -> None:
|
|
69
|
+
"""Raises ``AwlError("BAD_REQUEST")`` unless ``review`` is a valid review: ``order_id``, ``decision``
|
|
70
|
+
``"approve"`` or ``"rework"``, a ``reason`` for a rework, and ``effects`` only on an approval (§4.6)."""
|
|
71
|
+
ok = (
|
|
72
|
+
isinstance(review, Mapping)
|
|
73
|
+
and isinstance(review.get("order_id"), str)
|
|
74
|
+
and bool(review["order_id"])
|
|
75
|
+
and review.get("decision") in ("approve", "rework")
|
|
76
|
+
and (review.get("reason") is None or isinstance(review["reason"], str))
|
|
77
|
+
and (
|
|
78
|
+
review.get("effects") is None
|
|
79
|
+
or (isinstance(review["effects"], list) and all(isinstance(e, str) for e in review["effects"]))
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
if not ok:
|
|
83
|
+
raise AwlError("BAD_REQUEST", "a review needs order_id, decision approve or rework, and optional reason and effects")
|
|
84
|
+
if review["decision"] == "rework" and not (review.get("reason") or "").strip():
|
|
85
|
+
raise AwlError("BAD_REQUEST", "rework needs a reason the worker can act on")
|
|
86
|
+
if review["decision"] == "rework" and review.get("effects") is not None:
|
|
87
|
+
raise AwlError("BAD_REQUEST", "only an approval can choose effects")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass
|
|
91
|
+
class AwlParts:
|
|
92
|
+
"""The AWL documents found in a message's or artifact's parts."""
|
|
93
|
+
|
|
94
|
+
orders: List[Dict[str, Any]] = field(default_factory=list)
|
|
95
|
+
reports: List[Dict[str, Any]] = field(default_factory=list)
|
|
96
|
+
reviews: List[Dict[str, Any]] = field(default_factory=list)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def read_parts(parts: Optional[Sequence[Any]]) -> AwlParts:
|
|
100
|
+
"""Reads the AWL data parts among ``parts``, by ``metadata.mediaType``; other parts are ignored.
|
|
101
|
+
|
|
102
|
+
An order must pass the order checks, and a report the Work Report schema (R1); a report's other
|
|
103
|
+
checks need its order (:func:`validate_report`). Raises ``AwlError("VALIDATION_FAILED")`` with the
|
|
104
|
+
findings, or ``AwlError("BAD_REQUEST")`` for a bad review.
|
|
105
|
+
"""
|
|
106
|
+
out = AwlParts()
|
|
107
|
+
for p in parts or ():
|
|
108
|
+
if not isinstance(p, Mapping) or p.get("kind") != "data":
|
|
109
|
+
continue
|
|
110
|
+
metadata = p.get("metadata")
|
|
111
|
+
media_type = metadata.get("mediaType") if isinstance(metadata, Mapping) else None
|
|
112
|
+
data = p.get("data")
|
|
113
|
+
if media_type == AWL_MEDIA_TYPES["order"]:
|
|
114
|
+
findings = validate_order(data)
|
|
115
|
+
if findings:
|
|
116
|
+
raise AwlError("VALIDATION_FAILED", "work order part rejected", findings)
|
|
117
|
+
out.orders.append(data)
|
|
118
|
+
elif media_type == AWL_MEDIA_TYPES["report"]:
|
|
119
|
+
findings = _schema_findings("R1", _report_shape.iter_errors(data))
|
|
120
|
+
if findings:
|
|
121
|
+
raise AwlError("VALIDATION_FAILED", "work report part rejected", findings)
|
|
122
|
+
out.reports.append(data)
|
|
123
|
+
elif media_type == AWL_MEDIA_TYPES["review"]:
|
|
124
|
+
check_review(data)
|
|
125
|
+
out.reviews.append(data)
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def task_state(state: str) -> str:
|
|
130
|
+
"""The A2A task state for an AWL state (§9.2). ``blocked`` and ``submitted`` both need the manager, so
|
|
131
|
+
both are ``input-required``; the status's ``metadata["awl/state"]`` tells them apart."""
|
|
132
|
+
try:
|
|
133
|
+
return _TASK_STATE[state]
|
|
134
|
+
except KeyError:
|
|
135
|
+
raise ValueError(f"unknown AWL state {state!r}") from None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def task_status(order_id: str, state: str) -> Dict[str, Any]:
|
|
139
|
+
"""The A2A task status for an order in ``state``, with the AWL state and order id in its metadata."""
|
|
140
|
+
return {"state": task_state(state), "metadata": {"awl/state": state, "awl/order": order_id}}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def agent_card_extension(required: bool = False) -> Dict[str, Any]:
|
|
144
|
+
"""The entry for an Agent Card's ``capabilities.extensions``, saying which AWL versions the agent reads."""
|
|
145
|
+
return {
|
|
146
|
+
"uri": AWL_A2A_EXTENSION,
|
|
147
|
+
"description": "Takes Work Orders and returns Work Reports with evidence (Agent Work Layer).",
|
|
148
|
+
"required": required,
|
|
149
|
+
"params": {"order_specs": list(ORDER_SPECS), "report_specs": list(REPORT_SPECS)},
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass(frozen=True)
|
|
154
|
+
class TaskAction:
|
|
155
|
+
"""One worker action a task asks of the desk: ``accept``; ``decline``, with the status text as
|
|
156
|
+
``reason``; or ``submit``, with the ``report`` as sent (check it with :func:`validate_report`)."""
|
|
157
|
+
|
|
158
|
+
kind: Literal["accept", "decline", "submit"]
|
|
159
|
+
reason: Optional[str] = None
|
|
160
|
+
report: Optional[Dict[str, Any]] = None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def task_actions(order: Any, state: str, attempts: int, task: Mapping[str, Any], worker: str) -> List[TaskAction]:
|
|
164
|
+
"""The worker actions a worker's A2A task asks of the manager's desk (§9.2), in the order to apply them.
|
|
165
|
+
|
|
166
|
+
``state`` is the order's AWL state on the desk, and ``attempts`` the number of reports the desk holds.
|
|
167
|
+
A ``rejected`` task declines an offered order and any later state accepts it; then each Work Report in
|
|
168
|
+
the task's artifacts that the desk does not have yet (by ``attempt``, which each report MUST carry) is
|
|
169
|
+
submitted, in order. Seeing the same task twice asks for nothing new.
|
|
170
|
+
|
|
171
|
+
The caller MUST have authenticated the A2A peer as ``worker``, the order's ``to``: the desk takes these
|
|
172
|
+
actions on its word. Raises ``AwlError`` with ``FORBIDDEN`` for another agent or a report from someone
|
|
173
|
+
else, and ``BAD_REQUEST`` for a report for another order, without an ``attempt`` or skipping one.
|
|
174
|
+
"""
|
|
175
|
+
order = _plain(order)
|
|
176
|
+
order_id = order["id"]
|
|
177
|
+
if worker != order["to"]:
|
|
178
|
+
raise AwlError("FORBIDDEN", f'"{worker}" is not the worker of order "{order_id}"')
|
|
179
|
+
status = task.get("status") or {}
|
|
180
|
+
task_st = status.get("state")
|
|
181
|
+
actions: List[TaskAction] = []
|
|
182
|
+
if state == "offered":
|
|
183
|
+
if task_st == "rejected":
|
|
184
|
+
return [TaskAction("decline", reason=_text_of((status.get("message") or {}).get("parts")))]
|
|
185
|
+
if task_st in (None, "submitted", "unknown", "auth-required"):
|
|
186
|
+
return []
|
|
187
|
+
actions.append(TaskAction("accept"))
|
|
188
|
+
|
|
189
|
+
reports = [r for a in task.get("artifacts") or () for r in read_parts(a.get("parts")).reports]
|
|
190
|
+
for r in reports:
|
|
191
|
+
if not isinstance(r.get("attempt"), int):
|
|
192
|
+
raise AwlError("BAD_REQUEST", "a report sent over A2A must carry its attempt")
|
|
193
|
+
held = attempts
|
|
194
|
+
for r in sorted(reports, key=lambda r: r["attempt"]):
|
|
195
|
+
if r["attempt"] <= held:
|
|
196
|
+
continue
|
|
197
|
+
if r["attempt"] != held + 1:
|
|
198
|
+
raise AwlError("BAD_REQUEST", f"the task's next report is attempt {r['attempt']}; the desk expects {held + 1}")
|
|
199
|
+
if r["order_id"] != order_id:
|
|
200
|
+
raise AwlError("BAD_REQUEST", f'the task carries a report for "{r["order_id"]}", not "{order_id}"')
|
|
201
|
+
if r["from"] != worker:
|
|
202
|
+
raise AwlError("FORBIDDEN", f'the report is from "{r["from"]}", not "{worker}"')
|
|
203
|
+
actions.append(TaskAction("submit", report=r))
|
|
204
|
+
held += 1
|
|
205
|
+
return actions
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _text_of(parts: Any) -> Optional[str]:
|
|
209
|
+
texts = [p["text"] for p in parts or () if isinstance(p, Mapping) and p.get("kind") == "text"]
|
|
210
|
+
return "\n".join(texts) or None
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""The error raised where a check refuses a document outright, with the TypeScript SDK's codes."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import List, Literal, Optional, Sequence
|
|
5
|
+
|
|
6
|
+
from .validate import Finding
|
|
7
|
+
|
|
8
|
+
ErrorCode = Literal["VALIDATION_FAILED", "BAD_REQUEST", "FORBIDDEN"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AwlError(Exception):
|
|
12
|
+
"""A refused document or request. ``code`` matches the TypeScript SDK's ``AwlError`` codes, and
|
|
13
|
+
``findings`` holds the failed checks for ``VALIDATION_FAILED``."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, code: ErrorCode, message: str, findings: Optional[Sequence[Finding]] = None) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.code: ErrorCode = code
|
|
18
|
+
self.message = message
|
|
19
|
+
self.findings: List[Finding] = list(findings or [])
|
|
20
|
+
|
|
21
|
+
def __repr__(self) -> str:
|
|
22
|
+
return f"AwlError({self.code!r}, {self.message!r})"
|
|
@@ -355,8 +355,9 @@ _MISSING = object()
|
|
|
355
355
|
_CALL_NUMBER = re.compile(r"^[1-9][0-9]*\Z", re.ASCII)
|
|
356
356
|
|
|
357
357
|
|
|
358
|
-
def validate_report(report: Any, order: Any) -> List[Finding]:
|
|
359
|
-
"""Runs report checks R1–R12 and R14–R16 against the order it answers
|
|
358
|
+
def validate_report(report: Any, order: Any, usage: Optional[Mapping[str, Any]] = None) -> List[Finding]:
|
|
359
|
+
"""Runs report checks R1–R12 and R14–R16 against the order it answers, and R17–R19 against what
|
|
360
|
+
the order's gateway measured when ``usage`` is given. The order is assumed valid."""
|
|
360
361
|
report, order = _plain(report), _plain(order)
|
|
361
362
|
shape = _schema_findings("R1", _report_shape.iter_errors(report))
|
|
362
363
|
if shape:
|
|
@@ -426,6 +427,34 @@ def validate_report(report: Any, order: Any) -> List[Finding]:
|
|
|
426
427
|
elif r["pointer"] != "" and not r["pointer"].startswith("/"):
|
|
427
428
|
add("R16", "invalid", path, f'"{r["pointer"]}" is not a JSON Pointer')
|
|
428
429
|
refs.add(e["ref"])
|
|
430
|
+
if usage is not None:
|
|
431
|
+
out.extend(validate_usage(report, usage))
|
|
432
|
+
return out
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def validate_usage(report: Any, usage: Mapping[str, Any]) -> List[Finding]:
|
|
436
|
+
"""Runs report checks R17–R19 (§7.3): the report agrees with what the order's gateway measured.
|
|
437
|
+
|
|
438
|
+
``usage`` is ``{tool_calls, seconds?, tools_used, refs}``. A report may claim more than the
|
|
439
|
+
gateway saw, never less.
|
|
440
|
+
"""
|
|
441
|
+
report = _plain(report)
|
|
442
|
+
out: List[Finding] = []
|
|
443
|
+
logged = set(usage["refs"])
|
|
444
|
+
for i, e in enumerate(report["evidence"]):
|
|
445
|
+
if e["type"] == "tool_call" and "ref" in e and e["ref"] not in logged:
|
|
446
|
+
out.append(Finding("R17", "invalid", f"/evidence/{i}/ref", f'"{e["ref"]}" is not a call the gateway logged'))
|
|
447
|
+
calls = report["cost"].get("tool_calls")
|
|
448
|
+
if usage["tool_calls"] > 0 and (calls is None or calls < usage["tool_calls"]):
|
|
449
|
+
reported = "no" if calls is None else _num(calls)
|
|
450
|
+
out.append(Finding("R18", "invalid", "/cost/tool_calls", f'reports {reported} tool calls; the gateway counted {usage["tool_calls"]}'))
|
|
451
|
+
seconds = report["cost"].get("seconds")
|
|
452
|
+
if usage.get("seconds") is not None and seconds is not None and seconds < usage["seconds"]:
|
|
453
|
+
out.append(Finding("R18", "invalid", "/cost/seconds", f'reports {_num(seconds)} seconds; the gateway measured at least {usage["seconds"]}'))
|
|
454
|
+
used = set(report["tools_used"])
|
|
455
|
+
for tool in dict.fromkeys(usage["tools_used"]):
|
|
456
|
+
if tool not in used:
|
|
457
|
+
out.append(Finding("R19", "invalid", "/tools_used", f'the gateway logged calls to "{tool}"'))
|
|
429
458
|
return out
|
|
430
459
|
|
|
431
460
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|