aictrl-langgraph 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,18 @@
1
+ """Connect LangGraph workflows to AI Control Plane monitoring."""
2
+
3
+ from .client import ApplicationCredentials, MonitoringClient, MonitoringError, register_application
4
+ from .enforcement import Policy
5
+ from .graph import graph_metadata
6
+ from .monitor import LangGraphMonitor
7
+ from .policy import PolicyBlocked
8
+
9
+ __all__ = [
10
+ "ApplicationCredentials",
11
+ "LangGraphMonitor",
12
+ "MonitoringClient",
13
+ "MonitoringError",
14
+ "Policy",
15
+ "PolicyBlocked",
16
+ "graph_metadata",
17
+ "register_application",
18
+ ]
@@ -0,0 +1,135 @@
1
+ """LangGraph lifecycle observation with one sequence per graph invocation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import UTC, datetime
7
+ from threading import RLock
8
+ from typing import Any
9
+ from uuid import UUID, uuid4
10
+
11
+ from langgraph.callbacks import GraphCallbackHandler, GraphInterruptEvent
12
+ from langgraph.errors import GraphInterrupt
13
+
14
+ from .client import MonitoringError
15
+ from .delivery import Delivery
16
+ from .policy import PolicyBlocked
17
+
18
+
19
+ @dataclass
20
+ class _Run:
21
+ id: str = field(default_factory=lambda: uuid4().hex)
22
+ sequence: int = 0
23
+ paused: bool = False
24
+ nodes: dict[UUID, str] = field(default_factory=dict)
25
+
26
+
27
+ class MonitoringCallback(GraphCallbackHandler):
28
+ # Only a short lock and an in-memory enqueue run on the application thread.
29
+ run_inline = True
30
+ raise_error = False
31
+
32
+ def __init__(self, delivery: Delivery, digest: str, node_ids: set[str], max_runs: int) -> None:
33
+ self.delivery = delivery
34
+ self.digest = digest
35
+ self.node_ids = node_ids
36
+ self.max_runs = max_runs
37
+ self.lock = RLock()
38
+ self.runs: dict[UUID, _Run] = {}
39
+ self.parents: dict[UUID, UUID] = {}
40
+
41
+ def _emit(self, run: _Run, kind: str, node_id: str | None = None) -> None:
42
+ run.sequence += 1
43
+ self.delivery.submit(
44
+ {
45
+ "id": uuid4().hex,
46
+ "run_id": run.id,
47
+ "graph_digest": self.digest,
48
+ "sequence": run.sequence,
49
+ "type": kind,
50
+ "node_id": node_id,
51
+ "occurred_at": datetime.now(UTC).isoformat(),
52
+ }
53
+ )
54
+
55
+ def on_chain_start(
56
+ self,
57
+ serialized: dict[str, Any] | None,
58
+ inputs: Any,
59
+ *,
60
+ run_id: UUID,
61
+ parent_run_id: UUID | None = None,
62
+ tags: list[str] | None = None,
63
+ metadata: dict[str, Any] | None = None,
64
+ **kwargs: Any,
65
+ ) -> None:
66
+ with self.lock:
67
+ if self.delivery.closed or self.delivery.error:
68
+ return
69
+ node = (metadata or {}).get("langgraph_node")
70
+ if parent_run_id in self.runs and node in self.node_ids:
71
+ # Runnable calls inside a node have another parent and are ignored.
72
+ assert parent_run_id is not None
73
+ run = self.runs[parent_run_id]
74
+ run.nodes[run_id] = node
75
+ self.parents[run_id] = parent_run_id
76
+ self._emit(run, "node.started", node)
77
+ elif node is None:
78
+ if len(self.runs) >= self.max_runs:
79
+ self.delivery.fail(MonitoringError("Active monitoring run limit exceeded"))
80
+ return
81
+ run = self.runs[run_id] = _Run()
82
+ self._emit(run, "run.started")
83
+
84
+ def on_chain_end(self, outputs: Any, *, run_id: UUID, **kwargs: Any) -> None:
85
+ self._end(run_id, None)
86
+
87
+ def on_chain_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None:
88
+ self._end(run_id, error)
89
+
90
+ def _end(self, run_id: UUID, error: BaseException | None) -> None:
91
+ with self.lock:
92
+ parent = self.parents.pop(run_id, None)
93
+ if parent is not None and parent in self.runs:
94
+ run = self.runs[parent]
95
+ node = run.nodes.pop(run_id)
96
+ interrupted = isinstance(error, GraphInterrupt)
97
+ if interrupted:
98
+ run.paused = True
99
+ self._emit(
100
+ run,
101
+ "node.blocked"
102
+ if isinstance(error, PolicyBlocked)
103
+ else "node.paused"
104
+ if interrupted
105
+ else "node.failed"
106
+ if error
107
+ else "node.completed",
108
+ node,
109
+ )
110
+ elif run_id in self.runs:
111
+ run = self.runs.pop(run_id)
112
+ paused = isinstance(error, GraphInterrupt) or (error is None and run.paused)
113
+ for child, node in run.nodes.items():
114
+ self.parents.pop(child, None)
115
+ self._emit(run, "node.paused" if paused else "node.failed", node)
116
+ self._emit(
117
+ run,
118
+ "run.blocked"
119
+ if isinstance(error, PolicyBlocked)
120
+ else "run.paused"
121
+ if paused
122
+ else "run.failed"
123
+ if error
124
+ else "run.completed",
125
+ )
126
+
127
+ def on_interrupt(self, event: GraphInterruptEvent) -> None:
128
+ with self.lock:
129
+ if event.run_id is not None and event.run_id in self.runs:
130
+ self.runs[event.run_id].paused = True
131
+
132
+ def clear(self) -> None:
133
+ with self.lock:
134
+ self.runs.clear()
135
+ self.parents.clear()
@@ -0,0 +1,204 @@
1
+ """Application-scoped HTTP transport for the monitoring API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import random
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+ from urllib.parse import urlsplit
11
+
12
+ import httpx
13
+
14
+
15
+ class MonitoringError(RuntimeError):
16
+ """A safe diagnostic that never includes credentials or response bodies."""
17
+
18
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
19
+ super().__init__(message)
20
+ self.status_code = status_code
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class ApplicationCredentials:
25
+ application_id: str
26
+ api_key: str = field(repr=False)
27
+
28
+
29
+ def _url(base_url: str) -> str:
30
+ parts = urlsplit(base_url)
31
+ if (
32
+ parts.scheme not in {"http", "https"}
33
+ or not parts.hostname
34
+ or parts.username is not None
35
+ or parts.password is not None
36
+ or parts.query
37
+ or parts.fragment
38
+ ):
39
+ raise ValueError("base_url must be an HTTP(S) URL without credentials, query or fragment")
40
+ base = base_url.rstrip("/")
41
+ return base if base.endswith("/api/v1") else base + "/api/v1"
42
+
43
+
44
+ def _token(value: str) -> str:
45
+ if not value or len(value) > 1024 or not value.isascii() or any(c.isspace() for c in value):
46
+ raise ValueError("An API token must be nonempty ASCII without whitespace")
47
+ return value
48
+
49
+
50
+ class MonitoringClient:
51
+ """Thread-safe client. Retries are limited to idempotent SDK endpoints."""
52
+
53
+ def __init__(
54
+ self,
55
+ *,
56
+ base_url: str,
57
+ api_key: str,
58
+ timeout: float = 5.0,
59
+ max_retries: int = 2,
60
+ transport: httpx.BaseTransport | None = None,
61
+ ) -> None:
62
+ if not math.isfinite(timeout) or timeout <= 0:
63
+ raise ValueError("timeout must be positive and finite")
64
+ if not 0 <= max_retries <= 5:
65
+ raise ValueError("max_retries must be between 0 and 5")
66
+ self._http = httpx.Client(
67
+ base_url=_url(base_url) + "/",
68
+ headers={"Authorization": f"Bearer {_token(api_key)}"},
69
+ timeout=timeout,
70
+ follow_redirects=False,
71
+ transport=transport,
72
+ )
73
+ self._max_retries = max_retries
74
+
75
+ def _post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
76
+ return self._request("POST", path, body)
77
+
78
+ def _request(
79
+ self,
80
+ method: str,
81
+ path: str,
82
+ body: dict[str, Any] | None = None,
83
+ params: dict[str, str] | None = None,
84
+ ) -> dict[str, Any]:
85
+ error = MonitoringError("Monitoring request failed")
86
+ for attempt in range(self._max_retries + 1):
87
+ delay = min(0.1 * 2**attempt + random.uniform(0, 0.05), 2.0)
88
+ try:
89
+ response = self._http.request(method, path, json=body, params=params)
90
+ except httpx.RequestError:
91
+ error = MonitoringError("Monitoring service is unreachable")
92
+ else:
93
+ status = response.status_code
94
+ if 200 <= status < 300:
95
+ try:
96
+ result = response.json()
97
+ except ValueError:
98
+ raise MonitoringError("Invalid monitoring response") from None
99
+ if not isinstance(result, dict):
100
+ raise MonitoringError("Invalid monitoring response")
101
+ return result
102
+ error = MonitoringError(
103
+ f"Monitoring request rejected (HTTP {status})", status_code=status
104
+ )
105
+ if status not in {408, 429, 500, 502, 503, 504}:
106
+ raise error
107
+ retry_after = response.headers.get("Retry-After", "")
108
+ if retry_after.isdigit():
109
+ delay = min(float(retry_after), 2.0)
110
+ if attempt < self._max_retries:
111
+ time.sleep(delay)
112
+ raise error from None
113
+
114
+ def register_graph(self, graph: dict[str, Any]) -> str:
115
+ result = self._post("sdk/graph", graph)
116
+ digest = result.get("graph_digest")
117
+ if (
118
+ not isinstance(digest, str)
119
+ or len(digest) != 64
120
+ or any(c not in "0123456789abcdef" for c in digest)
121
+ ):
122
+ raise MonitoringError("Invalid graph registration response")
123
+ return digest
124
+
125
+ def send_events(self, events: list[dict[str, Any]]) -> None:
126
+ if not 1 <= len(events) <= 100:
127
+ raise ValueError("Send between 1 and 100 events per request")
128
+ result = self._post("sdk/events", {"events": events})
129
+ accepted, duplicates = result.get("accepted"), result.get("duplicates")
130
+ if (
131
+ type(accepted) is not int
132
+ or type(duplicates) is not int
133
+ or accepted < 0
134
+ or duplicates < 0
135
+ or accepted + duplicates != len(events)
136
+ ):
137
+ raise MonitoringError("Invalid event acknowledgement")
138
+
139
+ def publish_policies(self, policies: list[dict[str, Any]]) -> str:
140
+ result = self._post("sdk/policies", {"policies": policies})
141
+ digest = result.get("catalog_digest")
142
+ if (
143
+ not isinstance(digest, str)
144
+ or len(digest) != 64
145
+ or any(c not in "0123456789abcdef" for c in digest)
146
+ ):
147
+ raise MonitoringError("Invalid policy catalog response")
148
+ return digest
149
+
150
+ def policy_configuration(self, graph_digest: str, catalog_digest: str) -> dict[str, Any]:
151
+ return self._request(
152
+ "GET",
153
+ "sdk/policy-config",
154
+ params={"graph_digest": graph_digest, "catalog_digest": catalog_digest},
155
+ )
156
+
157
+ def heartbeat(self) -> None:
158
+ self._post("sdk/heartbeat", {})
159
+
160
+ def close(self) -> None:
161
+ self._http.close()
162
+
163
+ def __enter__(self) -> MonitoringClient:
164
+ return self
165
+
166
+ def __exit__(self, *_: object) -> None:
167
+ self.close()
168
+
169
+
170
+ def register_application(
171
+ *,
172
+ base_url: str,
173
+ name: str,
174
+ management_token: str | None = None,
175
+ timeout: float = 5.0,
176
+ transport: httpx.BaseTransport | None = None,
177
+ ) -> ApplicationCredentials:
178
+ """Provision once, then persist the returned key in your secret manager.
179
+
180
+ Registration is never retried: a lost response may already have created an app.
181
+ Omit the management token only for an explicitly local backend.
182
+ """
183
+ headers = {"Authorization": f"Bearer {_token(management_token)}"} if management_token else {}
184
+ with httpx.Client(timeout=timeout, transport=transport, follow_redirects=False) as client:
185
+ try:
186
+ response = client.post(
187
+ _url(base_url) + "/applications",
188
+ headers=headers,
189
+ json={"name": name, "framework": "langgraph"},
190
+ )
191
+ except httpx.RequestError:
192
+ raise MonitoringError(
193
+ "Application registration response unavailable; check before retrying"
194
+ ) from None
195
+ if response.status_code != 201:
196
+ raise MonitoringError("Application registration rejected", status_code=response.status_code)
197
+ try:
198
+ data = response.json()
199
+ app_id, key = data["application"]["id"], data["api_key"]
200
+ if not isinstance(app_id, str) or not app_id or not isinstance(key, str):
201
+ raise ValueError
202
+ return ApplicationCredentials(app_id, _token(key))
203
+ except (ValueError, KeyError, TypeError):
204
+ raise MonitoringError("Invalid application registration response") from None
@@ -0,0 +1,109 @@
1
+ """Bounded FIFO delivery; callbacks never perform network I/O."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import math
7
+ import time
8
+ from collections import deque
9
+ from threading import Condition, Thread
10
+ from typing import Any
11
+
12
+ from .client import MonitoringClient, MonitoringError
13
+
14
+ logger = logging.getLogger("aictrl_langgraph")
15
+
16
+
17
+ class Delivery:
18
+ def __init__(self, client: MonitoringClient, capacity: int, heartbeat_interval: float) -> None:
19
+ if capacity < 100:
20
+ raise ValueError("queue_capacity must be at least 100")
21
+ if not math.isfinite(heartbeat_interval) or not 0 < heartbeat_interval < 30:
22
+ raise ValueError("heartbeat_interval must be between 0 and 30 seconds")
23
+ self.client = client
24
+ self.capacity = capacity
25
+ self.interval = heartbeat_interval
26
+ self.condition = Condition()
27
+ self.queue: deque[dict[str, Any]] = deque()
28
+ self.inflight = 0
29
+ self.closed = False
30
+ self.error: MonitoringError | None = None
31
+ self.thread = Thread(target=self._run, name="aictrl-monitoring", daemon=True)
32
+ self.thread.start()
33
+
34
+ def fail(self, error: MonitoringError) -> None:
35
+ with self.condition:
36
+ if self.error is None:
37
+ self.error = error
38
+ logger.warning("AI Control Plane telemetry stopped: %s", error)
39
+ self.queue.clear()
40
+ self.condition.notify_all()
41
+
42
+ def submit(self, event: dict[str, Any]) -> None:
43
+ with self.condition:
44
+ if self.error is not None:
45
+ return
46
+ if self.closed:
47
+ self.fail(MonitoringError("Monitor is closed"))
48
+ return
49
+ if len(self.queue) + self.inflight >= self.capacity:
50
+ self.fail(MonitoringError("Monitoring queue capacity exceeded"))
51
+ return
52
+ self.queue.append(event)
53
+ self.condition.notify_all()
54
+
55
+ def _run(self) -> None:
56
+ last_send = time.monotonic()
57
+ try:
58
+ while True:
59
+ with self.condition:
60
+ while not self.queue and not self.closed and self.error is None:
61
+ remaining = self.interval - (time.monotonic() - last_send)
62
+ if remaining <= 0:
63
+ break
64
+ self.condition.wait(remaining)
65
+ if self.error is not None or (self.closed and not self.queue):
66
+ return
67
+ batch = [self.queue.popleft() for _ in range(min(100, len(self.queue)))]
68
+ self.inflight = len(batch)
69
+ if batch:
70
+ self.client.send_events(batch)
71
+ else:
72
+ self.client.heartbeat()
73
+ last_send = time.monotonic()
74
+ with self.condition:
75
+ self.inflight = 0
76
+ self.condition.notify_all()
77
+ except MonitoringError as error:
78
+ self.fail(error)
79
+ except Exception:
80
+ self.fail(MonitoringError("Unexpected monitoring delivery failure"))
81
+ finally:
82
+ self.client.close()
83
+ with self.condition:
84
+ self.inflight = 0
85
+ self.condition.notify_all()
86
+
87
+ def flush(self, timeout: float) -> None:
88
+ if not math.isfinite(timeout) or timeout <= 0:
89
+ raise ValueError("flush timeout must be positive and finite")
90
+ deadline = time.monotonic() + timeout
91
+ with self.condition:
92
+ while self.queue or self.inflight:
93
+ if self.error is not None:
94
+ raise self.error
95
+ remaining = deadline - time.monotonic()
96
+ if remaining <= 0:
97
+ raise MonitoringError("Monitoring flush timed out")
98
+ self.condition.wait(remaining)
99
+ if self.error is not None:
100
+ raise self.error
101
+
102
+ def close(self, timeout: float) -> None:
103
+ with self.condition:
104
+ self.closed = True
105
+ self.condition.notify_all()
106
+ self.flush(timeout)
107
+ self.thread.join(timeout)
108
+ if self.thread.is_alive():
109
+ raise MonitoringError("Monitoring shutdown timed out")
@@ -0,0 +1,132 @@
1
+ """Local policy evaluators and guarded node boundaries."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import inspect
7
+ from collections.abc import Awaitable, Callable, Sequence
8
+ from dataclasses import dataclass, field
9
+ from functools import wraps
10
+ from typing import Any
11
+
12
+ from .client import MonitoringClient, MonitoringError
13
+ from .policy import PolicyBlocked
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Policy:
18
+ """Declare an evaluator; bump version whenever its behavior changes.
19
+
20
+ Return exactly True to allow. False, any other value, or an exception denies.
21
+ Evaluation receives the local node input; it is never sent to the service.
22
+ """
23
+
24
+ id: str
25
+ name: str
26
+ version: str
27
+ check: Callable[[Any], bool | Awaitable[bool]] = field(repr=False)
28
+ description: str = ""
29
+ operations: tuple[str, ...] = ()
30
+
31
+ def metadata(self) -> dict[str, Any]:
32
+ return {
33
+ "id": self.id,
34
+ "name": self.name,
35
+ "version": self.version,
36
+ "description": self.description,
37
+ "operations": list(self.operations),
38
+ }
39
+
40
+
41
+ class PolicyEnforcer:
42
+ def __init__(self, client: MonitoringClient, policies: Sequence[Policy]) -> None:
43
+ self.client = client
44
+ self.policies = {policy.id: policy for policy in policies}
45
+ if len(self.policies) != len(policies):
46
+ raise ValueError("Policy IDs must be unique")
47
+ self.nodes: dict[str, str | None] = {}
48
+ self.graph_digest: str | None = None
49
+ self.catalog_digest: str | None = None
50
+
51
+ def register(self, metadata: dict[str, Any]) -> None:
52
+ if not self.nodes and not self.policies:
53
+ return
54
+ ids = {node["id"] for node in metadata["nodes"]}
55
+ if not self.nodes.keys() <= ids:
56
+ raise ValueError("A guarded node is absent from the compiled graph")
57
+ for node in metadata["nodes"]:
58
+ if node["id"] in self.nodes:
59
+ node["policy_hook"] = True
60
+ node["operation"] = self.nodes[node["id"]]
61
+ self.catalog_digest = self.client.publish_policies(
62
+ [policy.metadata() for policy in self.policies.values()]
63
+ )
64
+
65
+ def selected(self, node_id: str) -> list[Policy]:
66
+ if self.graph_digest is None or self.catalog_digest is None:
67
+ raise PolicyBlocked("Instrument the guarded graph before execution")
68
+ try:
69
+ config = self.client.policy_configuration(self.graph_digest, self.catalog_digest)
70
+ if (
71
+ config.get("graph_digest") != self.graph_digest
72
+ or config.get("catalog_digest") != self.catalog_digest
73
+ or type(config.get("version")) is not int
74
+ or config["version"] < 0
75
+ ):
76
+ raise ValueError
77
+ assignments = config["assignments"]
78
+ if not isinstance(assignments, dict):
79
+ raise ValueError
80
+ ids = assignments.get(node_id, [])
81
+ if not isinstance(ids, list) or any(not isinstance(item, str) for item in ids):
82
+ raise ValueError
83
+ return [self.policies[policy_id] for policy_id in ids]
84
+ except (MonitoringError, ValueError, KeyError, TypeError):
85
+ raise PolicyBlocked("The policy configuration is unavailable or incompatible") from None
86
+
87
+ def guard(self, node_id: str, function: Callable[..., Any], operation: str | None):
88
+ if self.graph_digest is not None:
89
+ raise ValueError("Declare guarded nodes before instrumenting the graph")
90
+ if node_id in self.nodes:
91
+ raise ValueError("This policy node was already declared")
92
+ if not callable(function):
93
+ raise TypeError("guard_node expects a node function")
94
+ input_name = next(iter(inspect.signature(function).parameters))
95
+ self.nodes[node_id] = operation
96
+
97
+ @wraps(function)
98
+ def sync_guard(*args: Any, **kwargs: Any):
99
+ try:
100
+ state = args[0] if args else kwargs[input_name]
101
+ for policy in self.selected(node_id):
102
+ result = policy.check(state)
103
+ if inspect.isawaitable(result):
104
+ if inspect.iscoroutine(result):
105
+ result.close()
106
+ raise PolicyBlocked("Async policy evaluators require an async node")
107
+ if result is not True:
108
+ raise PolicyBlocked("A configured policy denied this node")
109
+ except PolicyBlocked:
110
+ raise
111
+ except Exception:
112
+ raise PolicyBlocked("A configured policy could not be evaluated") from None
113
+ return function(*args, **kwargs)
114
+
115
+ @wraps(function)
116
+ async def async_guard(*args: Any, **kwargs: Any):
117
+ try:
118
+ state = args[0] if args else kwargs[input_name]
119
+ policies = await asyncio.to_thread(self.selected, node_id)
120
+ for policy in policies:
121
+ result = await asyncio.to_thread(policy.check, state)
122
+ if inspect.isawaitable(result):
123
+ result = await result
124
+ if result is not True:
125
+ raise PolicyBlocked("A configured policy denied this node")
126
+ except PolicyBlocked:
127
+ raise
128
+ except Exception:
129
+ raise PolicyBlocked("A configured policy could not be evaluated") from None
130
+ return await function(*args, **kwargs)
131
+
132
+ return async_guard if inspect.iscoroutinefunction(function) else sync_guard
@@ -0,0 +1,30 @@
1
+ """Export topology without serializing runnable objects or application state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ from langgraph.graph.state import CompiledStateGraph
9
+
10
+
11
+ def graph_metadata(graph: CompiledStateGraph) -> dict[str, Any]:
12
+ drawing = graph.get_graph(xray=False)
13
+ nodes = []
14
+ for node_id in drawing.nodes:
15
+ if not re.fullmatch(r"[\w.:-]{1,100}", node_id):
16
+ raise ValueError("Graph node IDs must match [\\w.:-]{1,100}")
17
+ kind = "start" if node_id == "__start__" else "end" if node_id == "__end__" else "step"
18
+ nodes.append({"id": node_id, "label": node_id, "kind": kind})
19
+ edges = [
20
+ {
21
+ "source": edge.source,
22
+ "target": edge.target,
23
+ "conditional": edge.conditional,
24
+ "label": str(edge.data)[:100] if edge.data is not None else "",
25
+ }
26
+ for edge in drawing.edges
27
+ ]
28
+ if not 1 <= len(nodes) <= 500 or len(edges) > 2000:
29
+ raise ValueError("Monitoring supports 1–500 nodes and up to 2,000 edges")
30
+ return {"framework": "langgraph", "nodes": nodes, "edges": edges}
@@ -0,0 +1,151 @@
1
+ """Public integration: retain the compiled graph API and add monitoring callbacks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import os
8
+ from collections.abc import Callable, Sequence
9
+ from typing import Any, TypeVar
10
+
11
+ import httpx
12
+ from langgraph.graph.state import CompiledStateGraph
13
+
14
+ from .callbacks import MonitoringCallback
15
+ from .client import MonitoringClient, MonitoringError
16
+ from .delivery import Delivery
17
+ from .enforcement import Policy, PolicyEnforcer
18
+ from .graph import graph_metadata
19
+
20
+ GraphT = TypeVar("GraphT", bound=CompiledStateGraph)
21
+
22
+
23
+ class LangGraphMonitor:
24
+ """Own one application connection and instrument its root compiled graph.
25
+
26
+ Call ``instrument`` during startup (or ``ainstrument`` in async code).
27
+ Telemetry is delivered in the background. Opt-in policy guards fetch current
28
+ assignments before node execution and raise PolicyBlocked on denial or an
29
+ unavailable configuration. ``flush`` and ``close`` report delivery failures.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ *,
35
+ base_url: str,
36
+ api_key: str,
37
+ timeout: float = 5.0,
38
+ max_retries: int = 2,
39
+ queue_capacity: int = 10_000,
40
+ heartbeat_interval: float = 10.0,
41
+ max_active_runs: int = 1_000,
42
+ transport: httpx.BaseTransport | None = None,
43
+ policies: Sequence[Policy] = (),
44
+ ) -> None:
45
+ if max_active_runs < 1:
46
+ raise ValueError("max_active_runs must be positive")
47
+ self._client = MonitoringClient(
48
+ base_url=base_url,
49
+ api_key=api_key,
50
+ timeout=timeout,
51
+ max_retries=max_retries,
52
+ transport=transport,
53
+ )
54
+ try:
55
+ self._enforcer = PolicyEnforcer(self._client, policies)
56
+ self._delivery = Delivery(self._client, queue_capacity, heartbeat_interval)
57
+ except Exception:
58
+ self._client.close()
59
+ raise
60
+ self._max_runs = max_active_runs
61
+ self._handler: MonitoringCallback | None = None
62
+
63
+ @classmethod
64
+ def from_env(cls, **kwargs: Any) -> LangGraphMonitor:
65
+ """Read AICTRL_URL and AICTRL_API_KEY; never load a dotenv file implicitly."""
66
+ try:
67
+ base_url, api_key = os.environ["AICTRL_URL"], os.environ["AICTRL_API_KEY"]
68
+ except KeyError:
69
+ raise ValueError("Set AICTRL_URL and AICTRL_API_KEY") from None
70
+ return cls(base_url=base_url, api_key=api_key, **kwargs)
71
+
72
+ @property
73
+ def error(self) -> MonitoringError | None:
74
+ """The first delivery failure, or None while delivery is healthy."""
75
+ return self._delivery.error
76
+
77
+ def guard_node(
78
+ self, node_id: str, function: Callable[..., Any], *, operation: str | None = None
79
+ ):
80
+ """Wrap a node before adding it to StateGraph; keep its signature and runtime inputs."""
81
+ return self._enforcer.guard(node_id, function, operation)
82
+
83
+ def instrument(self, graph: GraphT) -> GraphT:
84
+ if not isinstance(graph, CompiledStateGraph):
85
+ raise TypeError("instrument expects a compiled LangGraph StateGraph")
86
+ if self._delivery.closed or self.error:
87
+ raise self.error or MonitoringError("Monitor is closed")
88
+ if self._handler is not None:
89
+ raise ValueError(
90
+ "Use one monitor per root graph; create a new monitor for a new version"
91
+ )
92
+ metadata = graph_metadata(graph)
93
+ self._enforcer.register(metadata)
94
+ digest = self._client.register_graph(metadata)
95
+ self._enforcer.graph_digest = digest
96
+ handler = MonitoringCallback(
97
+ self._delivery,
98
+ digest,
99
+ {node["id"] for node in metadata["nodes"]},
100
+ self._max_runs,
101
+ )
102
+ self._handler = handler
103
+ # with_config copies the compiled graph and merges existing callbacks.
104
+ return graph.with_config({"callbacks": [handler]})
105
+
106
+ async def ainstrument(self, graph: GraphT) -> GraphT:
107
+ return await asyncio.to_thread(self.instrument, graph)
108
+
109
+ def flush(self, timeout: float = 30.0) -> None:
110
+ """Wait for queued events to be acknowledged; raises on loss or timeout."""
111
+ self._delivery.flush(timeout)
112
+
113
+ async def aflush(self, timeout: float = 30.0) -> None:
114
+ await asyncio.to_thread(self.flush, timeout)
115
+
116
+ def close(self, timeout: float = 30.0) -> None:
117
+ """Stop accepting events, drain delivery and release network resources."""
118
+ try:
119
+ self._delivery.close(timeout)
120
+ finally:
121
+ if self._handler is not None:
122
+ self._handler.clear()
123
+
124
+ async def aclose(self, timeout: float = 30.0) -> None:
125
+ await asyncio.to_thread(self.close, timeout)
126
+
127
+ def __enter__(self) -> LangGraphMonitor:
128
+ return self
129
+
130
+ def __exit__(self, exc_type: object, *_: object) -> None:
131
+ try:
132
+ self.close()
133
+ except MonitoringError:
134
+ if exc_type is None:
135
+ raise
136
+ logging.getLogger("aictrl_langgraph").warning(
137
+ "Monitoring shutdown failed while preserving an application exception"
138
+ )
139
+
140
+ async def __aenter__(self) -> LangGraphMonitor:
141
+ return self
142
+
143
+ async def __aexit__(self, exc_type: object, *_: object) -> None:
144
+ try:
145
+ await self.aclose()
146
+ except MonitoringError:
147
+ if exc_type is None:
148
+ raise
149
+ logging.getLogger("aictrl_langgraph").warning(
150
+ "Monitoring shutdown failed while preserving an application exception"
151
+ )
@@ -0,0 +1,10 @@
1
+ """Explicit application policy denials, observed by the monitoring callbacks."""
2
+
3
+
4
+ class PolicyBlocked(PermissionError):
5
+ """Raise before a denied operation to report a blocked node and run.
6
+
7
+ SDK guards evaluate application-defined policies locally. Applications can
8
+ also raise this exception explicitly; telemetry never sends its message or args.
9
+ Let it propagate out of the graph invocation before handling the denial.
10
+ """
File without changes
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: aictrl-langgraph
3
+ Version: 0.1.0
4
+ Summary: Graph and execution monitoring for LangGraph workflows
5
+ Project-URL: Repository, https://github.com/aictrl-azenohi/ai-control-plane-pro
6
+ Project-URL: Documentation, https://github.com/aictrl-azenohi/ai-control-plane-pro/tree/main/packages/aictrl-langgraph
7
+ Project-URL: Issues, https://github.com/aictrl-azenohi/ai-control-plane-pro/issues
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: agents,langgraph,monitoring,observability
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: <3.15,>=3.11
19
+ Requires-Dist: httpx<1,>=0.28
20
+ Requires-Dist: langchain-core<2,>=1.6
21
+ Requires-Dist: langgraph<2,>=1.2
22
+ Description-Content-Type: text/markdown
23
+
24
+ # AI Control Plane · LangGraph SDK
25
+
26
+ Connect a compiled LangGraph `StateGraph` to graph and run monitoring with one
27
+ Python package. The SDK registers the topology, reports run and node lifecycle
28
+ changes, and keeps the application connected with a heartbeat.
29
+ Optional policy guards enforce assignments configured in the graph workspace.
30
+
31
+ Python 3.11–3.14. This release is tested with LangGraph 1.2.12 and LangChain Core
32
+ 1.6.6; dependencies are pinned to those versions. License: Apache-2.0.
33
+
34
+ ## Install
35
+
36
+ ```sh
37
+ uv add aictrl-langgraph # or: pip install aictrl-langgraph
38
+ ```
39
+
40
+ Python 3.11–3.14. Pin a compatible range in applications, for example
41
+ `aictrl-langgraph>=0.1,<0.2`, while the SDK is in `0.x`. Releases and notes:
42
+ https://github.com/aictrl-azenohi/ai-control-plane-pro/releases
43
+
44
+ ## Install from a local build
45
+
46
+ From the repository root:
47
+
48
+ ```sh
49
+ uv build --package aictrl-langgraph --out-dir dist/sdk
50
+ ```
51
+
52
+ In the agent application's environment:
53
+
54
+ ```sh
55
+ python -m pip install /path/to/dist/sdk/aictrl_langgraph-0.1.0-py3-none-any.whl
56
+ ```
57
+
58
+ The wheel is standalone. It does not require the repository, the backend package,
59
+ or a separate `aictrl` installation. No package registry or publishing automation
60
+ is configured by this integration.
61
+
62
+ ## Provision the application once
63
+
64
+ An administrator creates an application using the monitoring API. This helper is
65
+ included in the same package:
66
+
67
+ ```python
68
+ import os
69
+ from aictrl_langgraph import register_application
70
+
71
+ credentials = register_application(
72
+ base_url=os.environ["AICTRL_URL"],
73
+ name="Support workflow",
74
+ management_token=os.environ["MONITORING_ACCESS_TOKEN"],
75
+ )
76
+ # Store credentials.api_key in your secret manager as AICTRL_API_KEY.
77
+ # Save credentials.application_id for administration. Do not log the key.
78
+ ```
79
+
80
+ Omit `management_token` only for the backend's explicit local development mode.
81
+ Do not provision on every process start. Registration is not retried because a
82
+ lost response can already have created an application. If this happens, inspect
83
+ the application list and rotate that application's credentials through the API.
84
+
85
+ Runtime processes only need `AICTRL_URL` and the application-scoped `AICTRL_API_KEY`.
86
+ `AICTRL_URL` is the server URL (for example `http://localhost:8100` locally), optionally
87
+ ending in `/api/v1`. Use HTTPS for remote connections. The SDK does not load `.env`
88
+ files. A management token is not an ingestion key.
89
+
90
+ ## Integrate your graph
91
+
92
+ ```python
93
+ from aictrl_langgraph import LangGraphMonitor
94
+
95
+ # builder is your application's existing StateGraph.
96
+ with LangGraphMonitor.from_env() as monitor:
97
+ graph = monitor.instrument(builder.compile())
98
+ result = graph.invoke(inputs)
99
+ monitor.flush()
100
+ ```
101
+
102
+ `instrument` returns a copy of the compiled graph with monitoring callbacks added.
103
+ Existing callbacks, configuration, checkpointing, runtime context and graph methods
104
+ remain available. Use the returned graph for `invoke`, `batch`, `stream`, `ainvoke`,
105
+ `abatch` and `astream`. Use one monitor per root graph and application connection;
106
+ create a new monitor for a new graph version. Instrument during startup.
107
+
108
+ Async applications can keep network registration and shutdown off the event loop:
109
+
110
+ ```python
111
+ async with LangGraphMonitor.from_env() as monitor:
112
+ graph = await monitor.ainstrument(builder.compile())
113
+ result = await graph.ainvoke(inputs)
114
+ async for chunk in graph.astream(inputs, stream_mode="updates"):
115
+ consume(chunk)
116
+ await monitor.aflush()
117
+ ```
118
+
119
+ Stream modes and chunks are unchanged. Exhaust or explicitly close/aclose stream
120
+ iterators before closing the monitor. Closing a stream early or cancelling an
121
+ invocation records a failed run. Graph exceptions are preserved.
122
+
123
+ A runnable, LLM-free example is included in
124
+ [`examples/workflow.py`](examples/workflow.py). Run it only against an application
125
+ registered for testing; it creates real monitoring records.
126
+
127
+ ## Run and graph semantics
128
+
129
+ - Each graph invocation gets a new monitoring run ID and starts at sequence 1.
130
+ Parallel invocations are isolated. Parallel nodes and retry attempts share the
131
+ invocation's ordered sequence.
132
+ - Interrupts finish that invocation as `PAUSED`. Resuming a checkpoint creates a
133
+ **new monitoring run** for the resumed invocation. LangGraph's thread/checkpoint
134
+ continuity remains intact; thread IDs and checkpoint contents are not sent.
135
+ - Branches and loops retain their node IDs. Give conditional edges an explicit
136
+ `path_map` or a `Literal` return annotation so LangGraph can expose their topology.
137
+ The SDK exports the public `get_graph(xray=False)` representation; it cannot
138
+ discover undeclared runtime `Command` destinations. Declare node destinations
139
+ when building such graphs.
140
+ - Nested subgraphs appear as their parent node. Internal subgraph nodes, nested
141
+ runnable calls, and individual model/tool calls are not separate runs or nodes.
142
+ Cache hits that do not execute a node do not generate synthetic node events.
143
+ - Node IDs must match `[\w.:-]{1,100}`. Graphs allow at most 500 nodes and 2,000 edges.
144
+ The immutable digest returned by the API is attached to every event.
145
+ - Monitoring callbacks observe execution without changing routing, prompts, retry
146
+ policies or checkpoint state. Explicit policy guards can block node execution.
147
+
148
+ ## Guard nodes with policies
149
+
150
+ Declare local evaluators with `Policy` and wrap each protected node with
151
+ `monitor.guard_node` **before** adding it to the StateGraph:
152
+
153
+ ```python
154
+ from aictrl_langgraph import LangGraphMonitor, Policy, PolicyBlocked
155
+
156
+ policies = [
157
+ Policy(
158
+ "export_limit",
159
+ "Export amount limit",
160
+ "1",
161
+ lambda state: state["amount"] <= 100,
162
+ description="Allow exports up to 100 units.",
163
+ operations=("data.export",),
164
+ )
165
+ ]
166
+ with LangGraphMonitor.from_env(policies=policies) as monitor:
167
+ # builder, export_result and inputs belong to your application.
168
+ builder.add_node(
169
+ "export",
170
+ monitor.guard_node(
171
+ "export",
172
+ export_result,
173
+ operation="data.export",
174
+ ),
175
+ )
176
+ graph = monitor.instrument(builder.compile())
177
+ try:
178
+ result = graph.invoke(inputs)
179
+ except PolicyBlocked:
180
+ handle_denial()
181
+ ```
182
+
183
+ The catalog appears in **Policies**. Choose **Optimize**, assign a policy to a
184
+ diamond and **Apply**. Each guard fetches current assignments before calling the
185
+ node, so a saved change affects its next execution boundary. No assignment means
186
+ no evaluator runs, but the configuration read must still succeed. Bump the policy
187
+ version when its behavior changes; evaluator source code is never uploaded.
188
+
189
+ Only exactly `True` allows execution. Denials, evaluator errors, unavailable
190
+ configuration or incompatible active versions raise `PolicyBlocked` before the
191
+ node function runs. Callbacks report the node and run as `BLOCKED`. Keep evaluators
192
+ free of side effects and do not mutate their input. Async node functions support
193
+ async evaluators; sync nodes reject an async evaluator. Wrappers preserve node
194
+ signatures and injected config/runtime context.
195
+
196
+ Guard only with ordinary sync/async node functions. Unwrapped nodes and side
197
+ effects already in progress are outside enforcement; parallel operations are not
198
+ rolled back. Do not cache protected nodes: cache hits skip their guards. A
199
+ checkpoint resume checks nodes that execute again. All versions using one
200
+ application key must have compatible graph/catalog metadata; incompatible active
201
+ bindings block until a compatible configuration is applied.
202
+
203
+ ## Delivery and shutdown
204
+
205
+ ```python
206
+ monitor = LangGraphMonitor(
207
+ base_url="https://control.example.com",
208
+ api_key=application_key,
209
+ timeout=5.0,
210
+ max_retries=2,
211
+ queue_capacity=10_000,
212
+ heartbeat_interval=10.0,
213
+ max_active_runs=1_000,
214
+ )
215
+ ```
216
+
217
+ Callbacks only enqueue metadata under a short lock. One background worker sends
218
+ FIFO batches of at most 100 events. Transient network errors and HTTP
219
+ 408/429/500/502/503/504 are retried with the **same event IDs, timestamps and body**.
220
+ Other errors, including authentication failures and sequence conflicts, are not
221
+ retried. Redirects are not followed. Request timeouts and retry counts are bounded.
222
+
223
+ If delivery retries are exhausted or the queue fills, telemetry for that monitor
224
+ stops and `monitor.error` records the failure. It does not silently skip an event
225
+ and continue with an invalid sequence. The application keeps running, a safe
226
+ warning is logged, and `flush()` / `close()` raise `MonitoringError`. Opt-in guards
227
+ still require a successful configuration read before execution; an unavailable
228
+ connection denies the operation even if telemetry can no longer report it. A new monitor
229
+ can be created after the underlying problem is corrected. The affected history
230
+ can remain incomplete; completion is never fabricated.
231
+
232
+ `flush(timeout=30)` waits for queued events to be acknowledged. A flush timeout
233
+ does not discard events. `close(timeout=30)` stops new telemetry and drains the
234
+ queue; use it after all graph invocations and streams finish. `aflush` and `aclose`
235
+ are the asynchronous equivalents. Context managers close automatically and do
236
+ not replace an exception already raised by the application with a delivery error.
237
+
238
+ Delivery is in-memory and best effort. Process crashes or forced termination can
239
+ lose unsent events. There is no disk spool, cross-process queue or recovery of
240
+ in-flight invocations after a process restart. Create monitors after worker fork;
241
+ monitor instances belong to one process.
242
+
243
+ ## Data collected
244
+
245
+ Only graph node IDs/labels, topology, opaque monitoring run/event IDs, graph digest,
246
+ lifecycle types, sequence numbers and UTC timestamps are sent. With policy guards,
247
+ policy IDs/names/descriptions/versions, operation restrictions and hook metadata are
248
+ also sent, and the SDK reads assignment IDs. Inputs, outputs,
249
+ state values, messages, prompts, tool arguments, exception text, checkpoint data
250
+ and callback metadata are never serialized. Node names and edge labels are visible
251
+ in the UI, so use structural labels rather than user content. Credentials and
252
+ server response bodies are excluded from SDK diagnostics.
253
+
254
+ ## Development
255
+
256
+ ```sh
257
+ uv run pytest packages/aictrl-langgraph/tests services/backend/tests/test_langgraph_sdk.py
258
+ make verify
259
+ make sdk-check
260
+ ```
261
+
262
+ `make sdk-check` builds the wheel and source distribution, checks their metadata,
263
+ installs the wheel into an isolated environment and executes a real LangGraph run
264
+ outside the repository. CI performs isolated installation checks on Python
265
+ 3.11, 3.12, 3.13 and 3.14. These checks do not upload or publish anything.
@@ -0,0 +1,13 @@
1
+ aictrl_langgraph/__init__.py,sha256=3Cjn7U2Q_wHiQqm2eL_vseVdYxwnjrSir0Cy4Qgk23U,506
2
+ aictrl_langgraph/callbacks.py,sha256=fnvK0JUTqyQkCJRToN8Id59CEdvG4q5HqXBuchUyOmM,4896
3
+ aictrl_langgraph/client.py,sha256=rqZOsraiMJUQPaWqVSsMX5OeOjAYn7BQRqAMRCiCHGI,7466
4
+ aictrl_langgraph/delivery.py,sha256=A7I1omCZXDIrG8PBYiy6IARs8G-wxj51tNoFiXbIyZM,4252
5
+ aictrl_langgraph/enforcement.py,sha256=zm7MuzFIWavrPKqJ9aECkl_27g7LoKRJ4cL1WHI3C5w,5593
6
+ aictrl_langgraph/graph.py,sha256=pFHnJpJLD9as8xFPYPRbIJmKJNe-QWO4GbzQw69EGEc,1135
7
+ aictrl_langgraph/monitor.py,sha256=jJ3eMGDEiw-VWPiMfKXOGhb8nyoNyuEawSH3KHfv8h4,5582
8
+ aictrl_langgraph/policy.py,sha256=NUGO7TIBEuaX_YWPxlce45I_AuTEhF6fPxf2tBJ-mvU,444
9
+ aictrl_langgraph/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ aictrl_langgraph-0.1.0.dist-info/METADATA,sha256=bfsj7zs8oa0Ar4sHM1KYw3bU7PNhhHf44mDw81ruZ74,11595
11
+ aictrl_langgraph-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
12
+ aictrl_langgraph-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ aictrl_langgraph-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
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.