agent-work-layer 0.3.0__tar.gz → 0.5.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.3.0
3
+ Version: 0.5.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
@@ -65,14 +65,16 @@ if has_invalid(findings):
65
65
 
66
66
  | Function | Rules |
67
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 |
68
+ | `validate_order(order)` | O1–O5 |
69
+ | `validate_report(report, order)` | R1–R12, R14–R16 |
70
+ | `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
71
  | `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
72
72
  | `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
73
73
  | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
74
74
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
75
75
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
76
+ | `order_spec_for(order)`, `report_spec_for(report)` | The lowest version that has every field a document uses; the models' default `spec` |
77
+ | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
76
78
 
77
79
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
78
80
 
@@ -44,14 +44,16 @@ if has_invalid(findings):
44
44
 
45
45
  | Function | Rules |
46
46
  |---|---|
47
- | `validate_order(order)` | O1–O4 |
48
- | `validate_report(report, order)` | R1–R12 |
49
- | `validate_child_order(child, parent)` | C1–C3: a sub-order may only narrow its parent's budget, tools and deadline |
47
+ | `validate_order(order)` | O1–O5 |
48
+ | `validate_report(report, order)` | R1–R12, R14–R16 |
49
+ | `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
50
  | `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
51
51
  | `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
52
52
  | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
53
53
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
54
54
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
55
+ | `order_spec_for(order)`, `report_spec_for(report)` | The lowest version that has every field a document uses; the models' default `spec` |
56
+ | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
55
57
 
56
58
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
57
59
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agent-work-layer"
7
- version = "0.3.0"
7
+ version = "0.5.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"
@@ -9,6 +9,7 @@ from .models import (
9
9
  ContextRef,
10
10
  Criterion,
11
11
  Decision,
12
+ Effect,
12
13
  Evidence,
13
14
  Handoff,
14
15
  WorkOrder,
@@ -22,6 +23,9 @@ from .validate import (
22
23
  REPORT_SPECS,
23
24
  UNITS,
24
25
  Finding,
26
+ effect_references,
27
+ order_spec_for,
28
+ report_spec_for,
25
29
  has_invalid,
26
30
  held_by_sub_orders,
27
31
  is_work_order,
@@ -37,13 +41,13 @@ from .validate import (
37
41
  work_report_schema,
38
42
  )
39
43
 
40
- __version__ = "0.3.0"
44
+ __version__ = "0.5.0"
41
45
 
42
46
  __all__ = [
43
- "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Evidence", "Handoff",
47
+ "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Effect", "Evidence", "Handoff",
44
48
  "WorkOrder", "WorkReport", "WorkResult",
45
49
  "ORDER_SPEC", "ORDER_SPECS", "REPORT_SPEC", "REPORT_SPECS", "UNITS", "Finding",
46
- "has_invalid", "held_by_sub_orders", "is_work_order", "is_work_report", "pattern_covered", "tool_allowed",
50
+ "effect_references", "order_spec_for", "report_spec_for", "has_invalid", "held_by_sub_orders", "is_work_order", "is_work_report", "pattern_covered", "tool_allowed",
47
51
  "validate_child_budgets", "validate_child_order", "validate_order", "validate_own_cost", "validate_report",
48
52
  "work_order_schema", "work_report_schema",
49
53
  "__version__",
@@ -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)
@@ -100,7 +105,7 @@ class Handoff(_Part):
100
105
 
101
106
 
102
107
  class WorkOrder(_Document):
103
- spec: Literal["awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3"] = ORDER_SPEC
108
+ spec: Literal["awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3", "awl/work-order@0.4"] = ORDER_SPEC
104
109
  id: Annotated[str, Field(min_length=1, max_length=128)]
105
110
  created_at: Timestamp
106
111
  from_: AgentRef = Field(alias="from")
@@ -111,6 +116,8 @@ class WorkOrder(_Document):
111
116
  deadline: Timestamp
112
117
  #: Tool patterns: ``server/tool``, ``server/*`` or ``*``.
113
118
  tools: List[Annotated[str, Field(pattern=r"^(\*|[A-Za-z0-9_.-]+/(\*|[A-Za-z0-9_.-]+))$")]]
119
+ #: Tools whose calls are held back until the report is approved (SPEC.md §4.6). Covered by ``tools``.
120
+ staged: Optional[List[Annotated[str, Field(pattern=r"^(\*|[A-Za-z0-9_.-]+/(\*|[A-Za-z0-9_.-]+))$")]]] = None
114
121
  escalate_to: Optional[AgentRef] = None
115
122
  inputs: Optional[Dict[str, Any]] = None
116
123
  context: Optional[List[ContextRef]] = None
@@ -121,6 +128,9 @@ class WorkOrder(_Document):
121
128
  continues: Optional[Text] = None
122
129
  metadata: Optional[Dict[str, Any]] = None
123
130
 
131
+ def _lowest_spec(self) -> str:
132
+ return order_spec_for(vars(self))
133
+
124
134
  @model_validator(mode="after")
125
135
  def _budget_not_empty(self) -> "WorkOrder":
126
136
  if not self.budget.model_fields_set:
@@ -141,6 +151,17 @@ class Artifact(_Part):
141
151
  note: Optional[str] = None
142
152
 
143
153
 
154
+ class Effect(_Part):
155
+ """A staged call that runs only if the report is approved (SPEC.md §4.6)."""
156
+
157
+ #: The call's name, ``server/tool#n``, as the gateway gave it.
158
+ ref: Text
159
+ tool: Annotated[str, Field(pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")]
160
+ arguments: Dict[str, Any]
161
+ #: The worker's claim that the effect can be undone. Not checked.
162
+ reversible: Optional[bool] = None
163
+
164
+
144
165
  class WorkResult(_Part):
145
166
  summary: str
146
167
  output: Any = None
@@ -148,7 +169,7 @@ class WorkResult(_Part):
148
169
 
149
170
 
150
171
  class WorkReport(_Document):
151
- spec: Literal["awl/work-report@0.1", "awl/work-report@0.2"] = REPORT_SPEC
172
+ spec: Literal["awl/work-report@0.1", "awl/work-report@0.2", "awl/work-report@0.3"] = REPORT_SPEC
152
173
  order_id: Text
153
174
  from_: AgentRef = Field(alias="from")
154
175
  status: Literal["done", "blocked", "failed"]
@@ -158,9 +179,14 @@ class WorkReport(_Document):
158
179
  finished_at: Timestamp
159
180
  #: Exact tool names, ``server/tool``.
160
181
  tools_used: List[Annotated[str, Field(pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")]]
182
+ #: Staged calls to run on approval, in order (SPEC.md §4.6).
183
+ effects: Optional[List[Effect]] = None
161
184
  started_at: Optional[Timestamp] = None
162
185
  attempt: Optional[Annotated[int, Field(ge=1)]] = None
163
186
  questions: Optional[List[Text]] = None
164
187
  error: Optional[Text] = None
165
188
  handoff: Optional[Handoff] = None
166
189
  metadata: Optional[Dict[str, Any]] = None
190
+
191
+ def _lowest_spec(self) -> str:
192
+ return report_spec_for(vars(self))
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://awl.dev/schemas/work-order-0.3.json",
4
- "title": "AWL Work Order v0.3",
3
+ "$id": "https://awl.dev/schemas/work-order-0.4.json",
4
+ "title": "AWL Work Order v0.4",
5
5
  "type": "object",
6
6
  "required": ["spec", "id", "created_at", "from", "to", "goal", "criteria", "budget", "deadline", "tools"],
7
7
  "properties": {
8
- "spec": { "enum": ["awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3"] },
8
+ "spec": { "enum": ["awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3", "awl/work-order@0.4"] },
9
9
  "id": { "type": "string", "minLength": 1, "maxLength": 128 },
10
10
  "created_at": { "type": "string", "format": "date-time" },
11
11
  "from": { "$ref": "#/$defs/agentRef" },
@@ -27,6 +27,7 @@
27
27
  "budget": { "$ref": "#/$defs/amounts", "minProperties": 1 },
28
28
  "deadline": { "type": "string", "format": "date-time" },
29
29
  "tools": { "type": "array", "items": { "$ref": "#/$defs/toolPattern" } },
30
+ "staged": { "type": "array", "items": { "$ref": "#/$defs/toolPattern" } },
30
31
  "escalate_to": { "$ref": "#/$defs/agentRef" },
31
32
  "inputs": { "type": "object" },
32
33
  "context": {
@@ -1,11 +1,11 @@
1
1
  {
2
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",
3
+ "$id": "https://awl.dev/schemas/work-report-0.3.json",
4
+ "title": "AWL Work Report v0.3",
5
5
  "type": "object",
6
6
  "required": ["spec", "order_id", "from", "status", "result", "evidence", "cost", "finished_at", "tools_used"],
7
7
  "properties": {
8
- "spec": { "enum": ["awl/work-report@0.1", "awl/work-report@0.2"] },
8
+ "spec": { "enum": ["awl/work-report@0.1", "awl/work-report@0.2", "awl/work-report@0.3"] },
9
9
  "order_id": { "type": "string", "minLength": 1 },
10
10
  "from": { "type": "string", "minLength": 1, "maxLength": 512 },
11
11
  "status": { "enum": ["done", "blocked", "failed"] },
@@ -58,6 +58,20 @@
58
58
  "started_at": { "type": "string", "format": "date-time" },
59
59
  "finished_at": { "type": "string", "format": "date-time" },
60
60
  "tools_used": { "type": "array", "items": { "type": "string", "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$" } },
61
+ "effects": {
62
+ "type": "array",
63
+ "items": {
64
+ "type": "object",
65
+ "required": ["ref", "tool", "arguments"],
66
+ "properties": {
67
+ "ref": { "type": "string", "minLength": 1 },
68
+ "tool": { "type": "string", "pattern": "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$" },
69
+ "arguments": { "type": "object" },
70
+ "reversible": { "type": "boolean" }
71
+ },
72
+ "additionalProperties": false
73
+ }
74
+ },
61
75
  "attempt": { "type": "integer", "minimum": 1 },
62
76
  "questions": { "type": "array", "items": { "type": "string", "minLength": 1 } },
63
77
  "error": { "type": "string", "minLength": 1 },
@@ -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
- ORDER_SPEC = "awl/work-order@0.3"
22
- REPORT_SPEC = "awl/work-report@0.2"
21
+ #: The newest spec version this package reads. New documents get the lowest that fits: see :func:`order_spec_for`.
22
+ ORDER_SPEC = "awl/work-order@0.4"
23
+ REPORT_SPEC = "awl/work-report@0.3"
23
24
  #: Every spec version this package reads (SPEC.md §11).
24
- ORDER_SPECS = ("awl/work-order@0.1", "awl/work-order@0.2", ORDER_SPEC)
25
- REPORT_SPECS = ("awl/work-report@0.1", REPORT_SPEC)
25
+ ORDER_SPECS = ("awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3", ORDER_SPEC)
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
 
@@ -249,6 +271,47 @@ def pattern_covered(child: str, parent: Sequence[str]) -> bool:
249
271
  return tool_allowed(child, parent)
250
272
 
251
273
 
274
+ def _patterns_overlap(a: str, b: str) -> bool:
275
+ """Can some tool match both patterns?"""
276
+ if a == "*" or b == "*" or a == b:
277
+ return True
278
+ server_a, _, tool_a = a.partition("/")
279
+ server_b, _, tool_b = b.partition("/")
280
+ return server_a == server_b and "*" in (tool_a, tool_b)
281
+
282
+
283
+ def _is_reference(value: Any) -> bool:
284
+ """An object whose members are ``$ref`` (a string) and, optionally, ``pointer`` (a string)."""
285
+ return (
286
+ isinstance(value, dict)
287
+ and isinstance(value.get("$ref"), str)
288
+ and isinstance(value.get("pointer", ""), str)
289
+ and all(k in ("$ref", "pointer") for k in value)
290
+ )
291
+
292
+
293
+ def effect_references(arguments: Any) -> List[Dict[str, str]]:
294
+ """Every reference to an earlier effect's result in an effect's arguments (SPEC.md §4.6), in document order.
295
+
296
+ Each is ``{"ref", "pointer", "path"}``: the earlier effect, a JSON Pointer into its result, and a
297
+ JSON Pointer to the reference within the arguments.
298
+ """
299
+ out: List[Dict[str, str]] = []
300
+
301
+ def walk(value: Any, path: str) -> None:
302
+ if _is_reference(value):
303
+ out.append({"ref": value["$ref"], "pointer": value.get("pointer", ""), "path": path})
304
+ elif isinstance(value, list):
305
+ for i, v in enumerate(value):
306
+ walk(v, f"{path}/{i}")
307
+ elif isinstance(value, dict):
308
+ for k, v in value.items():
309
+ walk(v, path + _pointer([k]))
310
+
311
+ walk(arguments, "")
312
+ return out
313
+
314
+
252
315
  def is_work_order(value: Any) -> bool:
253
316
  """Structurally a Work Order (rule O1 only)."""
254
317
  return _order_shape.is_valid(_plain(value))
@@ -260,7 +323,7 @@ def is_work_report(value: Any) -> bool:
260
323
 
261
324
 
262
325
  def validate_order(order: Any) -> List[Finding]:
263
- """Runs order checks O1–O4. Returns an empty list when the order is valid."""
326
+ """Runs order checks O1–O5. Returns an empty list when the order is valid."""
264
327
  order = _plain(order)
265
328
  shape = _schema_findings("O1", _order_shape.iter_errors(order))
266
329
  if shape:
@@ -281,14 +344,19 @@ def validate_order(order: Any) -> List[Finding]:
281
344
  _compile_user_schema(order["output_schema"])
282
345
  except SchemaError as e:
283
346
  out.append(Finding("O4", "invalid", "/output_schema", f"not a valid JSON Schema: {e.message}"))
347
+
348
+ for i, p in enumerate(order.get("staged", [])):
349
+ if not pattern_covered(p, order["tools"]):
350
+ out.append(Finding("O5", "invalid", f"/staged/{i}", f'staged "{p}" is not covered by the order\'s tools'))
284
351
  return out
285
352
 
286
353
 
287
354
  _MISSING = object()
355
+ _CALL_NUMBER = re.compile(r"^[1-9][0-9]*\Z", re.ASCII)
288
356
 
289
357
 
290
358
  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."""
359
+ """Runs report checks R1–R12 and R14–R16 against the order it answers. The order is assumed valid."""
292
360
  report, order = _plain(report), _plain(order)
293
361
  shape = _schema_findings("R1", _report_shape.iter_errors(report))
294
362
  if shape:
@@ -341,11 +409,29 @@ def validate_report(report: Any, order: Any) -> List[Finding]:
341
409
 
342
410
  if "started_at" in report and _time(report["started_at"]) > _time(report["finished_at"]):
343
411
  add("R12", "invalid", "/started_at", "started_at is after finished_at")
412
+
413
+ refs = set()
414
+ for i, e in enumerate(report.get("effects", [])):
415
+ if not tool_allowed(e["tool"], order.get("staged", [])):
416
+ add("R14", "invalid", f"/effects/{i}/tool", f'tool "{e["tool"]}" is not staged by this order')
417
+ n = e["ref"][len(e["tool"]) + 1 :]
418
+ if not e["ref"].startswith(e["tool"] + "#") or not _CALL_NUMBER.match(n):
419
+ add("R15", "invalid", f"/effects/{i}/ref", f'ref "{e["ref"]}" is not "{e["tool"]}#<n>"')
420
+ elif e["ref"] in refs:
421
+ add("R15", "invalid", f"/effects/{i}/ref", f'ref "{e["ref"]}" appears twice')
422
+ for r in effect_references(e["arguments"]):
423
+ path = f"/effects/{i}/arguments{r['path']}"
424
+ if r["ref"] not in refs:
425
+ add("R16", "invalid", path, f'"{r["ref"]}" is not an effect listed before this one')
426
+ elif r["pointer"] != "" and not r["pointer"].startswith("/"):
427
+ add("R16", "invalid", path, f'"{r["pointer"]}" is not a JSON Pointer')
428
+ refs.add(e["ref"])
344
429
  return out
345
430
 
346
431
 
347
432
  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."""
433
+ """Runs sub-order checks C1–C3 and C5: a child order may only narrow its parent's authority, and may not
434
+ call the tools its parent stages, since its effects would run when its own report is approved."""
349
435
  child, parent = _plain(child), _plain(parent)
350
436
  out: List[Finding] = []
351
437
  for unit in UNITS:
@@ -362,6 +448,10 @@ def validate_child_order(child: Any, parent: Any) -> List[Finding]:
362
448
  out.append(Finding("C2", "invalid", f"/tools/{i}", f'"{p}" is wider than the parent allows'))
363
449
  if _time(child["deadline"]) > _time(parent["deadline"]):
364
450
  out.append(Finding("C3", "invalid", "/deadline", "later than the parent's deadline"))
451
+ for i, p in enumerate(child["tools"]):
452
+ staged = next((s for s in parent.get("staged", []) if _patterns_overlap(p, s)), None)
453
+ if staged is not None:
454
+ out.append(Finding("C5", "invalid", f"/tools/{i}", f'"{p}" allows "{staged}", which the parent stages'))
365
455
  return out
366
456
 
367
457