agent-work-layer 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,46 @@
1
+ """Agent Work Layer for Python: Work Order and Work Report models and validation.
2
+
3
+ See SPEC.md in https://github.com/probita-ai/agent-work-layer for the format.
4
+ """
5
+ from .models import (
6
+ Amounts,
7
+ Artifact,
8
+ Attempt,
9
+ ContextRef,
10
+ Criterion,
11
+ Decision,
12
+ Evidence,
13
+ Handoff,
14
+ WorkOrder,
15
+ WorkReport,
16
+ WorkResult,
17
+ )
18
+ from .validate import (
19
+ ORDER_SPEC,
20
+ ORDER_SPECS,
21
+ REPORT_SPEC,
22
+ REPORT_SPECS,
23
+ UNITS,
24
+ Finding,
25
+ has_invalid,
26
+ is_work_order,
27
+ is_work_report,
28
+ pattern_covered,
29
+ tool_allowed,
30
+ validate_child_order,
31
+ validate_order,
32
+ validate_report,
33
+ work_order_schema,
34
+ work_report_schema,
35
+ )
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ __all__ = [
40
+ "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Evidence", "Handoff",
41
+ "WorkOrder", "WorkReport", "WorkResult",
42
+ "ORDER_SPEC", "ORDER_SPECS", "REPORT_SPEC", "REPORT_SPECS", "UNITS", "Finding",
43
+ "has_invalid", "is_work_order", "is_work_report", "pattern_covered", "tool_allowed",
44
+ "validate_child_order", "validate_order", "validate_report", "work_order_schema", "work_report_schema",
45
+ "__version__",
46
+ ]
@@ -0,0 +1,164 @@
1
+ """Pydantic models for Work Orders and Work Reports (SPEC.md §4 and §5).
2
+
3
+ The models give you types and catch obvious mistakes while you build a document. The checks
4
+ in :mod:`agent_work_layer.validate` are the normative ones; every ``validate_*`` function also
5
+ accepts these models.
6
+
7
+ ``from`` is a Python keyword, so the field is ``from_`` in Python and ``"from"`` in JSON.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime, timezone
12
+ from typing import Annotated, Any, Dict, List, Literal, Optional
13
+
14
+ from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, model_validator
15
+
16
+ from .validate import ORDER_SPEC, REPORT_SPEC
17
+
18
+ AgentRef = Annotated[str, Field(min_length=1, max_length=512)]
19
+
20
+
21
+ def _stamp(value: Any) -> Any:
22
+ if isinstance(value, datetime):
23
+ if value.tzinfo is None:
24
+ raise ValueError("timestamps need a time zone")
25
+ return value.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
26
+ return value
27
+
28
+
29
+ #: An RFC 3339 timestamp. Time-zone-aware datetimes are converted to strings.
30
+ Timestamp = Annotated[str, BeforeValidator(_stamp)]
31
+ Text = Annotated[str, Field(min_length=1)]
32
+
33
+
34
+ class _Part(BaseModel):
35
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
36
+
37
+
38
+ class _Document(_Part):
39
+ """A top-level document: unknown fields are allowed only as ``x-`` extensions."""
40
+
41
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
42
+
43
+ @model_validator(mode="after")
44
+ def _extensions_only(self) -> "_Document":
45
+ unknown = [k for k in (self.model_extra or {}) if not k.startswith("x-")]
46
+ if unknown:
47
+ raise ValueError(f"unknown fields {unknown}; extensions must start with 'x-'")
48
+ # `spec` always appears in to_dict(), even when left at its default.
49
+ self.model_fields_set.add("spec")
50
+ return self
51
+
52
+ def to_dict(self) -> Dict[str, Any]:
53
+ """The document as JSON-ready data, with ``from`` spelled as in the spec."""
54
+ return self.model_dump(mode="json", by_alias=True, exclude_unset=True, exclude_none=True)
55
+
56
+
57
+ class Criterion(_Part):
58
+ id: Annotated[str, Field(min_length=1, max_length=64)]
59
+ text: Text
60
+
61
+
62
+ class Amounts(_Part):
63
+ """A budget (upper limits) or a cost (what was spent). See SPEC.md §4.2."""
64
+
65
+ usd: Optional[Annotated[float, Field(ge=0)]] = None
66
+ tokens: Optional[Annotated[int, Field(ge=0)]] = None
67
+ tool_calls: Optional[Annotated[int, Field(ge=0)]] = None
68
+ seconds: Optional[Annotated[float, Field(ge=0)]] = None
69
+
70
+
71
+ class ContextRef(_Part):
72
+ uri: Text
73
+ note: Optional[str] = None
74
+
75
+
76
+ class Decision(_Part):
77
+ text: Text
78
+ why: Optional[str] = None
79
+
80
+
81
+ class Attempt(_Part):
82
+ text: Text
83
+ result: Optional[str] = None
84
+
85
+
86
+ class Handoff(_Part):
87
+ """What the next worker should know (SPEC.md §4.4). At least one field must be set."""
88
+
89
+ summary: Optional[Text] = None
90
+ decisions: Optional[List[Decision]] = None
91
+ tried: Optional[List[Attempt]] = None
92
+ open_questions: Optional[List[Text]] = None
93
+ next_step: Optional[Text] = None
94
+
95
+ @model_validator(mode="after")
96
+ def _not_empty(self) -> "Handoff":
97
+ if not self.model_fields_set:
98
+ raise ValueError("a handoff must not be empty")
99
+ return self
100
+
101
+
102
+ class WorkOrder(_Document):
103
+ spec: Literal["awl/work-order@0.1", "awl/work-order@0.2"] = ORDER_SPEC
104
+ id: Annotated[str, Field(min_length=1, max_length=128)]
105
+ created_at: Timestamp
106
+ from_: AgentRef = Field(alias="from")
107
+ to: AgentRef
108
+ goal: Text
109
+ criteria: Annotated[List[Criterion], Field(min_length=1)]
110
+ budget: Amounts
111
+ deadline: Timestamp
112
+ #: Tool patterns: ``server/tool``, ``server/*`` or ``*``.
113
+ tools: List[Annotated[str, Field(pattern=r"^(\*|[A-Za-z0-9_.-]+/(\*|[A-Za-z0-9_.-]+))$")]]
114
+ escalate_to: Optional[AgentRef] = None
115
+ inputs: Optional[Dict[str, Any]] = None
116
+ context: Optional[List[ContextRef]] = None
117
+ handoff: Optional[Handoff] = None
118
+ output_schema: Optional[Dict[str, Any]] = None
119
+ parent_id: Optional[Text] = None
120
+ metadata: Optional[Dict[str, Any]] = None
121
+
122
+ @model_validator(mode="after")
123
+ def _budget_not_empty(self) -> "WorkOrder":
124
+ if not self.budget.model_fields_set:
125
+ raise ValueError("a budget must set at least one unit")
126
+ return self
127
+
128
+
129
+ class Evidence(_Part):
130
+ criterion: Text
131
+ type: Literal["tool_call", "artifact", "citation", "note"]
132
+ ref: Optional[str] = None
133
+ note: Optional[str] = None
134
+
135
+
136
+ class Artifact(_Part):
137
+ uri: Text
138
+ media_type: Optional[str] = None
139
+ note: Optional[str] = None
140
+
141
+
142
+ class WorkResult(_Part):
143
+ summary: str
144
+ output: Any = None
145
+ artifacts: Optional[List[Artifact]] = None
146
+
147
+
148
+ class WorkReport(_Document):
149
+ spec: Literal["awl/work-report@0.1", "awl/work-report@0.2"] = REPORT_SPEC
150
+ order_id: Text
151
+ from_: AgentRef = Field(alias="from")
152
+ status: Literal["done", "blocked", "failed"]
153
+ result: WorkResult
154
+ evidence: List[Evidence]
155
+ cost: Amounts
156
+ finished_at: Timestamp
157
+ #: Exact tool names, ``server/tool``.
158
+ tools_used: List[Annotated[str, Field(pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")]]
159
+ started_at: Optional[Timestamp] = None
160
+ attempt: Optional[Annotated[int, Field(ge=1)]] = None
161
+ questions: Optional[List[Text]] = None
162
+ error: Optional[Text] = None
163
+ handoff: Optional[Handoff] = None
164
+ metadata: Optional[Dict[str, Any]] = None
File without changes
@@ -0,0 +1,90 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://awl.dev/schemas/work-order-0.2.json",
4
+ "title": "AWL Work Order v0.2",
5
+ "type": "object",
6
+ "required": ["spec", "id", "created_at", "from", "to", "goal", "criteria", "budget", "deadline", "tools"],
7
+ "properties": {
8
+ "spec": { "enum": ["awl/work-order@0.1", "awl/work-order@0.2"] },
9
+ "id": { "type": "string", "minLength": 1, "maxLength": 128 },
10
+ "created_at": { "type": "string", "format": "date-time" },
11
+ "from": { "$ref": "#/$defs/agentRef" },
12
+ "to": { "$ref": "#/$defs/agentRef" },
13
+ "goal": { "type": "string", "minLength": 1 },
14
+ "criteria": {
15
+ "type": "array",
16
+ "minItems": 1,
17
+ "items": {
18
+ "type": "object",
19
+ "required": ["id", "text"],
20
+ "properties": {
21
+ "id": { "type": "string", "minLength": 1, "maxLength": 64 },
22
+ "text": { "type": "string", "minLength": 1 }
23
+ },
24
+ "additionalProperties": false
25
+ }
26
+ },
27
+ "budget": { "$ref": "#/$defs/amounts", "minProperties": 1 },
28
+ "deadline": { "type": "string", "format": "date-time" },
29
+ "tools": { "type": "array", "items": { "$ref": "#/$defs/toolPattern" } },
30
+ "escalate_to": { "$ref": "#/$defs/agentRef" },
31
+ "inputs": { "type": "object" },
32
+ "context": {
33
+ "type": "array",
34
+ "items": {
35
+ "type": "object",
36
+ "required": ["uri"],
37
+ "properties": { "uri": { "type": "string", "minLength": 1 }, "note": { "type": "string" } },
38
+ "additionalProperties": false
39
+ }
40
+ },
41
+ "handoff": { "$ref": "#/$defs/handoff" },
42
+ "output_schema": { "type": "object" },
43
+ "parent_id": { "type": "string", "minLength": 1 },
44
+ "metadata": { "type": "object" }
45
+ },
46
+ "patternProperties": { "^x-": {} },
47
+ "additionalProperties": false,
48
+ "$defs": {
49
+ "agentRef": { "type": "string", "minLength": 1, "maxLength": 512 },
50
+ "toolPattern": { "type": "string", "pattern": "^(\\*|[A-Za-z0-9_.-]+/(\\*|[A-Za-z0-9_.-]+))$" },
51
+ "amounts": {
52
+ "type": "object",
53
+ "properties": {
54
+ "usd": { "type": "number", "minimum": 0 },
55
+ "tokens": { "type": "integer", "minimum": 0 },
56
+ "tool_calls": { "type": "integer", "minimum": 0 },
57
+ "seconds": { "type": "number", "minimum": 0 }
58
+ },
59
+ "additionalProperties": false
60
+ },
61
+ "handoff": {
62
+ "type": "object",
63
+ "minProperties": 1,
64
+ "properties": {
65
+ "summary": { "type": "string", "minLength": 1 },
66
+ "decisions": {
67
+ "type": "array",
68
+ "items": {
69
+ "type": "object",
70
+ "required": ["text"],
71
+ "properties": { "text": { "type": "string", "minLength": 1 }, "why": { "type": "string" } },
72
+ "additionalProperties": false
73
+ }
74
+ },
75
+ "tried": {
76
+ "type": "array",
77
+ "items": {
78
+ "type": "object",
79
+ "required": ["text"],
80
+ "properties": { "text": { "type": "string", "minLength": 1 }, "result": { "type": "string" } },
81
+ "additionalProperties": false
82
+ }
83
+ },
84
+ "open_questions": { "type": "array", "items": { "type": "string", "minLength": 1 } },
85
+ "next_step": { "type": "string", "minLength": 1 }
86
+ },
87
+ "additionalProperties": false
88
+ }
89
+ }
90
+ }
@@ -0,0 +1,99 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://awl.dev/schemas/work-report-0.2.json",
4
+ "title": "AWL Work Report v0.2",
5
+ "type": "object",
6
+ "required": ["spec", "order_id", "from", "status", "result", "evidence", "cost", "finished_at", "tools_used"],
7
+ "properties": {
8
+ "spec": { "enum": ["awl/work-report@0.1", "awl/work-report@0.2"] },
9
+ "order_id": { "type": "string", "minLength": 1 },
10
+ "from": { "type": "string", "minLength": 1, "maxLength": 512 },
11
+ "status": { "enum": ["done", "blocked", "failed"] },
12
+ "result": {
13
+ "type": "object",
14
+ "required": ["summary"],
15
+ "properties": {
16
+ "summary": { "type": "string" },
17
+ "output": {},
18
+ "artifacts": {
19
+ "type": "array",
20
+ "items": {
21
+ "type": "object",
22
+ "required": ["uri"],
23
+ "properties": {
24
+ "uri": { "type": "string", "minLength": 1 },
25
+ "media_type": { "type": "string" },
26
+ "note": { "type": "string" }
27
+ },
28
+ "additionalProperties": false
29
+ }
30
+ }
31
+ },
32
+ "additionalProperties": false
33
+ },
34
+ "evidence": {
35
+ "type": "array",
36
+ "items": {
37
+ "type": "object",
38
+ "required": ["criterion", "type"],
39
+ "properties": {
40
+ "criterion": { "type": "string", "minLength": 1 },
41
+ "type": { "enum": ["tool_call", "artifact", "citation", "note"] },
42
+ "ref": { "type": "string" },
43
+ "note": { "type": "string" }
44
+ },
45
+ "additionalProperties": false
46
+ }
47
+ },
48
+ "cost": {
49
+ "type": "object",
50
+ "properties": {
51
+ "usd": { "type": "number", "minimum": 0 },
52
+ "tokens": { "type": "integer", "minimum": 0 },
53
+ "tool_calls": { "type": "integer", "minimum": 0 },
54
+ "seconds": { "type": "number", "minimum": 0 }
55
+ },
56
+ "additionalProperties": false
57
+ },
58
+ "started_at": { "type": "string", "format": "date-time" },
59
+ "finished_at": { "type": "string", "format": "date-time" },
60
+ "tools_used": { "type": "array", "items": { "type": "string", "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$" } },
61
+ "attempt": { "type": "integer", "minimum": 1 },
62
+ "questions": { "type": "array", "items": { "type": "string", "minLength": 1 } },
63
+ "error": { "type": "string", "minLength": 1 },
64
+ "handoff": { "$ref": "#/$defs/handoff" },
65
+ "metadata": { "type": "object" }
66
+ },
67
+ "patternProperties": { "^x-": {} },
68
+ "additionalProperties": false,
69
+ "$defs": {
70
+ "handoff": {
71
+ "type": "object",
72
+ "minProperties": 1,
73
+ "properties": {
74
+ "summary": { "type": "string", "minLength": 1 },
75
+ "decisions": {
76
+ "type": "array",
77
+ "items": {
78
+ "type": "object",
79
+ "required": ["text"],
80
+ "properties": { "text": { "type": "string", "minLength": 1 }, "why": { "type": "string" } },
81
+ "additionalProperties": false
82
+ }
83
+ },
84
+ "tried": {
85
+ "type": "array",
86
+ "items": {
87
+ "type": "object",
88
+ "required": ["text"],
89
+ "properties": { "text": { "type": "string", "minLength": 1 }, "result": { "type": "string" } },
90
+ "additionalProperties": false
91
+ }
92
+ },
93
+ "open_questions": { "type": "array", "items": { "type": "string", "minLength": 1 } },
94
+ "next_step": { "type": "string", "minLength": 1 }
95
+ },
96
+ "additionalProperties": false
97
+ }
98
+ }
99
+ }
@@ -0,0 +1,370 @@
1
+ """Checks from SPEC.md §7 (orders and reports) and §8 (sub-orders).
2
+
3
+ Findings carry the same rule ids, kinds and paths as the TypeScript SDK. Paths are JSON
4
+ Pointers into the document; schema findings use the path of the offending value, or of
5
+ its parent object for missing and unknown fields.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import math
11
+ import re
12
+ from dataclasses import asdict, dataclass
13
+ from functools import lru_cache
14
+ from importlib import resources
15
+ from typing import Any, Callable, Dict, Iterable, Iterator, List, Literal, Mapping, Optional, Sequence
16
+
17
+ from jsonschema import Draft202012Validator, FormatChecker, ValidationError
18
+ from jsonschema.exceptions import SchemaError
19
+ from jsonschema.validators import extend
20
+
21
+ ORDER_SPEC = "awl/work-order@0.2"
22
+ REPORT_SPEC = "awl/work-report@0.2"
23
+ #: Every spec version this package reads (SPEC.md §11).
24
+ ORDER_SPECS = ("awl/work-order@0.1", ORDER_SPEC)
25
+ REPORT_SPECS = ("awl/work-report@0.1", REPORT_SPEC)
26
+ #: Budget and cost units (SPEC.md §4.2).
27
+ UNITS = ("usd", "tokens", "tool_calls", "seconds")
28
+
29
+ FindingKind = Literal["invalid", "limit"]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Finding:
34
+ """A finding from a check in SPEC.md §7–§8. ``limit`` findings are recorded; ``invalid`` ones reject."""
35
+
36
+ rule: str
37
+ kind: FindingKind
38
+ path: str
39
+ message: str
40
+
41
+ def to_dict(self) -> Dict[str, str]:
42
+ return asdict(self)
43
+
44
+
45
+ def _load(name: str) -> Dict[str, Any]:
46
+ return json.loads(resources.files(__package__).joinpath("schemas", name).read_text("utf-8"))
47
+
48
+
49
+ #: The JSON Schemas shipped with this package (the same files as the repository's ``schemas/``).
50
+ work_order_schema: Dict[str, Any] = _load("work-order.schema.json")
51
+ work_report_schema: Dict[str, Any] = _load("work-report.schema.json")
52
+
53
+ # ---- JSON Schema, behaving like the TypeScript SDK's Ajv setup -------------------------------------
54
+
55
+ _DATE = re.compile(r"^(\d\d\d\d)-(\d\d)-(\d\d)$", re.ASCII)
56
+ _TIME = re.compile(r"^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$", re.ASCII | re.IGNORECASE)
57
+ _SEPARATOR = re.compile(r"t|\s", re.IGNORECASE)
58
+ _DAYS = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
59
+
60
+
61
+ def _leap(year: int) -> bool:
62
+ return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
63
+
64
+
65
+ def _is_date(s: str) -> bool:
66
+ m = _DATE.match(s)
67
+ if not m:
68
+ return False
69
+ year, month, day = int(m[1]), int(m[2]), int(m[3])
70
+ return 1 <= month <= 12 and 1 <= day <= (29 if month == 2 and _leap(year) else _DAYS[month])
71
+
72
+
73
+ def _is_time(s: str) -> bool:
74
+ m = _TIME.match(s)
75
+ if not m:
76
+ return False
77
+ hr, mins, sec = int(m[1]), int(m[2]), float(m[3])
78
+ tz, sign = m[4], (-1 if m[5] == "-" else 1)
79
+ tz_h, tz_m = int(m[6] or 0), int(m[7] or 0)
80
+ if tz_h > 23 or tz_m > 59 or not tz:
81
+ return False
82
+ if hr <= 23 and mins <= 59 and sec < 60:
83
+ return True
84
+ # A leap second, which must fall at 23:59 UTC.
85
+ utc_min = mins - tz_m * sign
86
+ utc_hr = hr - tz_h * sign - (1 if utc_min < 0 else 0)
87
+ return utc_hr in (23, -1) and utc_min in (59, -1) and sec < 61
88
+
89
+
90
+ def _is_date_time(s: object) -> bool:
91
+ """RFC 3339 date-time with a required time zone, as ajv-formats checks it."""
92
+ if not isinstance(s, str):
93
+ return True
94
+ parts = _SEPARATOR.split(s)
95
+ return len(parts) == 2 and _is_date(parts[0]) and _is_time(parts[1])
96
+
97
+
98
+ _formats = FormatChecker()
99
+ _formats.checks("date-time")(_is_date_time)
100
+ _formats.checks("date")(lambda s: not isinstance(s, str) or _is_date(s))
101
+
102
+
103
+ @lru_cache(maxsize=256)
104
+ def _js_regex(pattern: str) -> "re.Pattern[str]":
105
+ """Compiles a JSON Schema pattern so it behaves as in JavaScript: ``$`` matches only at the very end, ``\\d`` only ASCII."""
106
+ out, in_class, i = [], False, 0
107
+ while i < len(pattern):
108
+ c = pattern[i]
109
+ if c == "\\":
110
+ out.append(pattern[i : i + 2])
111
+ i += 2
112
+ continue
113
+ if c == "[":
114
+ in_class = True
115
+ elif c == "]":
116
+ in_class = False
117
+ out.append(r"\Z" if c == "$" and not in_class else c)
118
+ i += 1
119
+ return re.compile("".join(out), re.ASCII)
120
+
121
+
122
+ def _pattern(validator: Any, pattern: str, instance: Any, schema: Any) -> Iterator[ValidationError]:
123
+ if validator.is_type(instance, "string") and not _js_regex(pattern).search(instance):
124
+ yield ValidationError(f"{instance!r} does not match {pattern!r}")
125
+
126
+
127
+ _Validator = extend(Draft202012Validator, {"pattern": _pattern})
128
+ _order_shape = _Validator(work_order_schema, format_checker=_formats)
129
+ _report_shape = _Validator(work_report_schema, format_checker=_formats)
130
+
131
+ _META_2020 = {"https://json-schema.org/draft/2020-12/schema", "https://json-schema.org/draft/2020-12/schema#"}
132
+
133
+
134
+ def _compile_user_schema(schema: Mapping[str, Any]) -> Any:
135
+ """Compiles a caller-supplied JSON Schema (2020-12). Raises SchemaError when it is not valid."""
136
+ declared = schema.get("$schema")
137
+ if declared is not None and declared not in _META_2020:
138
+ raise SchemaError(f"unsupported $schema {declared!r}; use JSON Schema 2020-12")
139
+ _Validator.check_schema(schema)
140
+ check = _Validator(schema, format_checker=_formats)
141
+ # Ajv resolves every $ref when it compiles; jsonschema waits until one is used.
142
+ resolver = check._resolver
143
+ for ref in _refs(schema):
144
+ try:
145
+ resolver.lookup(ref)
146
+ except Exception as e:
147
+ raise SchemaError(f"can't resolve reference {ref!r}") from e
148
+ return check
149
+
150
+
151
+ def _refs(value: Any) -> Iterator[str]:
152
+ if isinstance(value, dict):
153
+ for k, v in value.items():
154
+ if k in ("$ref", "$dynamicRef") and isinstance(v, str):
155
+ yield v
156
+ elif k not in ("const", "enum", "default", "examples"):
157
+ yield from _refs(v)
158
+ elif isinstance(value, list):
159
+ for v in value:
160
+ yield from _refs(v)
161
+
162
+
163
+ def _pointer(parts: Iterable[Any]) -> str:
164
+ return "".join("/" + str(p).replace("~", "~0").replace("/", "~1") for p in parts)
165
+
166
+
167
+ def _flatten(errors: Iterable[ValidationError]) -> Iterator[ValidationError]:
168
+ """Like Ajv with allErrors: a failed anyOf/oneOf reports each failing branch, then itself."""
169
+ for e in errors:
170
+ if e.validator in ("anyOf", "oneOf"):
171
+ yield from _flatten(e.context)
172
+ yield e
173
+
174
+
175
+ def _schema_findings(rule: str, errors: Iterable[ValidationError], prefix: str = "") -> List[Finding]:
176
+ out: List[Finding] = []
177
+ for e in _flatten(errors):
178
+ path = prefix + _pointer(e.absolute_path) or "/"
179
+ if e.validator == "additionalProperties":
180
+ # One finding per unknown field, like Ajv with allErrors.
181
+ known = e.schema.get("properties", {})
182
+ patterns = [_js_regex(p) for p in e.schema.get("patternProperties", {})]
183
+ for key in e.instance:
184
+ if key not in known and not any(p.search(key) for p in patterns):
185
+ out.append(Finding(rule, "invalid", path, f'unknown field "{key}"'))
186
+ else:
187
+ out.append(Finding(rule, "invalid", path, e.message))
188
+ return out
189
+
190
+
191
+ # ---- helpers ---------------------------------------------------------------------------------------
192
+
193
+
194
+ def _days_from_civil(y: int, m: int, d: int) -> int:
195
+ y -= m <= 2
196
+ era = (y if y >= 0 else y - 399) // 400
197
+ yoe = y - era * 400
198
+ doy = (153 * (m + (-3 if m > 2 else 9)) + 2) // 5 + d - 1
199
+ doe = yoe * 365 + yoe // 4 - yoe // 100 + doy
200
+ return era * 146097 + doe - 719468
201
+
202
+
203
+ _STAMP = re.compile(
204
+ r"^(\d{4})-(\d\d)-(\d\d)[tT ](\d\d):(\d\d):(\d\d)(?:\.(\d+))?(?:([zZ])|([+-])(\d\d)(?::?(\d\d))?)$", re.ASCII
205
+ )
206
+
207
+
208
+ def _time(s: Any) -> float:
209
+ """Milliseconds since the epoch, as JavaScript's Date.parse gives them; NaN when it would fail."""
210
+ m = _STAMP.match(s) if isinstance(s, str) else None
211
+ if not m or int(m[6]) >= 60 or (m[9] and m[11] is None):
212
+ return math.nan
213
+ ms = int((m[7] or "")[:3].ljust(3, "0"))
214
+ seconds = _days_from_civil(int(m[1]), int(m[2]), int(m[3])) * 86400 + int(m[4]) * 3600 + int(m[5]) * 60 + int(m[6])
215
+ if m[9]:
216
+ seconds -= (1 if m[9] == "+" else -1) * (int(m[10]) * 3600 + int(m[11]) * 60)
217
+ return seconds * 1000 + ms
218
+
219
+
220
+ def _num(x: Any) -> str:
221
+ """Formats a number the way JavaScript prints it in messages."""
222
+ return str(int(x)) if isinstance(x, float) and x.is_integer() and abs(x) < 1e21 else str(x)
223
+
224
+
225
+ def _plain(doc: Any) -> Any:
226
+ """Accepts pydantic models as well as plain JSON values."""
227
+ dump: Optional[Callable[..., Any]] = getattr(doc, "model_dump", None)
228
+ return dump(mode="json", by_alias=True, exclude_none=True) if dump else doc
229
+
230
+
231
+ # ---- public API ------------------------------------------------------------------------------------
232
+
233
+
234
+ def tool_allowed(tool: str, patterns: Sequence[str]) -> bool:
235
+ """Does a concrete tool name (``server/tool``) match one of the allowed patterns?"""
236
+ server = tool.split("/")[0]
237
+ return any(p == "*" or p == tool or p == f"{server}/*" for p in patterns)
238
+
239
+
240
+ def pattern_covered(child: str, parent: Sequence[str]) -> bool:
241
+ """Is everything a child pattern allows also allowed by the parent's patterns?"""
242
+ if "*" in parent:
243
+ return True
244
+ if child == "*":
245
+ return False
246
+ parts = child.split("/")
247
+ if len(parts) > 1 and parts[1] == "*":
248
+ return f"{parts[0]}/*" in parent
249
+ return tool_allowed(child, parent)
250
+
251
+
252
+ def is_work_order(value: Any) -> bool:
253
+ """Structurally a Work Order (rule O1 only)."""
254
+ return _order_shape.is_valid(_plain(value))
255
+
256
+
257
+ def is_work_report(value: Any) -> bool:
258
+ """Structurally a Work Report (rule R1 only)."""
259
+ return _report_shape.is_valid(_plain(value))
260
+
261
+
262
+ def validate_order(order: Any) -> List[Finding]:
263
+ """Runs order checks O1–O4. Returns an empty list when the order is valid."""
264
+ order = _plain(order)
265
+ shape = _schema_findings("O1", _order_shape.iter_errors(order))
266
+ if shape:
267
+ return shape
268
+ out: List[Finding] = []
269
+
270
+ seen = set()
271
+ for i, c in enumerate(order["criteria"]):
272
+ if c["id"] in seen:
273
+ out.append(Finding("O2", "invalid", f"/criteria/{i}/id", f'duplicate criterion id "{c["id"]}"'))
274
+ seen.add(c["id"])
275
+
276
+ if _time(order["deadline"]) <= _time(order["created_at"]):
277
+ out.append(Finding("O3", "invalid", "/deadline", "deadline must be later than created_at"))
278
+
279
+ if "output_schema" in order:
280
+ try:
281
+ _compile_user_schema(order["output_schema"])
282
+ except SchemaError as e:
283
+ out.append(Finding("O4", "invalid", "/output_schema", f"not a valid JSON Schema: {e.message}"))
284
+ return out
285
+
286
+
287
+ _MISSING = object()
288
+
289
+
290
+ def validate_report(report: Any, order: Any) -> List[Finding]:
291
+ """Runs report checks R1–R12 against the order it answers. The order is assumed valid."""
292
+ report, order = _plain(report), _plain(order)
293
+ shape = _schema_findings("R1", _report_shape.iter_errors(report))
294
+ if shape:
295
+ return shape
296
+ out: List[Finding] = []
297
+
298
+ def add(rule: str, kind: FindingKind, path: str, message: str) -> None:
299
+ out.append(Finding(rule, kind, path, message))
300
+
301
+ if report["order_id"] != order["id"]:
302
+ add("R2", "invalid", "/order_id", f'does not match order id "{order["id"]}"')
303
+
304
+ criterion_ids = {c["id"] for c in order["criteria"]}
305
+ for i, e in enumerate(report["evidence"]):
306
+ if e["criterion"] not in criterion_ids:
307
+ add("R3", "invalid", f"/evidence/{i}/criterion", f'unknown criterion "{e["criterion"]}"')
308
+
309
+ if report["status"] == "done":
310
+ proven = {e["criterion"] for e in report["evidence"]}
311
+ for c in order["criteria"]:
312
+ if c["id"] not in proven:
313
+ add("R4", "invalid", "/evidence", f'no evidence for criterion "{c["id"]}"')
314
+
315
+ for i, t in enumerate(report["tools_used"]):
316
+ if not tool_allowed(t, order["tools"]):
317
+ add("R5", "invalid", f"/tools_used/{i}", f'tool "{t}" is not allowed by this order')
318
+
319
+ for unit in UNITS:
320
+ limit = order["budget"].get(unit)
321
+ if limit is None:
322
+ continue
323
+ spent = report["cost"].get(unit)
324
+ if spent is None:
325
+ add("R6", "invalid", "/cost", f'cost must report "{unit}" because the budget sets it')
326
+ elif spent > limit:
327
+ add("R7", "limit", f"/cost/{unit}", f"spent {_num(spent)} {unit}, budget is {_num(limit)}")
328
+
329
+ if _time(report["finished_at"]) > _time(order["deadline"]):
330
+ add("R8", "limit", "/finished_at", "finished after the deadline")
331
+ if report["status"] == "blocked" and not report.get("questions"):
332
+ add("R9", "invalid", "/questions", "a blocked report must ask at least one question")
333
+ if report["status"] == "failed" and not report.get("error"):
334
+ add("R10", "invalid", "/error", "a failed report must say what went wrong")
335
+
336
+ if report["status"] == "done" and "output_schema" in order:
337
+ check = _compile_user_schema(order["output_schema"])
338
+ # A missing output fails any schema that constrains its type, as `undefined` does in JavaScript.
339
+ output = report["result"].get("output", _MISSING)
340
+ out.extend(_schema_findings("R11", check.iter_errors(output), "/result/output"))
341
+
342
+ if "started_at" in report and _time(report["started_at"]) > _time(report["finished_at"]):
343
+ add("R12", "invalid", "/started_at", "started_at is after finished_at")
344
+ return out
345
+
346
+
347
+ def validate_child_order(child: Any, parent: Any) -> List[Finding]:
348
+ """Runs sub-order checks C1–C3: a child order may only narrow its parent's authority."""
349
+ child, parent = _plain(child), _plain(parent)
350
+ out: List[Finding] = []
351
+ for unit in UNITS:
352
+ limit = parent["budget"].get(unit)
353
+ if limit is None:
354
+ continue
355
+ asked = child["budget"].get(unit)
356
+ if asked is None:
357
+ out.append(Finding("C1", "invalid", "/budget", f'must set "{unit}" because the parent does'))
358
+ elif asked > limit:
359
+ out.append(Finding("C1", "invalid", f"/budget/{unit}", f"{_num(asked)} exceeds parent's {_num(limit)}"))
360
+ for i, p in enumerate(child["tools"]):
361
+ if not pattern_covered(p, parent["tools"]):
362
+ out.append(Finding("C2", "invalid", f"/tools/{i}", f'"{p}" is wider than the parent allows'))
363
+ if _time(child["deadline"]) > _time(parent["deadline"]):
364
+ out.append(Finding("C3", "invalid", "/deadline", "later than the parent's deadline"))
365
+ return out
366
+
367
+
368
+ def has_invalid(findings: Sequence[Finding]) -> bool:
369
+ """True when any finding rejects the document."""
370
+ return any(f.kind == "invalid" for f in findings)
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.5
2
+ Name: agent-work-layer
3
+ Version: 0.1.0
4
+ Summary: Work Orders and Work Reports for AI agents: Pydantic models and the spec's validation rules.
5
+ Project-URL: Homepage, https://github.com/probita-ai/agent-work-layer/tree/main/python#readme
6
+ Project-URL: Repository, https://github.com/probita-ai/agent-work-layer
7
+ Project-URL: Issues, https://github.com/probita-ai/agent-work-layer/issues
8
+ Author: Probita
9
+ License-Expression: Apache-2.0
10
+ Keywords: a2a,agents,ai,llm,mcp,multi-agent,orchestration,work-order
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Requires-Dist: jsonschema>=4.18
17
+ Requires-Dist: pydantic>=2.6
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest>=8; extra == 'test'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # agent-work-layer (Python)
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.
25
+
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
+
28
+ ```sh
29
+ pip install agent-work-layer
30
+ ```
31
+
32
+ Python 3.9 or newer. Depends on `jsonschema` and `pydantic` (v2).
33
+
34
+ ## Validate documents
35
+
36
+ Documents are plain JSON (dicts). Each `validate_*` function returns a list of findings; an empty list means valid.
37
+
38
+ ```python
39
+ import json
40
+ from agent_work_layer import validate_order, validate_report, has_invalid
41
+
42
+ # examples/ in the repository
43
+ order = json.load(open("examples/risk-summary.order.json"))
44
+ report = json.load(open("examples/bad.report.json"))
45
+
46
+ assert validate_order(order) == []
47
+
48
+ findings = validate_report(report, order)
49
+ for f in findings:
50
+ print(f.rule, f.kind, f.path, f.message)
51
+ # R4 invalid /evidence no evidence for criterion "c2"
52
+ # R5 invalid /tools_used/1 tool "web/browse" is not allowed by this order
53
+ # R7 limit /cost/usd spent 3.1 usd, budget is 2
54
+ # R6 invalid /cost cost must report "tool_calls" because the budget sets it
55
+ # R8 limit /finished_at finished after the deadline
56
+ # R11 invalid /result/output 'total_debt' is a required property
57
+ # R11 invalid /result/output/risk_factors ['Refinancing'] is too short
58
+
59
+ if has_invalid(findings):
60
+ ... # reject the report and send the findings back to the worker
61
+ ```
62
+
63
+ - **`invalid`** findings reject the document.
64
+ - **`limit`** findings (R7 over budget, R8 past the deadline) are accepted but recorded, and move the order to `expired`.
65
+
66
+ | Function | Rules |
67
+ |---|---|
68
+ | `validate_order(order)` | O1–O4 |
69
+ | `validate_report(report, order)` | R1–R12 |
70
+ | `validate_child_order(child, parent)` | C1–C3: a sub-order may only narrow its parent's budget, tools and deadline |
71
+ | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
72
+ | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
73
+
74
+ The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
75
+
76
+ ## Build documents with models
77
+
78
+ ```python
79
+ from datetime import datetime, timedelta, timezone
80
+ from agent_work_layer import Criterion, WorkOrder, validate_order
81
+
82
+ now = datetime.now(timezone.utc)
83
+ order = WorkOrder(
84
+ id="wo_42",
85
+ created_at=now,
86
+ from_="agent:manager", # "from" in JSON
87
+ to="agent:researcher",
88
+ goal="Summarize the risk factors in the 2025 annual report",
89
+ criteria=[Criterion(id="c1", text="Lists the three largest risk factors with quotes")],
90
+ budget={"usd": 2, "tool_calls": 20},
91
+ deadline=now + timedelta(hours=2),
92
+ tools=["filings/*"],
93
+ )
94
+
95
+ doc = order.to_dict() # JSON-ready, with "from" and RFC 3339 timestamps
96
+ assert validate_order(order) == [] # the validators accept models too
97
+ ```
98
+
99
+ `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.
100
+
101
+ ## Matches the TypeScript SDK
102
+
103
+ 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:
104
+
105
+ - **Timestamps** follow RFC 3339 with a time zone. Instants are compared to the millisecond, as JavaScript's `Date.parse` does.
106
+ - **Missing and unknown fields** are reported at their parent object, one finding per field.
107
+ - **Regular expressions** match as in JavaScript. For example, `$` does not match before a trailing newline.
108
+
109
+ The messages are worded differently, and schema findings (O1, R1, R11) can come in a different order. One known difference: for a caller's `output_schema` (R11) that uses `if`/`then`, `contains`, `propertyNames` or `dependentRequired`, the number of R11 findings can differ from the TypeScript SDK. Whether R11 fires is always the same.
110
+
111
+ ## Not here yet
112
+
113
+ The desk (lifecycle, permissions, storage) and the MCP server are in the TypeScript packages. This package covers the documents and the checks.
114
+
115
+ ## License
116
+
117
+ Apache-2.0
@@ -0,0 +1,9 @@
1
+ agent_work_layer/__init__.py,sha256=zdsLmRz1MywEYhoXzAsVc_7zsIjm30S4ZXKX1P8tqWg,1158
2
+ agent_work_layer/models.py,sha256=OF6eJg5CRHulf0Mtn1uasQa5yYMlQcm93FC-AI84kyk,5414
3
+ agent_work_layer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ agent_work_layer/validate.py,sha256=E_7WHba7cSiz6hCdJgAgcTSIEz-JyguGARdRaMstHcs,14580
5
+ agent_work_layer/schemas/work-order.schema.json,sha256=adHQCsk4gF7o5KcxsyClt0_Ug7tL6pLdjBvEI1jQMHM,3288
6
+ agent_work_layer/schemas/work-report.schema.json,sha256=uFRDyctV4aY9Q-j3iVovI3Dp0lrzP8WmLnsERNptCIw,3489
7
+ agent_work_layer-0.1.0.dist-info/METADATA,sha256=ocmX8K_CIY8tkqqnjXDSH_rKVb17-0uaIsqVWhWIiCM,5322
8
+ agent_work_layer-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ agent_work_layer-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any