behaviorweave 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,27 @@
1
+ """Behavioral policy and intervention framework for graph agents."""
2
+
3
+ from .engine import BehaviorEngine
4
+ from .events import BehaviorEvent, EventType, Outcome
5
+ from .interventions import AuditRecord, Intervention, InterventionDecision, InterventionType
6
+ from .patterns import PatternObservation, built_in_patterns
7
+ from .policies import PolicyEngine, PolicyRule
8
+ from .state import BehaviorState, InMemoryBehaviorStateStore
9
+
10
+ __all__ = [
11
+ "AuditRecord",
12
+ "BehaviorEngine",
13
+ "BehaviorEvent",
14
+ "BehaviorState",
15
+ "EventType",
16
+ "InMemoryBehaviorStateStore",
17
+ "Intervention",
18
+ "InterventionDecision",
19
+ "InterventionType",
20
+ "Outcome",
21
+ "PatternObservation",
22
+ "PolicyEngine",
23
+ "PolicyRule",
24
+ "built_in_patterns",
25
+ ]
26
+
27
+ __version__ = "0.1.0"
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from .events import BehaviorEvent
6
+ from .interventions import Intervention, InterventionDecision, InterventionType
7
+ from .patterns import Pattern, built_in_patterns
8
+ from .policies import PolicyEngine, PolicyRule
9
+ from .state import BehaviorStateStore, InMemoryBehaviorStateStore, with_cooldown
10
+
11
+
12
+ class BehaviorEngine:
13
+ def __init__(
14
+ self,
15
+ *,
16
+ policies: Iterable[PolicyRule] = (),
17
+ patterns: Iterable[Pattern] | None = None,
18
+ state_store: BehaviorStateStore | None = None,
19
+ ) -> None:
20
+ self.store = state_store or InMemoryBehaviorStateStore()
21
+ self.patterns = tuple(patterns or built_in_patterns())
22
+ self.policy_engine = PolicyEngine(policies)
23
+ self._rules = self.policy_engine.rules
24
+
25
+ def process(self, event: BehaviorEvent) -> InterventionDecision:
26
+ decisions: list[InterventionDecision] = []
27
+ for pattern in self.patterns:
28
+ if pattern.matches(event):
29
+ observation = pattern.observe(event, self.store)
30
+ decision = self.policy_engine.evaluate(observation)
31
+ decisions.append(decision)
32
+ if decision.intervention.kind is not InterventionType.NOOP:
33
+ rule = next(
34
+ (r for r in self._rules if r.policy_id == decision.intervention.policy),
35
+ None,
36
+ )
37
+ if rule and rule.cooldown:
38
+ state = self.store.get(observation.state_key)
39
+ if state:
40
+ self.store.put(
41
+ observation.state_key,
42
+ with_cooldown(
43
+ state, event.timestamp + rule.cooldown, rule.policy_id
44
+ ),
45
+ )
46
+ if not decisions:
47
+ return InterventionDecision(intervention=Intervention(InterventionType.NOOP))
48
+ return max(
49
+ decisions,
50
+ key=lambda d: (
51
+ d.intervention.kind in {InterventionType.STOP, InterventionType.PAUSE},
52
+ d.intervention.kind is not InterventionType.NOOP,
53
+ d.explanation.count if d.explanation else 0,
54
+ ),
55
+ )
@@ -0,0 +1,118 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass, field
6
+ from datetime import UTC, datetime
7
+ from enum import StrEnum
8
+ from hashlib import sha256
9
+ from uuid import uuid4
10
+
11
+
12
+ class EventType(StrEnum):
13
+ TOOL_CALL = "tool_call"
14
+ NODE_EXECUTION = "node_execution"
15
+ AGENT_HANDOFF = "agent_handoff"
16
+ DELEGATION = "delegation"
17
+ OUTCOME = "outcome"
18
+ RETRY = "retry"
19
+ CUSTOM = "custom"
20
+
21
+
22
+ class Outcome(StrEnum):
23
+ SUCCESS = "success"
24
+ FAILURE = "failure"
25
+ RETRY = "retry"
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class BehaviorEvent:
30
+ event_type: EventType
31
+ scope: str
32
+ timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))
33
+ event_id: str = field(default_factory=lambda: str(uuid4()))
34
+ execution_id: str | None = None
35
+ thread_id: str | None = None
36
+ run_id: str | None = None
37
+ node_name: str | None = None
38
+ tool_name: str | None = None
39
+ agent_name: str | None = None
40
+ target_agent: str | None = None
41
+ outcome: Outcome | None = None
42
+ metadata: Mapping[str, object] = field(default_factory=dict)
43
+ provenance_ref: str | None = None
44
+ fingerprint: str | None = None
45
+
46
+ def __post_init__(self) -> None:
47
+ if not self.scope.strip():
48
+ raise ValueError("scope must not be empty")
49
+ if self.timestamp.tzinfo is None:
50
+ raise ValueError("timestamp must be timezone-aware")
51
+
52
+ @classmethod
53
+ def tool_call(
54
+ cls,
55
+ tool_name: str,
56
+ arguments: Mapping[str, object] | None = None,
57
+ *,
58
+ scope: str,
59
+ event_id: str | None = None,
60
+ ) -> BehaviorEvent:
61
+ args = dict(arguments or {})
62
+ fingerprint = f"{tool_name}({json.dumps(args, sort_keys=True, separators=(',', ':'))})"
63
+ return cls(
64
+ EventType.TOOL_CALL,
65
+ scope=scope,
66
+ tool_name=tool_name,
67
+ metadata={"arguments": args},
68
+ event_id=event_id or str(uuid4()),
69
+ fingerprint=fingerprint,
70
+ )
71
+
72
+ @classmethod
73
+ def outcome_event(
74
+ cls,
75
+ outcome: Outcome,
76
+ *,
77
+ scope: str,
78
+ event_id: str | None = None,
79
+ metadata: Mapping[str, object] | None = None,
80
+ ) -> BehaviorEvent:
81
+ return cls(
82
+ EventType.OUTCOME,
83
+ scope=scope,
84
+ outcome=outcome,
85
+ event_id=event_id or str(uuid4()),
86
+ metadata=dict(metadata or {}),
87
+ )
88
+
89
+ def identity(self) -> str:
90
+ if self.event_type in {EventType.AGENT_HANDOFF, EventType.DELEGATION}:
91
+ return f"{self.agent_name or 'unknown'}->{self.target_agent or 'unknown'}"
92
+ raw = self.fingerprint or self.node_name or self.tool_name or self.agent_name
93
+ return raw or self.event_type.value
94
+
95
+ def idempotency_key(self) -> str:
96
+ return self.event_id or sha256(self.to_json().encode()).hexdigest()
97
+
98
+ def to_dict(self) -> dict[str, object]:
99
+ return {
100
+ "event_type": self.event_type.value,
101
+ "scope": self.scope,
102
+ "timestamp": self.timestamp.isoformat(),
103
+ "event_id": self.event_id,
104
+ "execution_id": self.execution_id,
105
+ "thread_id": self.thread_id,
106
+ "run_id": self.run_id,
107
+ "node_name": self.node_name,
108
+ "tool_name": self.tool_name,
109
+ "agent_name": self.agent_name,
110
+ "target_agent": self.target_agent,
111
+ "outcome": self.outcome.value if self.outcome else None,
112
+ "metadata": dict(self.metadata),
113
+ "provenance_ref": self.provenance_ref,
114
+ "fingerprint": self.fingerprint,
115
+ }
116
+
117
+ def to_json(self) -> str:
118
+ return json.dumps(self.to_dict(), sort_keys=True)
@@ -0,0 +1 @@
1
+ """Framework integration boundaries."""
@@ -0,0 +1,3 @@
1
+ from .adapter import LangChainEventAdapter
2
+
3
+ __all__ = ["LangChainEventAdapter"]
@@ -0,0 +1,22 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from ...events import BehaviorEvent, EventType, Outcome
6
+
7
+
8
+ class LangChainEventAdapter:
9
+ """Adapter for public LangChain v1 callback payloads; no monkey-patching."""
10
+
11
+ def tool_start(
12
+ self, tool_name: str, *, scope: str, arguments: Mapping[str, object] | None = None
13
+ ) -> BehaviorEvent:
14
+ return BehaviorEvent.tool_call(tool_name, arguments, scope=scope)
15
+
16
+ def tool_error(self, *, scope: str, error_type: str) -> BehaviorEvent:
17
+ return BehaviorEvent.outcome_event(
18
+ Outcome.FAILURE, scope=scope, metadata={"error_type": error_type}
19
+ )
20
+
21
+ def retry(self, *, scope: str) -> BehaviorEvent:
22
+ return BehaviorEvent(EventType.RETRY, scope=scope, outcome=Outcome.RETRY)
@@ -0,0 +1,3 @@
1
+ from .adapter import LangGraphEventAdapter
2
+
3
+ __all__ = ["LangGraphEventAdapter"]
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from ...events import BehaviorEvent, EventType, Outcome
6
+
7
+
8
+ class LangGraphEventAdapter:
9
+ """Translate public callback/runtime payloads into normalized events."""
10
+
11
+ def node(
12
+ self, node_name: str, *, scope: str, metadata: Mapping[str, object] | None = None
13
+ ) -> BehaviorEvent:
14
+ return BehaviorEvent(
15
+ EventType.NODE_EXECUTION,
16
+ scope=scope,
17
+ node_name=node_name,
18
+ metadata=dict(metadata or {}),
19
+ )
20
+
21
+ def tool(
22
+ self, tool_name: str, *, scope: str, arguments: Mapping[str, object] | None = None
23
+ ) -> BehaviorEvent:
24
+ return BehaviorEvent.tool_call(tool_name, arguments, scope=scope)
25
+
26
+ def outcome(self, outcome: Outcome, *, scope: str) -> BehaviorEvent:
27
+ return BehaviorEvent.outcome_event(outcome, scope=scope)
@@ -0,0 +1,3 @@
1
+ from .adapter import LangGraphXAIEventAdapter
2
+
3
+ __all__ = ["LangGraphXAIEventAdapter"]
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from ...events import BehaviorEvent, EventType
6
+
7
+
8
+ class LangGraphXAIEventAdapter:
9
+ """Consume an xAI context reference without importing private xAI modules."""
10
+
11
+ def event(
12
+ self, payload: Mapping[str, object], *, scope: str, provenance_ref: str | None = None
13
+ ) -> BehaviorEvent:
14
+ raw_type = str(payload.get("event_type", EventType.CUSTOM.value))
15
+ try:
16
+ event_type = EventType(raw_type)
17
+ except ValueError:
18
+ event_type = EventType.CUSTOM
19
+ return BehaviorEvent(
20
+ event_type,
21
+ scope=scope,
22
+ node_name=_text(payload.get("node_name")),
23
+ tool_name=_text(payload.get("tool_name")),
24
+ agent_name=_text(payload.get("agent_name")),
25
+ target_agent=_text(payload.get("target_agent")),
26
+ metadata=dict(payload),
27
+ provenance_ref=provenance_ref,
28
+ )
29
+
30
+ @staticmethod
31
+ def instrument_graph(
32
+ graph: object,
33
+ *,
34
+ application_id: str = "behaviorweave",
35
+ tenant_id: str = "default",
36
+ graph_id: str = "graph",
37
+ ) -> object:
38
+ """Instrument a compiled graph through langgraph-xai's public runtime API."""
39
+ from langgraph_xai import XAIRuntime
40
+
41
+ runtime = XAIRuntime(application_id=application_id, tenant_id=tenant_id, graph_id=graph_id)
42
+ return runtime.instrument(graph)
43
+
44
+
45
+ def _text(value: object) -> str | None:
46
+ return value if isinstance(value, str) else None
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field
5
+ from enum import StrEnum
6
+
7
+ from .events import BehaviorEvent
8
+ from .state import BehaviorState
9
+
10
+
11
+ class InterventionType(StrEnum):
12
+ NOOP = "noop"
13
+ NUDGE = "nudge"
14
+ WARNING = "warning"
15
+ REDIRECT = "redirect"
16
+ RETRY = "retry"
17
+ ESCALATE = "escalate"
18
+ HUMAN_REVIEW = "human_review"
19
+ FORCE_SYNTHESIS = "force_synthesis"
20
+ PAUSE = "pause"
21
+ STOP = "stop"
22
+ CUSTOM = "custom"
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class Intervention:
27
+ kind: InterventionType
28
+ message: str | None = None
29
+ reason: str = ""
30
+ pattern: str | None = None
31
+ policy: str | None = None
32
+ scope: str | None = None
33
+ severity: str = "info"
34
+ metadata: Mapping[str, object] = field(default_factory=dict)
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Explanation:
39
+ pattern: str
40
+ count: int
41
+ threshold: int | None
42
+ policy: str | None
43
+ reason: str
44
+ provenance_ref: str | None = None
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class InterventionDecision:
49
+ intervention: Intervention
50
+ explanation: Explanation | None = None
51
+ suppressed: bool = False
52
+
53
+
54
+ @dataclass(frozen=True, slots=True)
55
+ class AuditRecord:
56
+ """Immutable observable policy audit record; never contains chain-of-thought."""
57
+
58
+ event: BehaviorEvent
59
+ pattern: str | None
60
+ state: BehaviorState | None
61
+ decision: InterventionDecision
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Protocol
5
+
6
+ from .events import BehaviorEvent, EventType, Outcome
7
+ from .state import BehaviorState, BehaviorStateStore, advance_state
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class PatternObservation:
12
+ pattern_id: str
13
+ scope: str
14
+ fingerprint: str
15
+ state_key: str
16
+ count: int
17
+ crossed: bool
18
+ state: BehaviorState
19
+ reason: str
20
+
21
+
22
+ class Pattern(Protocol):
23
+ @property
24
+ def pattern_id(self) -> str: ...
25
+
26
+ def matches(self, event: BehaviorEvent) -> bool: ...
27
+ def observe(self, event: BehaviorEvent, store: BehaviorStateStore) -> PatternObservation: ...
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class ConsecutivePattern:
32
+ pattern_id: str
33
+ event_types: frozenset[EventType]
34
+ outcome: Outcome | None = None
35
+ identity_field: str = "identity"
36
+
37
+ def matches(self, event: BehaviorEvent) -> bool:
38
+ return event.event_type in self.event_types and (
39
+ self.outcome is None or event.outcome is self.outcome
40
+ )
41
+
42
+ def observe(self, event: BehaviorEvent, store: BehaviorStateStore) -> PatternObservation:
43
+ fingerprint = event.identity()
44
+ key = f"{event.scope}:{self.pattern_id}"
45
+ previous = store.get(key)
46
+ state = store.update(
47
+ key,
48
+ lambda current: advance_state(
49
+ current,
50
+ pattern_id=self.pattern_id,
51
+ scope=event.scope,
52
+ fingerprint=fingerprint,
53
+ event_id=event.idempotency_key(),
54
+ timestamp=event.timestamp,
55
+ ),
56
+ )
57
+ return PatternObservation(
58
+ self.pattern_id,
59
+ event.scope,
60
+ fingerprint,
61
+ key,
62
+ state.count,
63
+ state.count > (previous.count if previous else 0),
64
+ state,
65
+ f"{self.pattern_id} observed {state.count} consecutive times",
66
+ )
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class FrequencyPattern:
71
+ pattern_id: str
72
+ event_types: frozenset[EventType]
73
+ window_size: int = 10
74
+
75
+ def matches(self, event: BehaviorEvent) -> bool:
76
+ return event.event_type in self.event_types
77
+
78
+ def observe(self, event: BehaviorEvent, store: BehaviorStateStore) -> PatternObservation:
79
+ fingerprint = event.identity()
80
+ key = f"{event.scope}:{self.pattern_id}:{fingerprint}"
81
+ state = store.update(
82
+ key,
83
+ lambda current: advance_state(
84
+ current,
85
+ pattern_id=self.pattern_id,
86
+ scope=event.scope,
87
+ fingerprint=fingerprint,
88
+ event_id=event.idempotency_key(),
89
+ timestamp=event.timestamp,
90
+ consecutive=False,
91
+ ),
92
+ )
93
+ return PatternObservation(
94
+ self.pattern_id,
95
+ event.scope,
96
+ fingerprint,
97
+ key,
98
+ state.count,
99
+ True,
100
+ state,
101
+ f"{fingerprint} occurred {state.count} times",
102
+ )
103
+
104
+
105
+ def built_in_patterns() -> tuple[Pattern, ...]:
106
+ return (
107
+ ConsecutivePattern("repeated_tool_call", frozenset({EventType.TOOL_CALL})),
108
+ ConsecutivePattern("repeated_node_execution", frozenset({EventType.NODE_EXECUTION})),
109
+ ConsecutivePattern("failure_streak", frozenset({EventType.OUTCOME}), Outcome.FAILURE),
110
+ ConsecutivePattern(
111
+ "retry_streak", frozenset({EventType.RETRY, EventType.OUTCOME}), Outcome.RETRY
112
+ ),
113
+ ConsecutivePattern("success_streak", frozenset({EventType.OUTCOME}), Outcome.SUCCESS),
114
+ ConsecutivePattern("delegation_streak", frozenset({EventType.DELEGATION})),
115
+ FrequencyPattern("event_frequency", frozenset(set(EventType))),
116
+ )
@@ -0,0 +1,81 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable
4
+ from dataclasses import dataclass
5
+ from datetime import timedelta
6
+
7
+ from .interventions import Explanation, Intervention, InterventionDecision, InterventionType
8
+ from .patterns import PatternObservation
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class PolicyRule:
13
+ policy_id: str
14
+ pattern_id: str
15
+ threshold: int
16
+ intervention: InterventionType
17
+ priority: int = 0
18
+ cooldown: timedelta | None = None
19
+ once_only: bool = False
20
+ message: str | None = None
21
+ severity: str = "info"
22
+
23
+
24
+ class PolicyEngine:
25
+ def __init__(self, rules: Iterable[PolicyRule] = ()) -> None:
26
+ self.rules = tuple(rules)
27
+
28
+ def evaluate(self, observation: PatternObservation) -> InterventionDecision:
29
+ candidates = [
30
+ r
31
+ for r in self.rules
32
+ if r.pattern_id == observation.pattern_id and observation.count >= r.threshold
33
+ ]
34
+ if not candidates:
35
+ return InterventionDecision(
36
+ Intervention(
37
+ InterventionType.NOOP, pattern=observation.pattern_id, scope=observation.scope
38
+ )
39
+ )
40
+ rule = max(
41
+ candidates,
42
+ key=lambda r: (
43
+ r.priority,
44
+ r.threshold,
45
+ r.intervention in {InterventionType.STOP, InterventionType.PAUSE},
46
+ ),
47
+ )
48
+ state = observation.state
49
+ already = rule.policy_id in state.intervention_history
50
+ active = (
51
+ state.cooldown_until is not None
52
+ and state.last_seen is not None
53
+ and state.cooldown_until > state.last_seen
54
+ )
55
+ if (rule.once_only and already) or active:
56
+ return InterventionDecision(
57
+ Intervention(
58
+ InterventionType.NOOP,
59
+ reason="cooldown or once-only",
60
+ pattern=rule.pattern_id,
61
+ policy=rule.policy_id,
62
+ scope=observation.scope,
63
+ ),
64
+ suppressed=True,
65
+ )
66
+ reason = rule.message or observation.reason
67
+ intervention = Intervention(
68
+ rule.intervention,
69
+ message=rule.message,
70
+ reason=reason,
71
+ pattern=rule.pattern_id,
72
+ policy=rule.policy_id,
73
+ scope=observation.scope,
74
+ severity=rule.severity,
75
+ )
76
+ return InterventionDecision(
77
+ intervention,
78
+ Explanation(
79
+ observation.pattern_id, observation.count, rule.threshold, rule.policy_id, reason
80
+ ),
81
+ )
behaviorweave/py.typed ADDED
File without changes
behaviorweave/state.py ADDED
@@ -0,0 +1,130 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import json
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass, field, replace
7
+ from datetime import UTC, datetime, timedelta
8
+ from threading import RLock
9
+ from typing import Protocol
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class BehaviorState:
14
+ pattern_id: str
15
+ scope: str
16
+ count: int = 0
17
+ first_seen: datetime | None = None
18
+ last_seen: datetime | None = None
19
+ previous_fingerprint: str | None = None
20
+ current_fingerprint: str | None = None
21
+ event_count: int = 0
22
+ window_start: datetime | None = None
23
+ window_end: datetime | None = None
24
+ threshold_state: bool = False
25
+ cooldown_until: datetime | None = None
26
+ intervention_history: tuple[str, ...] = ()
27
+ seen_event_ids: tuple[str, ...] = ()
28
+ metadata: dict[str, object] = field(default_factory=dict)
29
+ version: int = 0
30
+
31
+ def json(self) -> str:
32
+ data = (
33
+ {**self.__dict__}
34
+ if hasattr(self, "__dict__")
35
+ else {name: getattr(self, name) for name in self.__dataclass_fields__}
36
+ )
37
+ for key in ("first_seen", "last_seen", "window_start", "window_end", "cooldown_until"):
38
+ if data[key]:
39
+ data[key] = data[key].isoformat()
40
+ return json.dumps(data, sort_keys=True)
41
+
42
+
43
+ class BehaviorStateStore(Protocol):
44
+ def get(self, key: str) -> BehaviorState | None: ...
45
+ def update(
46
+ self, key: str, fn: Callable[[BehaviorState | None], BehaviorState]
47
+ ) -> BehaviorState: ...
48
+ def put(self, key: str, state: BehaviorState) -> None: ...
49
+ def delete(self, key: str) -> None: ...
50
+
51
+
52
+ class InMemoryBehaviorStateStore:
53
+ def __init__(self, ttl: timedelta | None = None) -> None:
54
+ self._states: dict[str, tuple[BehaviorState, datetime | None]] = {}
55
+ self._lock = RLock()
56
+ self._ttl = ttl
57
+
58
+ def get(self, key: str) -> BehaviorState | None:
59
+ with self._lock:
60
+ entry = self._states.get(key)
61
+ if entry is None:
62
+ return None
63
+ state, expires = entry
64
+ if expires and expires <= datetime.now(UTC):
65
+ del self._states[key]
66
+ return None
67
+ return copy.deepcopy(state)
68
+
69
+ def put(self, key: str, state: BehaviorState) -> None:
70
+ with self._lock:
71
+ expires = datetime.now(UTC) + self._ttl if self._ttl else None
72
+ self._states[key] = (copy.deepcopy(state), expires)
73
+
74
+ def update(
75
+ self, key: str, fn: Callable[[BehaviorState | None], BehaviorState]
76
+ ) -> BehaviorState:
77
+ with self._lock:
78
+ current = self.get(key)
79
+ updated = fn(current)
80
+ if updated.count < 0:
81
+ raise ValueError("behavior state count cannot be negative")
82
+ self.put(key, updated)
83
+ return copy.deepcopy(updated)
84
+
85
+ def delete(self, key: str) -> None:
86
+ with self._lock:
87
+ self._states.pop(key, None)
88
+
89
+
90
+ def advance_state(
91
+ current: BehaviorState | None,
92
+ *,
93
+ pattern_id: str,
94
+ scope: str,
95
+ fingerprint: str,
96
+ event_id: str,
97
+ timestamp: datetime,
98
+ consecutive: bool = True,
99
+ ) -> BehaviorState:
100
+ if current and event_id in current.seen_event_ids:
101
+ return current
102
+ same = current is not None and current.current_fingerprint == fingerprint
103
+ count = (current.count + 1) if current and (same or not consecutive) else 1
104
+ seen = ((current.seen_event_ids if current else ()) + (event_id,))[-256:]
105
+ return BehaviorState(
106
+ pattern_id=pattern_id,
107
+ scope=scope,
108
+ count=count,
109
+ first_seen=current.first_seen if current and count > 1 else timestamp,
110
+ last_seen=timestamp,
111
+ previous_fingerprint=current.current_fingerprint if current else None,
112
+ current_fingerprint=fingerprint,
113
+ event_count=(current.event_count if current else 0) + 1,
114
+ window_start=current.window_start if current and count > 1 else timestamp,
115
+ window_end=timestamp,
116
+ threshold_state=current.threshold_state if current else False,
117
+ cooldown_until=current.cooldown_until if current else None,
118
+ intervention_history=current.intervention_history if current else (),
119
+ seen_event_ids=seen,
120
+ metadata=current.metadata if current else {},
121
+ version=(current.version if current else 0) + 1,
122
+ )
123
+
124
+
125
+ def with_cooldown(state: BehaviorState, until: datetime, intervention: str) -> BehaviorState:
126
+ return replace(
127
+ state,
128
+ cooldown_until=until,
129
+ intervention_history=(*state.intervention_history, intervention),
130
+ )
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.5
2
+ Name: behaviorweave
3
+ Version: 0.1.0
4
+ Summary: Behavioral policy and intervention framework for LangGraph and LangChain agents.
5
+ Author: S Muni Harish
6
+ License: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: agents,behavior,intervention,langchain,langgraph,policy
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Typing :: Typed
13
+ Requires-Python: <3.13,>=3.12
14
+ Requires-Dist: langchain>=1.0
15
+ Requires-Dist: langgraph-xai>=0.1.0
16
+ Requires-Dist: langgraph>=1.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: black>=25.0; extra == 'dev'
19
+ Requires-Dist: hypothesis>=6.0; extra == 'dev'
20
+ Requires-Dist: langchain[mcp]>=1.4; extra == 'dev'
21
+ Requires-Dist: mkdocs-material>=9.0; extra == 'dev'
22
+ Requires-Dist: mkdocs>=1.6; extra == 'dev'
23
+ Requires-Dist: pyrefly>=0.18; extra == 'dev'
24
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
25
+ Requires-Dist: pytest>=8.0; extra == 'dev'
26
+ Requires-Dist: ruff>=0.9; extra == 'dev'
27
+ Provides-Extra: examples
28
+ Requires-Dist: deepagents; extra == 'examples'
29
+ Requires-Dist: langgraph-swarm; extra == 'examples'
30
+ Provides-Extra: mcp
31
+ Requires-Dist: langchain[mcp]>=1.4; extra == 'mcp'
32
+ Provides-Extra: real-model
33
+ Requires-Dist: langchain-openai>=1.0; extra == 'real-model'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # BehaviorWeave
37
+
38
+ Behavioral policy and intervention framework for LangGraph and LangChain agents.
39
+
40
+ BehaviorWeave observes normalized execution events, detects deterministic behavioral
41
+ patterns, evaluates explicit policies, and emits intervention decisions. It does not
42
+ execute interventions, replace LangGraph, capture chain-of-thought, or require LangSmith.
43
+
44
+ ## Why BehaviorWeave?
45
+
46
+ Agent frameworks are designed to execute models, tools, routing, and graph transitions.
47
+ They intentionally leave application-specific behavioral governance to the host system.
48
+ That creates a gap when an otherwise capable agent starts repeating a tool call, cycling
49
+ through retries, repeatedly delegating work, or continuing after a failure streak.
50
+
51
+ BehaviorWeave fills that gap with a small, deterministic policy layer:
52
+
53
+ - **Make recurring behavior explicit.** Normalize observable tool calls, node execution,
54
+ outcomes, retries, and delegations into events that can be evaluated consistently.
55
+ - **Keep decisions explainable.** Policies map known patterns and thresholds to a
56
+ structured intervention with the pattern, count, scope, reason, and policy ID.
57
+ - **Preserve framework ownership.** LangChain and LangGraph still own agent execution,
58
+ tool invocation, routing, persistence, and interrupts. Your application decides how
59
+ to apply a `nudge`, `pause`, `human_review`, or `stop` decision.
60
+ - **Avoid prompt-only guardrails.** A prompt can ask an agent not to repeat itself, but
61
+ it cannot provide deterministic, scope-isolated behavioral history at the runtime
62
+ boundary.
63
+ - **Support progressive intervention.** Start with a nudge, escalate after continued
64
+ behavior, or require human review without embedding policy logic into every tool or
65
+ graph node.
66
+
67
+ Use BehaviorWeave when you need deterministic operational controls around observable
68
+ agent behavior. It is not a replacement for model safety controls, authorization,
69
+ schema validation, LangGraph persistence, or a general-purpose event-processing system.
70
+
71
+ ## Architecture
72
+
73
+ ```text
74
+ LangGraph/LangChain -> langgraph-xai context -> BehaviorEvent
75
+ -> fingerprint -> pattern state -> policy -> InterventionDecision -> host runtime
76
+ ```
77
+
78
+ The core is framework-neutral internally. Adapters at `behaviorweave.integrations`
79
+ translate framework callbacks and preserve provenance references supplied by
80
+ `langgraph-xai`.
81
+
82
+ ## Quickstart
83
+
84
+ ```python
85
+ from behaviorweave import BehaviorEngine, BehaviorEvent, EventType, PolicyRule, InterventionType
86
+
87
+ engine = BehaviorEngine(
88
+ policies=[PolicyRule("repeat-tool", "repeated_tool_call", 3, InterventionType.NUDGE)]
89
+ )
90
+ for i in range(3):
91
+ decision = engine.process(BehaviorEvent.tool_call("get_alarm", {"machine": "ETCH-3"},
92
+ scope="thread-1"))
93
+ assert decision.intervention.kind is InterventionType.NUDGE
94
+ ```
95
+
96
+ Install with `uv sync`; see [docs](docs/index.md) for the full architecture and integrations.
97
+
98
+ ## Live integrations
99
+
100
+ The checked-in tests are deterministic. The real execution examples construct LangChain
101
+ v1 agents, call actual LangChain tools, and apply BehaviorWeave at the tool/delegation
102
+ boundary. See [live examples](docs/live-examples.md) for the opt-in real model setup;
103
+ provider credentials are read only from the environment.
104
+
105
+ ## License
106
+
107
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,19 @@
1
+ behaviorweave/__init__.py,sha256=RL6IZoOcehapokpF3TxlpBDS3gTHOkyxQjG5pnqRuxo,795
2
+ behaviorweave/engine.py,sha256=qI2WTnQVZeYSf0-hhKP1LYAykbaDRIbk1hgFAQyvfLw,2392
3
+ behaviorweave/events.py,sha256=pLBd9S69zKAXjzwe4LRshMu_535BYsgz5PL3JiOaOMs,3871
4
+ behaviorweave/interventions.py,sha256=S6sCWMrXYQ-36AKmL-8tghAyW1Bww1R3kKKFHPdIAhg,1509
5
+ behaviorweave/patterns.py,sha256=iSEdpzOoS3IEaEcChuPu5OivZofxrUgknqirAS0XHaU,3881
6
+ behaviorweave/policies.py,sha256=DZQBvAdQdVRCPNfFQz1iFaB0FLwzYlUk4-HXyQMETIE,2722
7
+ behaviorweave/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ behaviorweave/state.py,sha256=PZrlok9Fo88wIvMmePOuy5Olf548jXvPvIlLcRdParE,4732
9
+ behaviorweave/integrations/__init__.py,sha256=NbCvMM3_fyEf1fHqJkZZm9ySSDUvnfpDbgGIh1bBc6o,41
10
+ behaviorweave/integrations/langchain/__init__.py,sha256=XLWYK4e20AUTUWaojQDBlfDD0y6jOfy4jtyH-mPc-4M,83
11
+ behaviorweave/integrations/langchain/adapter.py,sha256=IqazjclFG-VhPa8NNgEtU3sgmqM3yCrPuAwoz8Pn9Zs,817
12
+ behaviorweave/integrations/langgraph/__init__.py,sha256=6zBXtF-6uFfQ4CBvxrrDbgKlSEnH8Nc32Jai3dxLfSg,83
13
+ behaviorweave/integrations/langgraph/adapter.py,sha256=CjwVIyMgbfpW8D3N6OSGlLU6dwXAd-kMzT41Re1VPXM,915
14
+ behaviorweave/integrations/langgraph_xai/__init__.py,sha256=h3Mg6Y6-Vcvx9sbkToJyR2wJIayQ_oB32lOP5WiMCbA,89
15
+ behaviorweave/integrations/langgraph_xai/adapter.py,sha256=lM1x1Fj98WqtSlxNpcSATtteAH2WYyRP3E8fD7PRvA4,1593
16
+ behaviorweave-0.1.0.dist-info/METADATA,sha256=mu6GrmE6aPVKKxRkjtT-3L83fCut_0zvYRfbZgLTDLI,4688
17
+ behaviorweave-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
18
+ behaviorweave-0.1.0.dist-info/licenses/LICENSE,sha256=Dn-qZoMNVTHD58VIaIgQoMowI7-pUQ69KxOPJyikfZw,5890
19
+ behaviorweave-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,89 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ "You" shall mean an individual or Legal Entity exercising permissions granted by this License.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work.
71
+
72
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, provided that You meet the following conditions:
73
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
74
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
75
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices.
76
+
77
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You shall be under the terms and conditions of this License.
78
+
79
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor.
80
+
81
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
82
+
83
+ 8. Limitation of Liability. In no event and under no legal theory shall any Contributor be liable to You for damages arising from this License.
84
+
85
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work, You may offer and charge for support, warranty, indemnity, or other liability obligations.
86
+
87
+ END OF TERMS AND CONDITIONS
88
+
89
+ Copyright 2026 Muni Harish