agent-work-layer 0.4.0__tar.gz → 0.6.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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agent-work-layer
3
- Version: 0.4.0
3
+ Version: 0.6.0
4
4
  Summary: Work Orders and Work Reports for AI agents: Pydantic models and the spec's validation rules.
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
@@ -66,13 +66,15 @@ 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 |
73
74
  | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
74
75
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
75
76
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
77
+ | `order_spec_for(order)`, `report_spec_for(report)` | The lowest version that has every field a document uses; the models' default `spec` |
76
78
  | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
77
79
 
78
80
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
@@ -45,13 +45,15 @@ 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 |
52
53
  | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
53
54
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
54
55
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
56
+ | `order_spec_for(order)`, `report_spec_for(report)` | The lowest version that has every field a document uses; the models' default `spec` |
55
57
  | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
56
58
 
57
59
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agent-work-layer"
7
- version = "0.4.0"
7
+ version = "0.6.0"
8
8
  description = "Work Orders and Work Reports for AI agents: Pydantic models and the spec's validation rules."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -24,6 +24,8 @@ from .validate import (
24
24
  UNITS,
25
25
  Finding,
26
26
  effect_references,
27
+ order_spec_for,
28
+ report_spec_for,
27
29
  has_invalid,
28
30
  held_by_sub_orders,
29
31
  is_work_order,
@@ -35,18 +37,19 @@ from .validate import (
35
37
  validate_order,
36
38
  validate_own_cost,
37
39
  validate_report,
40
+ validate_usage,
38
41
  work_order_schema,
39
42
  work_report_schema,
40
43
  )
41
44
 
42
- __version__ = "0.4.0"
45
+ __version__ = "0.6.0"
43
46
 
44
47
  __all__ = [
45
48
  "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Effect", "Evidence", "Handoff",
46
49
  "WorkOrder", "WorkReport", "WorkResult",
47
50
  "ORDER_SPEC", "ORDER_SPECS", "REPORT_SPEC", "REPORT_SPECS", "UNITS", "Finding",
48
- "effect_references", "has_invalid", "held_by_sub_orders", "is_work_order", "is_work_report", "pattern_covered", "tool_allowed",
49
- "validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report",
51
+ "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
+ "validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report", "validate_usage",
50
53
  "work_order_schema", "work_report_schema",
51
54
  "__version__",
52
55
  ]
@@ -13,7 +13,7 @@ from typing import Annotated, Any, Dict, List, Literal, Optional
13
13
 
14
14
  from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, model_validator
15
15
 
16
- from .validate import ORDER_SPEC, REPORT_SPEC
16
+ from .validate import ORDER_SPEC, REPORT_SPEC, order_spec_for, report_spec_for
17
17
 
18
18
  AgentRef = Annotated[str, Field(min_length=1, max_length=512)]
19
19
 
@@ -45,10 +45,15 @@ class _Document(_Part):
45
45
  unknown = [k for k in (self.model_extra or {}) if not k.startswith("x-")]
46
46
  if unknown:
47
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.
48
+ # Left unset, `spec` is the lowest version that has every field used, and always appears in to_dict().
49
+ if "spec" not in self.model_fields_set:
50
+ self.spec = self._lowest_spec()
49
51
  self.model_fields_set.add("spec")
50
52
  return self
51
53
 
54
+ def _lowest_spec(self) -> str:
55
+ raise NotImplementedError
56
+
52
57
  def to_dict(self) -> Dict[str, Any]:
53
58
  """The document as JSON-ready data, with ``from`` spelled as in the spec."""
54
59
  return self.model_dump(mode="json", by_alias=True, exclude_unset=True, exclude_none=True)
@@ -123,6 +128,9 @@ class WorkOrder(_Document):
123
128
  continues: Optional[Text] = None
124
129
  metadata: Optional[Dict[str, Any]] = None
125
130
 
131
+ def _lowest_spec(self) -> str:
132
+ return order_spec_for(vars(self))
133
+
126
134
  @model_validator(mode="after")
127
135
  def _budget_not_empty(self) -> "WorkOrder":
128
136
  if not self.budget.model_fields_set:
@@ -179,3 +187,6 @@ class WorkReport(_Document):
179
187
  error: Optional[Text] = None
180
188
  handoff: Optional[Handoff] = None
181
189
  metadata: Optional[Dict[str, Any]] = None
190
+
191
+ def _lowest_spec(self) -> str:
192
+ return report_spec_for(vars(self))
@@ -18,11 +18,33 @@ from jsonschema import Draft202012Validator, FormatChecker, ValidationError
18
18
  from jsonschema.exceptions import SchemaError
19
19
  from jsonschema.validators import extend
20
20
 
21
+ #: The newest spec version this package reads. New documents get the lowest that fits: see :func:`order_spec_for`.
21
22
  ORDER_SPEC = "awl/work-order@0.4"
22
23
  REPORT_SPEC = "awl/work-report@0.3"
23
24
  #: Every spec version this package reads (SPEC.md §11).
24
25
  ORDER_SPECS = ("awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3", ORDER_SPEC)
25
26
  REPORT_SPECS = ("awl/work-report@0.1", "awl/work-report@0.2", REPORT_SPEC)
27
+
28
+
29
+ def order_spec_for(order: Mapping[str, Any]) -> str:
30
+ """The lowest Work Order version that defines every field ``order`` uses (SPEC.md §11).
31
+
32
+ Readers that predate a field then still accept orders that don't use it.
33
+ """
34
+ if order.get("staged") is not None:
35
+ return ORDER_SPECS[3]
36
+ if order.get("continues") is not None:
37
+ return ORDER_SPECS[2]
38
+ return ORDER_SPECS[1] if order.get("handoff") is not None else ORDER_SPECS[0]
39
+
40
+
41
+ def report_spec_for(report: Mapping[str, Any]) -> str:
42
+ """The lowest Work Report version that defines every field ``report`` uses (SPEC.md §11)."""
43
+ if report.get("effects") is not None:
44
+ return REPORT_SPECS[2]
45
+ return REPORT_SPECS[1] if report.get("handoff") is not None else REPORT_SPECS[0]
46
+
47
+
26
48
  #: Budget and cost units (SPEC.md §4.2).
27
49
  UNITS = ("usd", "tokens", "tool_calls", "seconds")
28
50
 
@@ -333,8 +355,9 @@ _MISSING = object()
333
355
  _CALL_NUMBER = re.compile(r"^[1-9][0-9]*\Z", re.ASCII)
334
356
 
335
357
 
336
- def validate_report(report: Any, order: Any) -> List[Finding]:
337
- """Runs report checks R1–R12 and R14–R16 against the order it answers. The order is assumed valid."""
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."""
338
361
  report, order = _plain(report), _plain(order)
339
362
  shape = _schema_findings("R1", _report_shape.iter_errors(report))
340
363
  if shape:
@@ -404,6 +427,34 @@ def validate_report(report: Any, order: Any) -> List[Finding]:
404
427
  elif r["pointer"] != "" and not r["pointer"].startswith("/"):
405
428
  add("R16", "invalid", path, f'"{r["pointer"]}" is not a JSON Pointer')
406
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}"'))
407
458
  return out
408
459
 
409
460