-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreadme_quickstart.py
More file actions
79 lines (63 loc) · 2.31 KB
/
Copy pathreadme_quickstart.py
File metadata and controls
79 lines (63 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""readme_quickstart.py — runnable mirror of the README "Quickstart".
Kept in step with the quickstart in ``README.md`` so CI catches regressions in
the first code a new user runs (issue #83). ``make example`` and the CI
"Examples" step execute this file; the final ``assert`` fails the build if
handle expansion ever stops returning the documented result.
Run with: ``python examples/readme_quickstart.py``
"""
from __future__ import annotations
import asyncio
import os
os.environ.setdefault("WEAVER_KERNEL_SECRET", "readme-quickstart-secret-not-for-prod")
from weaver_kernel import (
Capability,
CapabilityRegistry,
InMemoryDriver,
Kernel,
Principal,
SafetyClass,
StaticRouter,
)
from weaver_kernel.models import CapabilityRequest
# 1. Register a capability
registry = CapabilityRegistry()
registry.register(
Capability(
capability_id="tasks.list",
name="List Tasks",
description="List all tasks",
safety_class=SafetyClass.READ,
tags=["tasks", "list"],
)
)
# 2. Wire up a driver
driver = InMemoryDriver()
driver.register_handler("tasks.list", lambda ctx: [{"id": 1, "title": "Buy milk"}])
# 3. Build the kernel
kernel = Kernel(registry=registry, router=StaticRouter(routes={"tasks.list": ["memory"]}))
kernel.register_driver(driver)
async def main() -> None:
principal = Principal(principal_id="alice", roles=["reader"])
# 4. Discover → grant → invoke → expand → explain
token = kernel.get_token(
CapabilityRequest(capability_id="tasks.list", goal="list tasks"),
principal,
justification="",
)
frame = await kernel.invoke(token, principal=principal, args={})
print(frame.facts)
print(frame.handle)
# `principal` is required: the handle is bound to the granting principal,
# so an omitted principal raises HandleConstraintViolation (#83).
expanded = kernel.expand(
frame.handle, query={"limit": 1, "fields": ["title"]}, principal=principal
)
print(expanded.table_preview)
assert expanded.table_preview == [{"title": "Buy milk"}], (
f"README quickstart regression: expected [{{'title': 'Buy milk'}}], "
f"got {expanded.table_preview!r}"
)
trace = kernel.explain(frame.action_id)
print(trace.driver_id)
if __name__ == "__main__":
asyncio.run(main())