agent-work-layer 0.2.0__tar.gz → 0.4.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.2.0
3
+ Version: 0.4.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,11 +65,15 @@ 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
+ | `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
72
+ | `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
73
+ | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
71
74
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
72
75
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
76
+ | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
73
77
 
74
78
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
75
79
 
@@ -44,11 +44,15 @@ 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
+ | `validate_own_cost(report, order, sub_orders)` | R13: an order's own cost, plus what its sub-orders hold, stays within its budget |
51
+ | `held_by_sub_orders(sub_orders)` | The budget an order's sub-orders hold |
52
+ | `validate_child_budgets(child, parent, siblings)` | C4: a parent's sub-orders together stay within its budget. `siblings` are `{"order": ..., "state": ...}` |
50
53
  | `is_work_order(value)`, `is_work_report(value)` | Structure only (O1, R1) |
51
54
  | `tool_allowed(tool, patterns)`, `pattern_covered(child, parents)` | Tool pattern matching (`server/tool`, `server/*`, `*`) |
55
+ | `effect_references(arguments)` | References to earlier effects' results in an effect's arguments, each `{"ref", "pointer", "path"}` |
52
56
 
53
57
  The JSON Schemas are available as `work_order_schema` and `work_report_schema`.
54
58
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agent-work-layer"
7
- version = "0.2.0"
7
+ version = "0.4.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,25 +23,30 @@ from .validate import (
22
23
  REPORT_SPECS,
23
24
  UNITS,
24
25
  Finding,
26
+ effect_references,
25
27
  has_invalid,
28
+ held_by_sub_orders,
26
29
  is_work_order,
27
30
  is_work_report,
28
31
  pattern_covered,
29
32
  tool_allowed,
33
+ validate_child_budgets,
30
34
  validate_child_order,
31
35
  validate_order,
36
+ validate_own_cost,
32
37
  validate_report,
33
38
  work_order_schema,
34
39
  work_report_schema,
35
40
  )
36
41
 
37
- __version__ = "0.2.0"
42
+ __version__ = "0.4.0"
38
43
 
39
44
  __all__ = [
40
- "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Evidence", "Handoff",
45
+ "Amounts", "Artifact", "Attempt", "ContextRef", "Criterion", "Decision", "Effect", "Evidence", "Handoff",
41
46
  "WorkOrder", "WorkReport", "WorkResult",
42
47
  "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",
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",
50
+ "work_order_schema", "work_report_schema",
45
51
  "__version__",
46
52
  ]
@@ -100,7 +100,7 @@ class Handoff(_Part):
100
100
 
101
101
 
102
102
  class WorkOrder(_Document):
103
- spec: Literal["awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3"] = ORDER_SPEC
103
+ 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
104
  id: Annotated[str, Field(min_length=1, max_length=128)]
105
105
  created_at: Timestamp
106
106
  from_: AgentRef = Field(alias="from")
@@ -111,6 +111,8 @@ class WorkOrder(_Document):
111
111
  deadline: Timestamp
112
112
  #: Tool patterns: ``server/tool``, ``server/*`` or ``*``.
113
113
  tools: List[Annotated[str, Field(pattern=r"^(\*|[A-Za-z0-9_.-]+/(\*|[A-Za-z0-9_.-]+))$")]]
114
+ #: Tools whose calls are held back until the report is approved (SPEC.md §4.6). Covered by ``tools``.
115
+ staged: Optional[List[Annotated[str, Field(pattern=r"^(\*|[A-Za-z0-9_.-]+/(\*|[A-Za-z0-9_.-]+))$")]]] = None
114
116
  escalate_to: Optional[AgentRef] = None
115
117
  inputs: Optional[Dict[str, Any]] = None
116
118
  context: Optional[List[ContextRef]] = None
@@ -141,6 +143,17 @@ class Artifact(_Part):
141
143
  note: Optional[str] = None
142
144
 
143
145
 
146
+ class Effect(_Part):
147
+ """A staged call that runs only if the report is approved (SPEC.md §4.6)."""
148
+
149
+ #: The call's name, ``server/tool#n``, as the gateway gave it.
150
+ ref: Text
151
+ tool: Annotated[str, Field(pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")]
152
+ arguments: Dict[str, Any]
153
+ #: The worker's claim that the effect can be undone. Not checked.
154
+ reversible: Optional[bool] = None
155
+
156
+
144
157
  class WorkResult(_Part):
145
158
  summary: str
146
159
  output: Any = None
@@ -148,7 +161,7 @@ class WorkResult(_Part):
148
161
 
149
162
 
150
163
  class WorkReport(_Document):
151
- spec: Literal["awl/work-report@0.1", "awl/work-report@0.2"] = REPORT_SPEC
164
+ spec: Literal["awl/work-report@0.1", "awl/work-report@0.2", "awl/work-report@0.3"] = REPORT_SPEC
152
165
  order_id: Text
153
166
  from_: AgentRef = Field(alias="from")
154
167
  status: Literal["done", "blocked", "failed"]
@@ -158,6 +171,8 @@ class WorkReport(_Document):
158
171
  finished_at: Timestamp
159
172
  #: Exact tool names, ``server/tool``.
160
173
  tools_used: List[Annotated[str, Field(pattern=r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")]]
174
+ #: Staged calls to run on approval, in order (SPEC.md §4.6).
175
+ effects: Optional[List[Effect]] = None
161
176
  started_at: Optional[Timestamp] = None
162
177
  attempt: Optional[Annotated[int, Field(ge=1)]] = None
163
178
  questions: Optional[List[Text]] = None
@@ -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,11 @@ 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
+ ORDER_SPEC = "awl/work-order@0.4"
22
+ REPORT_SPEC = "awl/work-report@0.3"
23
23
  #: 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)
24
+ ORDER_SPECS = ("awl/work-order@0.1", "awl/work-order@0.2", "awl/work-order@0.3", ORDER_SPEC)
25
+ REPORT_SPECS = ("awl/work-report@0.1", "awl/work-report@0.2", REPORT_SPEC)
26
26
  #: Budget and cost units (SPEC.md §4.2).
27
27
  UNITS = ("usd", "tokens", "tool_calls", "seconds")
28
28
 
@@ -249,6 +249,47 @@ def pattern_covered(child: str, parent: Sequence[str]) -> bool:
249
249
  return tool_allowed(child, parent)
250
250
 
251
251
 
252
+ def _patterns_overlap(a: str, b: str) -> bool:
253
+ """Can some tool match both patterns?"""
254
+ if a == "*" or b == "*" or a == b:
255
+ return True
256
+ server_a, _, tool_a = a.partition("/")
257
+ server_b, _, tool_b = b.partition("/")
258
+ return server_a == server_b and "*" in (tool_a, tool_b)
259
+
260
+
261
+ def _is_reference(value: Any) -> bool:
262
+ """An object whose members are ``$ref`` (a string) and, optionally, ``pointer`` (a string)."""
263
+ return (
264
+ isinstance(value, dict)
265
+ and isinstance(value.get("$ref"), str)
266
+ and isinstance(value.get("pointer", ""), str)
267
+ and all(k in ("$ref", "pointer") for k in value)
268
+ )
269
+
270
+
271
+ def effect_references(arguments: Any) -> List[Dict[str, str]]:
272
+ """Every reference to an earlier effect's result in an effect's arguments (SPEC.md §4.6), in document order.
273
+
274
+ Each is ``{"ref", "pointer", "path"}``: the earlier effect, a JSON Pointer into its result, and a
275
+ JSON Pointer to the reference within the arguments.
276
+ """
277
+ out: List[Dict[str, str]] = []
278
+
279
+ def walk(value: Any, path: str) -> None:
280
+ if _is_reference(value):
281
+ out.append({"ref": value["$ref"], "pointer": value.get("pointer", ""), "path": path})
282
+ elif isinstance(value, list):
283
+ for i, v in enumerate(value):
284
+ walk(v, f"{path}/{i}")
285
+ elif isinstance(value, dict):
286
+ for k, v in value.items():
287
+ walk(v, path + _pointer([k]))
288
+
289
+ walk(arguments, "")
290
+ return out
291
+
292
+
252
293
  def is_work_order(value: Any) -> bool:
253
294
  """Structurally a Work Order (rule O1 only)."""
254
295
  return _order_shape.is_valid(_plain(value))
@@ -260,7 +301,7 @@ def is_work_report(value: Any) -> bool:
260
301
 
261
302
 
262
303
  def validate_order(order: Any) -> List[Finding]:
263
- """Runs order checks O1–O4. Returns an empty list when the order is valid."""
304
+ """Runs order checks O1–O5. Returns an empty list when the order is valid."""
264
305
  order = _plain(order)
265
306
  shape = _schema_findings("O1", _order_shape.iter_errors(order))
266
307
  if shape:
@@ -281,14 +322,19 @@ def validate_order(order: Any) -> List[Finding]:
281
322
  _compile_user_schema(order["output_schema"])
282
323
  except SchemaError as e:
283
324
  out.append(Finding("O4", "invalid", "/output_schema", f"not a valid JSON Schema: {e.message}"))
325
+
326
+ for i, p in enumerate(order.get("staged", [])):
327
+ if not pattern_covered(p, order["tools"]):
328
+ out.append(Finding("O5", "invalid", f"/staged/{i}", f'staged "{p}" is not covered by the order\'s tools'))
284
329
  return out
285
330
 
286
331
 
287
332
  _MISSING = object()
333
+ _CALL_NUMBER = re.compile(r"^[1-9][0-9]*\Z", re.ASCII)
288
334
 
289
335
 
290
336
  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."""
337
+ """Runs report checks R1–R12 and R14–R16 against the order it answers. The order is assumed valid."""
292
338
  report, order = _plain(report), _plain(order)
293
339
  shape = _schema_findings("R1", _report_shape.iter_errors(report))
294
340
  if shape:
@@ -341,11 +387,29 @@ def validate_report(report: Any, order: Any) -> List[Finding]:
341
387
 
342
388
  if "started_at" in report and _time(report["started_at"]) > _time(report["finished_at"]):
343
389
  add("R12", "invalid", "/started_at", "started_at is after finished_at")
390
+
391
+ refs = set()
392
+ for i, e in enumerate(report.get("effects", [])):
393
+ if not tool_allowed(e["tool"], order.get("staged", [])):
394
+ add("R14", "invalid", f"/effects/{i}/tool", f'tool "{e["tool"]}" is not staged by this order')
395
+ n = e["ref"][len(e["tool"]) + 1 :]
396
+ if not e["ref"].startswith(e["tool"] + "#") or not _CALL_NUMBER.match(n):
397
+ add("R15", "invalid", f"/effects/{i}/ref", f'ref "{e["ref"]}" is not "{e["tool"]}#<n>"')
398
+ elif e["ref"] in refs:
399
+ add("R15", "invalid", f"/effects/{i}/ref", f'ref "{e["ref"]}" appears twice')
400
+ for r in effect_references(e["arguments"]):
401
+ path = f"/effects/{i}/arguments{r['path']}"
402
+ if r["ref"] not in refs:
403
+ add("R16", "invalid", path, f'"{r["ref"]}" is not an effect listed before this one')
404
+ elif r["pointer"] != "" and not r["pointer"].startswith("/"):
405
+ add("R16", "invalid", path, f'"{r["pointer"]}" is not a JSON Pointer')
406
+ refs.add(e["ref"])
344
407
  return out
345
408
 
346
409
 
347
410
  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."""
411
+ """Runs sub-order checks C1–C3 and C5: a child order may only narrow its parent's authority, and may not
412
+ call the tools its parent stages, since its effects would run when its own report is approved."""
349
413
  child, parent = _plain(child), _plain(parent)
350
414
  out: List[Finding] = []
351
415
  for unit in UNITS:
@@ -362,6 +426,67 @@ def validate_child_order(child: Any, parent: Any) -> List[Finding]:
362
426
  out.append(Finding("C2", "invalid", f"/tools/{i}", f'"{p}" is wider than the parent allows'))
363
427
  if _time(child["deadline"]) > _time(parent["deadline"]):
364
428
  out.append(Finding("C3", "invalid", "/deadline", "later than the parent's deadline"))
429
+ for i, p in enumerate(child["tools"]):
430
+ staged = next((s for s in parent.get("staged", []) if _patterns_overlap(p, s)), None)
431
+ if staged is not None:
432
+ out.append(Finding("C5", "invalid", f"/tools/{i}", f'"{p}" allows "{staged}", which the parent stages'))
433
+ return out
434
+
435
+
436
+ #: Units whose sub-order budgets add up (C4, R13). ``seconds`` is wall-clock time, and sub-orders run side by side.
437
+ _SHARED_UNITS = ("usd", "tokens", "tool_calls")
438
+ #: Absorbs floating-point error in sums of money, so 0.1 + 0.2 fits a budget of 0.3.
439
+ _EPSILON = 1e-9
440
+
441
+
442
+ def held_by_sub_orders(sub_orders: Sequence[Mapping[str, Any]]) -> Dict[str, Any]:
443
+ """The budget an order's sub-orders hold (§8): their budgets added up, leaving out declined ones.
444
+
445
+ ``sub_orders`` are ``{"order": ..., "state": ...}``, as the desk stores them.
446
+ """
447
+ held: Dict[str, Any] = {}
448
+ for s in sub_orders:
449
+ if s["state"] == "declined":
450
+ continue
451
+ budget = _plain(s["order"])["budget"]
452
+ for unit in _SHARED_UNITS:
453
+ if unit in budget:
454
+ held[unit] = round(held.get(unit, 0) + budget[unit], 9)
455
+ return held
456
+
457
+
458
+ def validate_child_budgets(child: Any, parent: Any, siblings: Sequence[Mapping[str, Any]]) -> List[Finding]:
459
+ """Runs sub-order check C4: a parent's sub-orders, this one included, stay within its budget together.
460
+
461
+ ``siblings`` are the parent's existing sub-orders as ``{"order": ..., "state": ...}``; declined ones are not counted.
462
+ """
463
+ held = held_by_sub_orders([*siblings, {"order": child, "state": "offered"}])
464
+ parent = _plain(parent)
465
+ out: List[Finding] = []
466
+ for unit in _SHARED_UNITS:
467
+ limit = parent["budget"].get(unit)
468
+ total = held.get(unit, 0)
469
+ if limit is not None and total - limit > _EPSILON:
470
+ out.append(Finding("C4", "invalid", f"/budget/{unit}", f"sub-orders would total {_num(total)} {unit}, parent's budget is {_num(limit)}"))
471
+ return out
472
+
473
+
474
+ def validate_own_cost(report: Any, order: Any, sub_orders: Sequence[Mapping[str, Any]]) -> List[Finding]:
475
+ """Runs report check R13: the order's own cost, plus what its sub-orders hold, stays within its budget.
476
+
477
+ Units already over budget on their own are left to R7, and units missing from the cost to R6.
478
+ """
479
+ report, order = _plain(report), _plain(order)
480
+ held = held_by_sub_orders(sub_orders)
481
+ out: List[Finding] = []
482
+ for unit in _SHARED_UNITS:
483
+ limit = order["budget"].get(unit)
484
+ spent = report["cost"].get(unit)
485
+ hold = held.get(unit, 0)
486
+ if limit is None or spent is None or spent > limit or not hold:
487
+ continue
488
+ if spent + hold - limit > _EPSILON:
489
+ out.append(Finding("R13", "limit", f"/cost/{unit}", f"spent {_num(spent)} {unit} while sub-orders hold {_num(hold)}; budget is {_num(limit)}"))
365
490
  return out
366
491
 
367
492