agent-work-layer 0.6.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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agent-work-layer
3
- Version: 0.6.0
4
- Summary: Work Orders and Work Reports for AI agents: Pydantic models and the spec's validation rules.
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 and every validation rule 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.
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
 
@@ -104,6 +104,39 @@ assert validate_order(order) == [] # the validators accept models too
104
104
 
105
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.
106
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
+
107
140
  ## Matches the TypeScript SDK
108
141
 
109
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:
@@ -116,7 +149,7 @@ The messages are worded differently, and schema findings (O1, R1, R11) can come
116
149
 
117
150
  ## Not here yet
118
151
 
119
- The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents and the checks.
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.
120
153
 
121
154
  ## License
122
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 and every validation rule 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.
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
 
@@ -83,6 +83,39 @@ assert validate_order(order) == [] # the validators accept models too
83
83
 
84
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.
85
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
+
86
119
  ## Matches the TypeScript SDK
87
120
 
88
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:
@@ -95,7 +128,7 @@ The messages are worded differently, and schema findings (O1, R1, R11) can come
95
128
 
96
129
  ## Not here yet
97
130
 
98
- The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents and the checks.
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.
99
132
 
100
133
  ## License
101
134
 
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agent-work-layer"
7
- version = "0.6.0"
8
- description = "Work Orders and Work Reports for AI agents: Pydantic models and the spec's validation rules."
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,
@@ -42,11 +45,12 @@ from .validate import (
42
45
  work_report_schema,
43
46
  )
44
47
 
45
- __version__ = "0.6.0"
48
+ __version__ = "0.7.0"
46
49
 
47
50
  __all__ = [
48
51
  "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Effect", "Evidence", "Handoff",
49
52
  "WorkOrder", "WorkReport", "WorkResult",
53
+ "AwlError", "STATES",
50
54
  "ORDER_SPEC", "ORDER_SPECS", "REPORT_SPEC", "REPORT_SPECS", "UNITS", "Finding",
51
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",
52
56
  "validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report", "validate_usage",
@@ -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})"