loopgrid-claude-agent 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,12 @@
1
+ """LoopGrid native Claude Agent SDK integration."""
2
+ from .integration import (
3
+ FRAMEWORK, VERSION, EvidenceGateError, EvidencePersistenceError,
4
+ LoopGridClaudeAgent, LoopGridClaudeHooks, ReviewVerdict,
5
+ InMemoryAuthorizationStore, SQLiteAuthorizationStore,
6
+ MemoryClaimStore, SQLiteClaimStore,
7
+ )
8
+
9
+ __all__ = ['FRAMEWORK', 'VERSION', 'EvidenceGateError', 'EvidencePersistenceError',
10
+ 'LoopGridClaudeAgent', 'LoopGridClaudeHooks', 'ReviewVerdict',
11
+ 'InMemoryAuthorizationStore', 'SQLiteAuthorizationStore',
12
+ 'MemoryClaimStore', 'SQLiteClaimStore']
@@ -0,0 +1,195 @@
1
+ """Pluggable, atomic authorization counters for LoopGrid Claude Agent SDK.
2
+
3
+ The SQLite store supports independent processes sharing a *local* filesystem
4
+ (database on a network filesystem is not a supported distributed lock). The
5
+ application and database permissions must protect this trusted state.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import sqlite3
10
+ import threading
11
+ from dataclasses import dataclass, replace
12
+ from contextlib import closing
13
+ from pathlib import Path
14
+ from typing import Protocol, Any, Callable
15
+
16
+
17
+ class AuthorizationDenied(RuntimeError):
18
+ """Authorization is absent, mismatched or already consumed."""
19
+
20
+
21
+ @dataclass
22
+ class ActionState:
23
+ name: str
24
+ arguments_sha256: str
25
+ limit: int
26
+ remaining: int
27
+ policy: str | None = None
28
+ approved: bool = False
29
+ rejected: bool = False
30
+
31
+
32
+ class AuthorizationStore(Protocol):
33
+ def register(self, workspace: str, decision: str, name: str, args_sha256: str, limit: int) -> None: ...
34
+ def get(self, workspace: str, decision: str) -> ActionState | None: ...
35
+ def set_policy(self, workspace: str, decision: str, verdict: str) -> None: ...
36
+ def set_review(self, workspace: str, decision: str, approved: bool) -> None: ...
37
+ def reserve(self, workspace: str, decision: str, name: str, args_sha256: str) -> int: ...
38
+
39
+
40
+ def _check(action: ActionState | None, name: str, args_sha256: str) -> None:
41
+ if action is None:
42
+ raise AuthorizationDenied("decision not bound to an authorized action")
43
+ if name != action.name or args_sha256 != action.arguments_sha256:
44
+ raise AuthorizationDenied("tool name or arguments differ from authorized decision")
45
+ if action.rejected:
46
+ raise AuthorizationDenied("host reviewer rejected the action")
47
+ if not (action.policy == 'auto_allowed' or
48
+ (action.policy == 'human_approval_required' and action.approved)):
49
+ raise AuthorizationDenied("persisted policy or approved human review required")
50
+ if action.remaining <= 0:
51
+ raise AuthorizationDenied("authorized invocation limit reached")
52
+
53
+
54
+ class InMemoryAuthorizationStore:
55
+ """Atomic within one Python process, not across restarts/workers."""
56
+ def __init__(self) -> None:
57
+ self._actions: dict[tuple[str, str], ActionState] = {}
58
+ self._lock = threading.RLock()
59
+
60
+ def register(self, workspace: str, decision: str, name: str, args_sha256: str, limit: int) -> None:
61
+ with self._lock:
62
+ key = workspace, decision
63
+ old = self._actions.get(key)
64
+ if old:
65
+ if (old.name, old.arguments_sha256, old.limit) != (name, args_sha256, limit):
66
+ raise ValueError("decision ID already has a different authorized action")
67
+ return
68
+ self._actions[key] = ActionState(name, args_sha256, limit, limit)
69
+
70
+ def get(self, workspace: str, decision: str) -> ActionState | None:
71
+ with self._lock:
72
+ action = self._actions.get((workspace, decision))
73
+ return replace(action) if action else None
74
+
75
+ def set_policy(self, workspace: str, decision: str, verdict: str) -> None:
76
+ with self._lock:
77
+ action = self._actions.get((workspace, decision))
78
+ if not action:
79
+ raise ValueError('unknown decision')
80
+ if action.policy is not None:
81
+ raise ValueError('policy already recorded for this decision')
82
+ action.policy = verdict
83
+
84
+ def set_review(self, workspace: str, decision: str, approved: bool) -> None:
85
+ with self._lock:
86
+ action = self._actions.get((workspace, decision))
87
+ if not action or action.policy != 'human_approval_required':
88
+ raise ValueError('human review requires a human_approval_required policy')
89
+ if action.approved or action.rejected:
90
+ raise ValueError('review already resolved')
91
+ action.approved = approved
92
+ action.rejected = not approved
93
+
94
+ def reserve(self, workspace: str, decision: str, name: str, args_sha256: str) -> int:
95
+ with self._lock:
96
+ action = self._actions.get((workspace, decision))
97
+ _check(action, name, args_sha256)
98
+ assert action is not None
99
+ action.remaining -= 1
100
+ return action.limit - action.remaining
101
+
102
+
103
+ class SQLiteAuthorizationStore:
104
+ """SQLite-backed single-host authorization ledger with atomic reservations.
105
+
106
+ Use a stable absolute path on local disk, provision secure file/directory
107
+ permissions, and use the same path across processes. A consumed reservation
108
+ remains consumed after a crash (no automatic replay of side effects).
109
+ Policy/review writes to Core and this store are not a distributed transaction;
110
+ any interruption in the middle requires operator reconciliation, never a
111
+ guessed approval or reset of consumed invocations.
112
+ """
113
+ def __init__(self, path: str | Path) -> None:
114
+ if str(path) == ':memory:':
115
+ raise ValueError('SQLiteAuthorizationStore requires a persistent file path')
116
+ self.path = str(Path(path).expanduser().resolve())
117
+ with closing(self._connect()) as conn:
118
+ conn.execute('''CREATE TABLE IF NOT EXISTS authorizations (
119
+ workspace TEXT NOT NULL, decision TEXT NOT NULL,
120
+ tool TEXT NOT NULL, args_sha256 TEXT NOT NULL,
121
+ call_limit INTEGER NOT NULL CHECK(call_limit>0),
122
+ remaining INTEGER NOT NULL CHECK(remaining>=0),
123
+ policy TEXT, approved INTEGER NOT NULL DEFAULT 0,
124
+ rejected INTEGER NOT NULL DEFAULT 0,
125
+ PRIMARY KEY(workspace, decision)
126
+ )''')
127
+
128
+ def _connect(self) -> sqlite3.Connection:
129
+ conn = sqlite3.connect(self.path, timeout=15, isolation_level=None)
130
+ conn.execute('PRAGMA busy_timeout=15000')
131
+ return conn
132
+
133
+ def _transaction(self, fn: Callable[[sqlite3.Connection], Any]) -> Any:
134
+ with closing(self._connect()) as conn:
135
+ conn.execute('BEGIN IMMEDIATE')
136
+ try:
137
+ result = fn(conn)
138
+ conn.execute('COMMIT')
139
+ return result
140
+ except BaseException:
141
+ conn.execute('ROLLBACK')
142
+ raise
143
+
144
+ @staticmethod
145
+ def _load(conn: sqlite3.Connection, workspace: str, decision: str) -> ActionState | None:
146
+ row = conn.execute('''SELECT tool,args_sha256,call_limit,remaining,policy,approved,rejected
147
+ FROM authorizations WHERE workspace=? AND decision=?''',
148
+ (workspace, decision)).fetchone()
149
+ if row is None:
150
+ return None
151
+ return ActionState(row[0], row[1], row[2], row[3], row[4], bool(row[5]), bool(row[6]))
152
+
153
+ def get(self, workspace: str, decision: str) -> ActionState | None:
154
+ with closing(self._connect()) as conn:
155
+ return self._load(conn, workspace, decision)
156
+
157
+ def register(self, workspace: str, decision: str, name: str, args_sha256: str, limit: int) -> None:
158
+ def op(conn: sqlite3.Connection) -> None:
159
+ old = self._load(conn, workspace, decision)
160
+ if old:
161
+ if (old.name, old.arguments_sha256, old.limit) != (name, args_sha256, limit):
162
+ raise ValueError('decision ID already has a different authorized action')
163
+ return
164
+ conn.execute('''INSERT INTO authorizations
165
+ (workspace,decision,tool,args_sha256,call_limit,remaining) VALUES (?,?,?,?,?,?)''',
166
+ (workspace, decision, name, args_sha256, limit, limit))
167
+ self._transaction(op)
168
+
169
+ def set_policy(self, workspace: str, decision: str, verdict: str) -> None:
170
+ def op(conn: sqlite3.Connection) -> None:
171
+ result = conn.execute('''UPDATE authorizations SET policy=?
172
+ WHERE workspace=? AND decision=? AND policy IS NULL''', (verdict, workspace, decision))
173
+ if result.rowcount != 1:
174
+ raise ValueError('unknown decision or policy already recorded')
175
+ self._transaction(op)
176
+
177
+ def set_review(self, workspace: str, decision: str, approved: bool) -> None:
178
+ def op(conn: sqlite3.Connection) -> None:
179
+ result = conn.execute('''UPDATE authorizations SET approved=?,rejected=?
180
+ WHERE workspace=? AND decision=? AND policy='human_approval_required'
181
+ AND approved=0 AND rejected=0''',
182
+ (int(approved), int(not approved), workspace, decision))
183
+ if result.rowcount != 1:
184
+ raise ValueError('unknown decision, wrong policy, or review already resolved')
185
+ self._transaction(op)
186
+
187
+ def reserve(self, workspace: str, decision: str, name: str, args_sha256: str) -> int:
188
+ def op(conn: sqlite3.Connection) -> int:
189
+ action = self._load(conn, workspace, decision)
190
+ _check(action, name, args_sha256)
191
+ assert action is not None
192
+ conn.execute('''UPDATE authorizations SET remaining=remaining-1
193
+ WHERE workspace=? AND decision=?''', (workspace, decision))
194
+ return action.limit - action.remaining + 1
195
+ return self._transaction(op)
@@ -0,0 +1,153 @@
1
+ """Durable tool-call correlation and reconciliation flags.
2
+
3
+ Claims never automatically expire or reset. An ambiguous timed-out action requires
4
+ an authoritative external receipt before an operator authorizes a new attempt.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from contextlib import closing
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from typing import Protocol
12
+ import sqlite3
13
+ import threading
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class Claim:
18
+ workspace: str
19
+ decision_id: str
20
+ call_id: str
21
+ tool_name: str
22
+ arguments_sha256: str
23
+ state: str # reserved, recorded, reconcile, failed
24
+ result_sha256: str | None = None
25
+
26
+
27
+ class ClaimStore(Protocol):
28
+ def reserve(self, claim: Claim) -> None: ...
29
+ def get(self, workspace: str, decision_id: str, call_id: str) -> Claim | None: ...
30
+ def abort_pre_execution(self, workspace: str, decision_id: str, call_id: str) -> None: ...
31
+ def finish(self, workspace: str, decision_id: str, call_id: str, state: str,
32
+ result_sha256: str | None = None) -> None: ...
33
+ def needing_reconciliation(self, workspace: str) -> list[Claim]: ...
34
+ def successful(self, workspace: str, decision_id: str) -> list[Claim]: ...
35
+
36
+
37
+ class MemoryClaimStore:
38
+ def __init__(self) -> None:
39
+ self._values: dict[tuple[str, str, str], Claim] = {}
40
+ self._lock = threading.RLock()
41
+
42
+ def reserve(self, claim: Claim) -> None:
43
+ with self._lock:
44
+ key = claim.workspace, claim.decision_id, claim.call_id
45
+ if key in self._values:
46
+ raise ValueError('tool-use ID already reserved (replay denied)')
47
+ self._values[key] = claim
48
+
49
+ def get(self, workspace: str, decision_id: str, call_id: str) -> Claim | None:
50
+ with self._lock:
51
+ return self._values.get((workspace, decision_id, call_id))
52
+
53
+ def abort_pre_execution(self, workspace: str, decision_id: str, call_id: str) -> None:
54
+ """Cancel a claim only when the pre-execution authorization was denied."""
55
+ with self._lock:
56
+ key = workspace, decision_id, call_id
57
+ old = self._values.get(key)
58
+ if old is None or old.state != 'reserved':
59
+ raise ValueError('pre-execution claim missing or finalized')
60
+ del self._values[key]
61
+
62
+ def finish(self, workspace: str, decision_id: str, call_id: str, state: str,
63
+ result_sha256: str | None = None) -> None:
64
+ if state not in ('recorded', 'reconcile', 'failed'):
65
+ raise ValueError('invalid claim state')
66
+ with self._lock:
67
+ key = workspace, decision_id, call_id
68
+ old = self._values.get(key)
69
+ if old is None or old.state != 'reserved':
70
+ raise ValueError('claim missing or already finalized')
71
+ from dataclasses import replace
72
+ self._values[key] = replace(old, state=state, result_sha256=result_sha256)
73
+
74
+ def needing_reconciliation(self, workspace: str) -> list[Claim]:
75
+ with self._lock:
76
+ return [v for v in self._values.values()
77
+ if v.workspace == workspace and v.state in ('reserved', 'reconcile', 'failed')]
78
+
79
+ def successful(self, workspace: str, decision_id: str) -> list[Claim]:
80
+ with self._lock:
81
+ return [v for v in self._values.values() if v.workspace == workspace
82
+ and v.decision_id == decision_id and v.state == 'recorded']
83
+
84
+
85
+ class SQLiteClaimStore:
86
+ """Atomic claim uniqueness for multiple processes sharing a *local* SQLite file."""
87
+ def __init__(self, path: str | Path) -> None:
88
+ if str(path) == ':memory:':
89
+ raise ValueError('persistent absolute/local path required')
90
+ self.path = str(Path(path).expanduser().resolve())
91
+ with closing(self._connect()) as conn:
92
+ conn.execute('''CREATE TABLE IF NOT EXISTS claude_tool_claims (
93
+ workspace TEXT NOT NULL, decision TEXT NOT NULL, call_id TEXT NOT NULL,
94
+ tool TEXT NOT NULL, args_sha256 TEXT NOT NULL, state TEXT NOT NULL,
95
+ result_sha256 TEXT,
96
+ PRIMARY KEY(workspace, decision, call_id))''')
97
+
98
+ def _connect(self) -> sqlite3.Connection:
99
+ con = sqlite3.connect(self.path, timeout=15, isolation_level=None)
100
+ con.execute('PRAGMA busy_timeout=15000')
101
+ return con
102
+
103
+ def reserve(self, claim: Claim) -> None:
104
+ with closing(self._connect()) as con:
105
+ con.execute('''INSERT INTO claude_tool_claims
106
+ (workspace,decision,call_id,tool,args_sha256,state)
107
+ VALUES (?,?,?,?,?,?)''',
108
+ (claim.workspace, claim.decision_id, claim.call_id, claim.tool_name,
109
+ claim.arguments_sha256, 'reserved'))
110
+
111
+ @staticmethod
112
+ def _read(row: tuple | None) -> Claim | None:
113
+ return Claim(*row) if row is not None else None
114
+
115
+ def get(self, workspace: str, decision_id: str, call_id: str) -> Claim | None:
116
+ with closing(self._connect()) as con:
117
+ return self._read(con.execute('''SELECT workspace,decision,call_id,tool,args_sha256,state,result_sha256
118
+ FROM claude_tool_claims WHERE workspace=? AND decision=? AND call_id=?''',
119
+ (workspace, decision_id, call_id)).fetchone())
120
+
121
+ def abort_pre_execution(self, workspace: str, decision_id: str, call_id: str) -> None:
122
+ """Atomically cancel a claim denied before tool execution was authorized."""
123
+ with closing(self._connect()) as con:
124
+ n = con.execute("""DELETE FROM claude_tool_claims
125
+ WHERE workspace=? AND decision=? AND call_id=? AND state='reserved'""",
126
+ (workspace, decision_id, call_id)).rowcount
127
+ if n != 1:
128
+ raise ValueError('pre-execution claim missing or finalized')
129
+
130
+ def finish(self, workspace: str, decision_id: str, call_id: str, state: str,
131
+ result_sha256: str | None = None) -> None:
132
+ if state not in ('recorded', 'reconcile', 'failed'):
133
+ raise ValueError('invalid claim state')
134
+ with closing(self._connect()) as con:
135
+ n = con.execute('''UPDATE claude_tool_claims SET state=?,result_sha256=?
136
+ WHERE workspace=? AND decision=? AND call_id=? AND state='reserved' ''',
137
+ (state, result_sha256, workspace, decision_id, call_id)).rowcount
138
+ if n != 1:
139
+ raise ValueError('claim missing or already finalized')
140
+
141
+ def needing_reconciliation(self, workspace: str) -> list[Claim]:
142
+ with closing(self._connect()) as con:
143
+ rows = con.execute('''SELECT workspace,decision,call_id,tool,args_sha256,state,result_sha256
144
+ FROM claude_tool_claims WHERE workspace=? AND state IN ('reserved','reconcile','failed')''',
145
+ (workspace,)).fetchall()
146
+ return [Claim(*row) for row in rows]
147
+
148
+ def successful(self, workspace: str, decision_id: str) -> list[Claim]:
149
+ with closing(self._connect()) as con:
150
+ rows = con.execute('''SELECT workspace,decision,call_id,tool,args_sha256,state,result_sha256
151
+ FROM claude_tool_claims WHERE workspace=? AND decision=? AND state='recorded' ''',
152
+ (workspace, decision_id)).fetchall()
153
+ return [Claim(*row) for row in rows]
@@ -0,0 +1,430 @@
1
+ """Claude Agent SDK native hooks to LoopGrid signed decision evidence.
2
+
3
+ Claude executes tools. Trusted application policy, review, and downstream receipts
4
+ must come from the host, not an agent's generated text. The hook gate runs on
5
+ EVERY tool call and denies anything not explicitly bound to the decision.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import base64
11
+ import dataclasses
12
+ import datetime as dt
13
+ import decimal
14
+ import hashlib
15
+ import json
16
+ import sqlite3
17
+ import threading
18
+ import uuid
19
+ from dataclasses import dataclass
20
+ from typing import Any, AsyncIterator, Awaitable, Callable, Mapping
21
+
22
+ from .authorization import (
23
+ AuthorizationDenied, AuthorizationStore, InMemoryAuthorizationStore,
24
+ SQLiteAuthorizationStore,
25
+ )
26
+ from .claims import Claim, ClaimStore, MemoryClaimStore, SQLiteClaimStore
27
+
28
+ FRAMEWORK = 'claude-agent-sdk'
29
+ VERSION = '0.1.0'
30
+
31
+
32
+ class EvidenceGateError(RuntimeError):
33
+ """An external action must not proceed without required evidence and authority."""
34
+
35
+
36
+ class EvidencePersistenceError(EvidenceGateError):
37
+ """An action may have occurred; post-execution evidence needs reconciliation."""
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ReviewVerdict:
42
+ """Authentic decision supplied by the host's authenticated review service."""
43
+ reviewer_id: str
44
+ approved: bool
45
+ reason: str = ''
46
+
47
+
48
+ ApprovalHandler = Callable[[str, str, Mapping[str, Any]], Awaitable[ReviewVerdict]]
49
+
50
+
51
+ def _required(name: str, value: Any) -> None:
52
+ if value is None or value == '' or value == {} or value == []:
53
+ raise ValueError(f'{name} is required')
54
+
55
+
56
+ def _ready(value: Any) -> Any:
57
+ if value is None or isinstance(value, (bool, str, int, float)):
58
+ return value
59
+ if isinstance(value, decimal.Decimal):
60
+ return {'decimal': str(value)}
61
+ if isinstance(value, (dt.date, dt.time)):
62
+ return {'iso': value.isoformat()}
63
+ if isinstance(value, (bytes, bytearray)):
64
+ return {'base64': base64.b64encode(value).decode('ascii')}
65
+ if isinstance(value, uuid.UUID):
66
+ return str(value)
67
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
68
+ return _ready(dataclasses.asdict(value))
69
+ if hasattr(value, 'model_dump') and callable(value.model_dump):
70
+ return _ready(value.model_dump(mode='json'))
71
+ if isinstance(value, Mapping):
72
+ return {str(k): _ready(v) for k, v in value.items()}
73
+ if isinstance(value, (list, tuple)):
74
+ return [_ready(v) for v in value]
75
+ raise TypeError(f'unsupported evidence value: {type(value).__name__}')
76
+
77
+
78
+ def _canonical(value: Any) -> bytes:
79
+ return json.dumps(_ready(value), sort_keys=True, ensure_ascii=False,
80
+ allow_nan=False, separators=(',', ':')).encode('utf-8')
81
+
82
+
83
+ def _commit(value: Any) -> dict[str, Any]:
84
+ raw = _canonical(value)
85
+ return {'algorithm': 'sha256', 'sha256': hashlib.sha256(raw).hexdigest(), 'bytes': len(raw)}
86
+
87
+
88
+ def _idem(*values: Any) -> str:
89
+ return 'lg-claude-' + hashlib.sha256(_canonical(values)).hexdigest()
90
+
91
+
92
+ def _deny(reason: str) -> dict[str, Any]:
93
+ # Never return an empty dict on a gate error: Claude would continue.
94
+ return {'hookSpecificOutput': {'hookEventName': 'PreToolUse',
95
+ 'permissionDecision': 'deny',
96
+ 'permissionDecisionReason': reason}}
97
+
98
+
99
+ def _halt(reason: str) -> dict[str, Any]:
100
+ # This occurs AFTER an action may have run: do NOT claim the action stopped.
101
+ return {'continue_': False, 'stopReason': reason, 'systemMessage': reason}
102
+
103
+
104
+ class LoopGridClaudeAgent:
105
+ """Bridge for one application-authenticated decision and its native tool hooks."""
106
+
107
+ def __init__(self, *, client: Any | None = None,
108
+ base_url: str = 'http://127.0.0.1:8000', api_key: str | None = None,
109
+ workspace_id: str = 'default', agent_id: str = 'claude-agent',
110
+ authorization_store: AuthorizationStore | None = None,
111
+ claim_store: ClaimStore | None = None) -> None:
112
+ _required('workspace_id', workspace_id)
113
+ _required('agent_id', agent_id)
114
+ if client is None:
115
+ from loopgrid import LoopGrid
116
+ client = LoopGrid(base_url=base_url, api_key=api_key, workspace_id=workspace_id)
117
+ self.client = client
118
+ self.workspace_id = workspace_id
119
+ self.agent_id = agent_id
120
+ self.authorizations = authorization_store or InMemoryAuthorizationStore()
121
+ self.claims = claim_store or MemoryClaimStore()
122
+ self._lock = threading.RLock()
123
+
124
+ @classmethod
125
+ def with_sqlite(cls, *, sqlite_path: str, **kwargs: Any) -> 'LoopGridClaudeAgent':
126
+ """Use one durable local SQLite file for both authorization and claim ledgers."""
127
+ return cls(authorization_store=SQLiteAuthorizationStore(sqlite_path),
128
+ claim_store=SQLiteClaimStore(sqlite_path), **kwargs)
129
+
130
+ def start_decision(self, *, decision_type: str, agent: Mapping[str, Any],
131
+ authority: Mapping[str, Any], model: Mapping[str, Any],
132
+ context: Mapping[str, Any], proposed_action: Mapping[str, Any],
133
+ policy: Mapping[str, Any] | None = None,
134
+ metadata: Mapping[str, Any] | None = None,
135
+ privacy_mode: str = 'redacted',
136
+ idempotency_key: str | None = None,
137
+ max_tool_calls: int = 1) -> dict[str, Any]:
138
+ _required('decision_type', decision_type)
139
+ _required('agent.id', agent.get('id'))
140
+ _required('authority', authority)
141
+ _required('model.name', model.get('name'))
142
+ _required('context', context)
143
+ _required('proposed_action', proposed_action)
144
+ name, args = proposed_action.get('tool'), proposed_action.get('arguments')
145
+ if not isinstance(name, str) or not name.strip():
146
+ raise ValueError('proposed_action.tool must be a nonempty tool name')
147
+ if not isinstance(args, Mapping):
148
+ raise ValueError('proposed_action.arguments must be a mapping')
149
+ if isinstance(max_tool_calls, bool) or not isinstance(max_tool_calls, int) or max_tool_calls < 1:
150
+ raise ValueError('max_tool_calls must be a positive integer')
151
+ meta = {**dict(metadata or {}), 'framework': FRAMEWORK,
152
+ 'integration': 'loopgrid-claude-agent', 'integration_version': VERSION}
153
+ event = self.client.record_decision(
154
+ decision_type=decision_type, agent=dict(agent), authority=dict(authority),
155
+ model=dict(model), context=dict(context), proposed_action=dict(proposed_action),
156
+ metadata=meta, privacy_mode=privacy_mode, idempotency_key=idempotency_key,
157
+ )
158
+ did = event['decision_id']
159
+ self.authorizations.register(self.workspace_id, did, name, _commit(args)['sha256'], max_tool_calls)
160
+ if policy is not None:
161
+ self.record_policy(did, policy)
162
+ return event
163
+
164
+ def record_policy(self, decision_id: str, policy: Mapping[str, Any]) -> Any:
165
+ p = dict(policy)
166
+ if p.get('decision') not in ('auto_allowed', 'human_approval_required', 'blocked'):
167
+ raise ValueError('policy.decision invalid')
168
+ _required('policy_id', p.get('policy_id'))
169
+ _required('policy.version', p.get('version'))
170
+ with self._lock:
171
+ state = self.authorizations.get(self.workspace_id, decision_id)
172
+ if state is None or state.policy is not None:
173
+ raise ValueError('unknown decision or existing policy')
174
+ response = self.client.policy_evaluated(decision_id, p, actor_id=str(p['policy_id']))
175
+ self.authorizations.set_policy(self.workspace_id, decision_id, p['decision'])
176
+ return response
177
+
178
+ def record_human_review(self, decision_id: str, *, reviewer: str,
179
+ approved: bool, reason: str = '') -> Any:
180
+ """Host must authenticate reviewer and supply the authentic verdict."""
181
+ _required('reviewer', reviewer)
182
+ if not isinstance(approved, bool):
183
+ raise ValueError('approved must be a bool')
184
+ with self._lock:
185
+ state = self.authorizations.get(self.workspace_id, decision_id)
186
+ if state is None or state.policy != 'human_approval_required':
187
+ raise ValueError('requires human_approval_required policy')
188
+ if state.approved or state.rejected:
189
+ raise ValueError('review already resolved')
190
+ if approved:
191
+ result = self.client.human_approved(decision_id, reviewer, reason)
192
+ else:
193
+ result = self.client.human_rejected(decision_id, reviewer, reason)
194
+ self.authorizations.set_review(self.workspace_id, decision_id, approved)
195
+ return result
196
+
197
+ def record_observed_outcome(self, decision_id: str, *, outcome: Mapping[str, Any],
198
+ observer: str, receipt_id: str) -> Any:
199
+ _required('observer', observer)
200
+ _required('receipt_id', receipt_id)
201
+ _required('outcome', outcome)
202
+ # An actual observed outcome can exist only after a corresponding tool result
203
+ # was durably recorded. Never fill this from agent-generated claims.
204
+ if not self._has_recorded_call(decision_id):
205
+ raise EvidenceGateError('no persisted tool result for decision; reconcile before outcome')
206
+ return self.client.outcome_observed(decision_id,
207
+ {**dict(outcome), 'observer': observer,
208
+ 'receipt_id': receipt_id}, actor_id=observer)
209
+
210
+ def _has_recorded_call(self, decision_id: str) -> bool:
211
+ # Durable success state survives a process restart in SQLite mode.
212
+ return bool(self.claims.successful(self.workspace_id, decision_id))
213
+
214
+ def pending_reconciliations(self) -> list[Claim]:
215
+ return self.claims.needing_reconciliation(self.workspace_id)
216
+
217
+ def hooks(self, decision_id: str, *, approval_handler: ApprovalHandler | None = None) -> 'LoopGridClaudeHooks':
218
+ if self.authorizations.get(self.workspace_id, decision_id) is None:
219
+ raise ValueError('decision not found in authorization store')
220
+ return LoopGridClaudeHooks(self, decision_id, approval_handler=approval_handler)
221
+
222
+ def get_decision(self, decision_id: str) -> dict[str, Any]:
223
+ return self.client.get_decision(decision_id)
224
+
225
+ def export_evidence(self, decision_id: str, *, include_payloads: bool = True) -> bytes:
226
+ return self.client.export_evidence(decision_id, include_payloads=include_payloads)
227
+
228
+ async def _event(self, decision_id: str, event_type: str, payload: dict[str, Any],
229
+ actor_type: str, actor_id: str, key: str) -> Any:
230
+ return await asyncio.to_thread(self.client.add_event, decision_id, event_type, payload,
231
+ actor_type=actor_type, actor_id=actor_id,
232
+ idempotency_key=key)
233
+
234
+
235
+ class LoopGridClaudeHooks:
236
+ """Native Claude Agent SDK hooks bound to a specific LoopGrid decision.
237
+
238
+ Install via `options()` to register a wildcard gate covering built-in, MCP
239
+ and subagent tool invocations. Do not modify options.hooks after creation.
240
+ """
241
+
242
+ def __init__(self, bridge: LoopGridClaudeAgent, decision_id: str, *,
243
+ approval_handler: ApprovalHandler | None = None) -> None:
244
+ self.bridge = bridge
245
+ self.decision_id = decision_id
246
+ self.approval_handler = approval_handler
247
+ self.last_gate_error: str | None = None
248
+ self.last_post_error: str | None = None
249
+ self._model_ordinal = 0
250
+
251
+ def options(self, **kwargs: Any) -> Any:
252
+ """Construct SDK-native options; narrow allowed tools, no shadowing hooks.
253
+
254
+ Hooks must never be casually merged with arbitrary third-party hooks
255
+ which can rewrite tool_input after an authorization commitment.
256
+ """
257
+ forbidden = {'hooks', 'can_use_tool', 'allowed_tools', 'disallowed_tools',
258
+ 'permission_mode', 'setting_sources'} & set(kwargs)
259
+ if forbidden:
260
+ raise ValueError('security-controlled SDK options cannot be overridden: ' + ', '.join(sorted(forbidden)))
261
+ from claude_agent_sdk import ClaudeAgentOptions, HookMatcher
262
+ state = self.bridge.authorizations.get(self.bridge.workspace_id, self.decision_id)
263
+ if state is None:
264
+ raise ValueError('no authorized decision')
265
+ return ClaudeAgentOptions(
266
+ **kwargs, setting_sources=[], permission_mode='dontAsk',
267
+ allowed_tools=[state.name],
268
+ hooks={
269
+ 'PreToolUse': [HookMatcher(matcher=None, hooks=[self.pre_tool_use])],
270
+ 'PostToolUse': [HookMatcher(matcher=None, hooks=[self.post_tool_use])],
271
+ 'PostToolUseFailure': [HookMatcher(matcher=None, hooks=[self.post_tool_use_failure])],
272
+ },
273
+ )
274
+
275
+ def _validated_call(self, input_data: Mapping[str, Any], tool_use_id: str | None,
276
+ expected_event: str) -> tuple[str, dict[str, Any], str]:
277
+ if input_data.get('hook_event_name') != expected_event:
278
+ raise EvidenceGateError('unexpected SDK hook event')
279
+ name = input_data.get('tool_name')
280
+ args = input_data.get('tool_input')
281
+ uid = tool_use_id or input_data.get('tool_use_id')
282
+ if not isinstance(name, str) or not name.strip():
283
+ raise EvidenceGateError('tool name is missing')
284
+ if not isinstance(args, dict):
285
+ raise EvidenceGateError('tool input must be a mapping')
286
+ if not isinstance(uid, str) or not uid.strip():
287
+ raise EvidenceGateError('tool-use identifier is required for replay protection')
288
+ if tool_use_id and input_data.get('tool_use_id') and tool_use_id != input_data['tool_use_id']:
289
+ raise EvidenceGateError('SDK tool-use identifier mismatch')
290
+ return name, args, uid
291
+
292
+ async def _trusted_review(self, name: str, args: dict[str, Any]) -> None:
293
+ state = self.bridge.authorizations.get(self.bridge.workspace_id, self.decision_id)
294
+ if state is None:
295
+ raise EvidenceGateError('authorization unavailable')
296
+ if state.policy != 'human_approval_required' or state.approved or state.rejected:
297
+ return
298
+ if self.approval_handler is None:
299
+ raise EvidenceGateError('host approval required before execution')
300
+ verdict = await self.approval_handler(self.decision_id, name, args)
301
+ if not isinstance(verdict, ReviewVerdict) or not verdict.reviewer_id or not isinstance(verdict.approved, bool):
302
+ raise EvidenceGateError('host approval handler did not return an authenticated verdict')
303
+ await asyncio.to_thread(self.bridge.record_human_review, self.decision_id,
304
+ reviewer=verdict.reviewer_id, approved=verdict.approved,
305
+ reason=verdict.reason)
306
+ if not verdict.approved:
307
+ raise EvidenceGateError('authenticated host reviewer rejected the tool call')
308
+
309
+ async def pre_tool_use(self, input_data: dict[str, Any], tool_use_id: str | None,
310
+ context: Any) -> dict[str, Any]:
311
+ """Fail-closed before action; return SDK-native PreToolUse deny on any error."""
312
+ try:
313
+ name, args, uid = self._validated_call(input_data, tool_use_id, 'PreToolUse')
314
+ state = self.bridge.authorizations.get(self.bridge.workspace_id, self.decision_id)
315
+ args_hash = _commit(args)['sha256']
316
+ # Refuse mismatched tool/args BEFORE prompting a trusted reviewer.
317
+ if state is None or state.name != name or state.arguments_sha256 != args_hash:
318
+ raise EvidenceGateError('tool name or arguments differ from authorized decision')
319
+ # Do not emit misleading tool_requested evidence or prompt a reviewer
320
+ # when this request is already known to be a replay/over-limit.
321
+ # Atomic claim/counter writes below still enforce concurrent races.
322
+ if state.remaining <= 0:
323
+ raise EvidenceGateError('authorized invocation limit reached')
324
+ if self.bridge.claims.get(self.bridge.workspace_id, self.decision_id, uid) is not None:
325
+ raise EvidenceGateError('tool-use identifier already reserved (replay denied)')
326
+ await self._trusted_review(name, args)
327
+ common = {'framework': FRAMEWORK,
328
+ 'source': 'claude_agent_sdk.PreToolUse',
329
+ 'tool_name': name, 'tool_use_id': uid,
330
+ 'session_id': str(input_data.get('session_id') or ''),
331
+ 'agent_id': str(input_data.get('agent_id') or self.bridge.agent_id),
332
+ 'arguments_commitment': _commit(args)}
333
+ # Core may refuse tool_requested while blocked/awaiting review.
334
+ # Such a failure MUST deny the action.
335
+ await self.bridge._event(self.decision_id, 'tool_requested', common,
336
+ 'tool', name, _idem(self.decision_id, 'request', uid))
337
+ claim = Claim(self.bridge.workspace_id, self.decision_id, uid, name, args_hash, 'reserved')
338
+ self.bridge.claims.reserve(claim)
339
+ # Durable invocation count: no duplicate/replayed invocation after restart.
340
+ # A refused reservation never authorized execution: cancel only this
341
+ # newly created claim to avoid false downstream reconciliation.
342
+ try:
343
+ self.bridge.authorizations.reserve(self.bridge.workspace_id, self.decision_id, name, args_hash)
344
+ except BaseException:
345
+ try:
346
+ self.bridge.claims.abort_pre_execution(self.bridge.workspace_id, self.decision_id, uid)
347
+ except Exception:
348
+ # Cleanup errors preserve the claim for human investigation;
349
+ # they can never turn a denied action into an allowed action.
350
+ pass
351
+ raise
352
+ except Exception as exc:
353
+ self.last_gate_error = f'{type(exc).__name__}: {exc}'
354
+ return _deny('LoopGrid action not authorized or required evidence unavailable; execution denied')
355
+ return {'hookSpecificOutput': {'hookEventName': 'PreToolUse',
356
+ 'permissionDecision': 'allow',
357
+ 'permissionDecisionReason': 'Host policy/review and LoopGrid evidence gate passed'}}
358
+
359
+ def _claim_for_post(self, input_data: dict[str, Any], tool_use_id: str | None,
360
+ expected_event: str) -> tuple[str, dict[str, Any], str, Claim]:
361
+ name, args, uid = self._validated_call(input_data, tool_use_id, expected_event)
362
+ claim = self.bridge.claims.get(self.bridge.workspace_id, self.decision_id, uid)
363
+ if claim is None or claim.state != 'reserved':
364
+ raise EvidenceGateError('tool result has no unique authorized reservation')
365
+ if claim.tool_name != name or claim.arguments_sha256 != _commit(args)['sha256']:
366
+ raise EvidenceGateError('post-tool name/arguments do not match authorized request')
367
+ return name, args, uid, claim
368
+
369
+ async def post_tool_use(self, input_data: dict[str, Any], tool_use_id: str | None,
370
+ context: Any) -> dict[str, Any]:
371
+ """Persist the actual returned tool result before the agent proceeds."""
372
+ uid = str(tool_use_id or input_data.get('tool_use_id') or '')
373
+ try:
374
+ name, args, uid, claim = self._claim_for_post(input_data, tool_use_id, 'PostToolUse')
375
+ result = _commit(input_data.get('tool_response'))
376
+ payload = {'framework': FRAMEWORK, 'source': 'claude_agent_sdk.PostToolUse',
377
+ 'tool_name': name, 'tool_use_id': uid, 'arguments_commitment': _commit(args),
378
+ 'result_commitment': result, 'status': 'returned',
379
+ 'external_outcome_verified': False}
380
+ await self.bridge._event(self.decision_id, 'tool_executed', payload,
381
+ 'tool', name, _idem(self.decision_id, 'executed', uid))
382
+ self.bridge.claims.finish(self.bridge.workspace_id, self.decision_id, uid,
383
+ 'recorded', result['sha256'])
384
+ return {}
385
+ except Exception as exc:
386
+ self.last_post_error = f'{type(exc).__name__}: {exc}'
387
+ # The tool may already have changed external state, so no retry.
388
+ try:
389
+ claim = self.bridge.claims.get(self.bridge.workspace_id, self.decision_id, uid)
390
+ if claim is not None and claim.state == 'reserved':
391
+ self.bridge.claims.finish(self.bridge.workspace_id, self.decision_id, uid, 'reconcile')
392
+ except Exception:
393
+ pass
394
+ return _halt('LoopGrid tool result evidence incomplete after execution; reconcile external state before retry')
395
+
396
+ async def post_tool_use_failure(self, input_data: dict[str, Any], tool_use_id: str | None,
397
+ context: Any) -> dict[str, Any]:
398
+ """Failure is not a successful tool outcome; halt and require review."""
399
+ uid = str(tool_use_id or input_data.get('tool_use_id') or '')
400
+ try:
401
+ _name, _args, uid, _claim = self._claim_for_post(input_data, tool_use_id, 'PostToolUseFailure')
402
+ # CLI reports an error but this does not establish downstream side effects.
403
+ # Do not fabricate tool_executed or outcome_observed events.
404
+ self.bridge.claims.finish(self.bridge.workspace_id, self.decision_id, uid,
405
+ 'failed', _commit(str(input_data.get('error')))['sha256'])
406
+ except Exception as exc:
407
+ self.last_post_error = f'{type(exc).__name__}: {exc}'
408
+ return _halt('Claude tool failed; downstream side effects are unknown; reconcile before retry')
409
+
410
+ async def observe_messages(self, messages: AsyncIterator[Any]) -> AsyncIterator[Any]:
411
+ """Wrap SDK message stream to record authoritative assistant model events.
412
+
413
+ Consumer should *fully exhaust* the iterator to capture all model events.
414
+ """
415
+ async for message in messages:
416
+ if type(message).__name__ == 'AssistantMessage':
417
+ self._model_ordinal += 1
418
+ payload = {'framework': FRAMEWORK, 'source': 'claude_agent_sdk.AssistantMessage',
419
+ 'status': 'completed', 'model': str(getattr(message, 'model', 'unknown')),
420
+ 'response_commitment': _commit(getattr(message, 'content', []))}
421
+ await self.bridge._event(self.decision_id, 'model_completed', payload,
422
+ 'agent', self.bridge.agent_id,
423
+ _idem(self.decision_id, 'assistant', self._model_ordinal))
424
+ yield message
425
+
426
+
427
+ __all__ = ['LoopGridClaudeAgent', 'LoopGridClaudeHooks', 'ReviewVerdict',
428
+ 'EvidenceGateError', 'EvidencePersistenceError',
429
+ 'InMemoryAuthorizationStore', 'SQLiteAuthorizationStore',
430
+ 'MemoryClaimStore', 'SQLiteClaimStore', 'FRAMEWORK', 'VERSION']
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: loopgrid-claude-agent
3
+ Version: 0.1.0
4
+ Summary: Signed decision, policy, approval and tool-action evidence for Claude Agent SDK
5
+ Author: LoopGrid contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://loopgrid.io
8
+ Project-URL: Repository, https://github.com/loopgridio/loopgrid-claude-agent
9
+ Project-URL: Documentation, https://loopgrid.io/integrations/
10
+ Keywords: claude-agent-sdk,anthropic,agent-governance,action-evidence,ed25519,audit-trail
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ License-File: NOTICE.md
21
+ Requires-Dist: loopgrid<0.9,>=0.8.0
22
+ Requires-Dist: claude-agent-sdk<0.3,>=0.2.165
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=8; extra == "dev"
25
+ Requires-Dist: build>=1.2; extra == "dev"
26
+ Requires-Dist: twine>=6; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # LoopGrid × Claude Agent SDK
30
+
31
+ **Verifiable decision evidence and policy enforcement for consequential Claude agent actions.**
32
+
33
+ Give Claude agents the freedom to use real tools—and give your application an independently checkable record of *what was authorized, what ran, and what happened afterward*.
34
+
35
+ **LoopGrid adds a decision-level evidence layer to the native Claude Agent SDK lifecycle:**
36
+
37
+ **Authority → Policy → Human review (when required) → Tool request → Tool execution → Observed outcome → Signed verification**
38
+
39
+ It works with the Claude Agent SDK's built-in and MCP tools, uses native tool hooks, and keeps the Claude model and existing tool implementations in place. LoopGrid Core signs and chains the resulting evidence for independent verification.
40
+
41
+ ## Why LoopGrid
42
+
43
+ A conventional agent trace can describe an interaction. LoopGrid links consequential actions to their authorization and outcome evidence, so an operator or auditor can independently verify the captured record.
44
+
45
+ | Capability | What you get |
46
+ | --- | --- |
47
+ | **Native Claude hooks** | `PreToolUse`, `PostToolUse`, and `PostToolUseFailure` lifecycle integration |
48
+ | **Decision-scoped authorization** | Exact tool-name and canonical-argument matching; fail-closed policy checks before execution |
49
+ | **Human-in-the-loop evidence** | Host-authenticated approval and rejection records when a decision requires review |
50
+ | **Execution provenance** | Correlation by tool-use ID, response commitments, failure reporting, and model-output commitments |
51
+ | **Durable action safety** | One-use authorizations, replay/concurrency protection, optional SQLite persistence across local process restarts |
52
+ | **Outcome evidence** | Separately recorded, host-verified receipts rather than treating model text as a completed action |
53
+ | **Independent verification** | Ed25519 signatures and SHA-256-linked evidence from LoopGrid Core |
54
+ | **Reconciliation** | Explicit handling of uncertain actions when evidence cannot be persisted after tool execution |
55
+
56
+ Designed for teams building Claude agents that act through business APIs, internal tools, MCP servers, and automated workflows—especially where policy, review, and proof matter as much as the model's answer.
57
+
58
+ ## Installation
59
+
60
+ **From the current source checkout:**
61
+
62
+ ```bash
63
+ python -m pip install -e ".[dev]"
64
+ ```
65
+
66
+ **After the public v0.1.0 release:**
67
+
68
+ ```bash
69
+ pip install loopgrid-claude-agent==0.1.0
70
+ ```
71
+
72
+ Requires Python 3.11+, the official `claude-agent-sdk` Python package, the `loopgrid` Python SDK, and a reachable LoopGrid Core instance. The SDK dependencies are declared in `pyproject.toml`.
73
+
74
+ ## Integrate in four steps
75
+
76
+ **1. Create a decision with exact action authority and a policy verdict.** Your trusted application—not the model—chooses the tool, arguments, scope, and policy.
77
+
78
+ ```python
79
+ from loopgrid import LoopGrid
80
+ from loopgrid_claude_agent import LoopGridClaudeAgent
81
+
82
+ workspace_id = "YOUR_EXISTING_WORKSPACE_ID"
83
+ core = LoopGrid(base_url="http://127.0.0.1:8000", workspace_id=workspace_id)
84
+ bridge = LoopGridClaudeAgent(client=core, workspace_id=workspace_id, agent_id="refund-agent")
85
+
86
+ decision_id = bridge.start_decision(
87
+ decision_type="refund_simulation",
88
+ agent={"id": "refund-agent", "version": "1"},
89
+ authority={"acting_for": "sandbox", "scope": ["refund:simulate"]},
90
+ model={"provider": "anthropic", "name": "claude-agent-sdk"},
91
+ context={"prompt_version": "refund-v1"},
92
+ proposed_action={
93
+ "tool": "mcp__loopgrid_sandbox__sandbox_refund",
94
+ "arguments": {"amount": 25},
95
+ },
96
+ policy={"policy_id": "refund-policy", "version": "1", "decision": "auto_allowed"},
97
+ )["decision_id"]
98
+ ```
99
+
100
+ **2. Attach the native enforcement hooks to the Claude session.**
101
+
102
+ ```python
103
+ from claude_agent_sdk import ClaudeSDKClient
104
+
105
+ hooks = bridge.hooks(decision_id)
106
+ options = hooks.options(mcp_servers={"loopgrid_sandbox": your_mcp_server})
107
+
108
+ async with ClaudeSDKClient(options=options) as agent:
109
+ await agent.query("Simulate the authorized refund once using the sandbox tool.")
110
+ async for message in hooks.observe_messages(agent.receive_response()):
111
+ pass
112
+ ```
113
+
114
+ Here, `your_mcp_server` is the SDK MCP server object your application supplies. The hooks deny other tool names, unexpected arguments, and unauthorized repeat calls.
115
+
116
+ **3. Add genuine downstream outcome evidence.**
117
+
118
+ ```python
119
+ # Host application validates a receipt from the actual downstream system.
120
+ bridge.record_observed_outcome(
121
+ decision_id,
122
+ observer="sandbox-ledger",
123
+ receipt_id=verified_receipt["id"],
124
+ outcome=verified_receipt,
125
+ )
126
+ ```
127
+
128
+ `verified_receipt` is supplied by your application after verification—not generated from Claude's summary.
129
+
130
+ **4. Inspect the signed decision record.**
131
+
132
+ ```python
133
+ record = bridge.get_decision(decision_id)
134
+ evidence = bridge.export_evidence(decision_id)
135
+ ```
136
+
137
+ For a **complete runnable example**, including creation of the in-process MCP sandbox tool, workspace setup, lifecycle assertions, and signed verification, use [`examples/native_claude_runtime_e2e.py`](examples/native_claude_runtime_e2e.py).
138
+
139
+ ## Human approval and durable authorization
140
+
141
+ For sensitive actions, record a real host-authenticated approval before execution:
142
+
143
+ ```python
144
+ bridge.record_human_review(
145
+ decision_id,
146
+ reviewer="authenticated-user-123",
147
+ approved=True,
148
+ reason="approved support ticket 123",
149
+ )
150
+ ```
151
+
152
+ Use a decision policy of `human_approval_required` for this path, or pass a host-owned asynchronous `approval_handler` to `bridge.hooks(...)` returning a `ReviewVerdict`. A Claude-generated statement is never accepted as a reviewer identity.
153
+
154
+ For persistence across local worker restarts:
155
+
156
+ ```python
157
+ bridge = LoopGridClaudeAgent.with_sqlite(
158
+ client=core,
159
+ workspace_id=workspace_id,
160
+ agent_id="refund-agent",
161
+ sqlite_path="./loopgrid-claude-authorizations.db",
162
+ )
163
+
164
+ pending = bridge.pending_reconciliations()
165
+ ```
166
+
167
+ Keep the SQLite file secure and reuse the same file across restarted workers. The integration prevents blind re-execution when an action's downstream outcome needs reconciliation.
168
+
169
+ ## See the evidence lifecycle in action
170
+
171
+ ### Offline and real-Core validation — no Claude API credits
172
+
173
+ With LoopGrid Core running at `http://127.0.0.1:8000`:
174
+
175
+ ```bash
176
+ python -m pytest -q
177
+ python examples/native_core_hook_e2e.py
178
+ python examples/native_core_security_e2e.py
179
+ python examples/native_core_recovery_e2e.py
180
+ python examples/offline_core_durability_e2e.py
181
+ ```
182
+
183
+ These exercise native SDK hook construction, deterministic SDK-hook inputs, the real LoopGrid Core, authorization, security scenarios, durability, signed verification, and failure recovery. They do **not** run a Claude model.
184
+
185
+ ### Full Claude model and MCP sandbox example
186
+
187
+ ```bash
188
+ python examples/native_claude_runtime_e2e.py
189
+ ```
190
+
191
+ This exercises an actual Claude SDK session with a harmless in-process MCP refund simulator and real Core. It requires an authenticated Anthropic API account with available credits. The sandbox moves **no real money**.
192
+
193
+ ## Validation status
194
+
195
+ **Validated on Windows with Python 3.12 and Claude Agent SDK 0.2.165:** 59/59 automated tests, six real-Core security scenarios, native hook/Core verification, restart and replay durability, post-execution reconciliation, dependency checks, and wheel/sdist builds with both distributions passing `twine check`.
196
+
197
+ **Live-runtime validation:** The authenticated, model-driven Claude → MCP tool → signed Core verification scenario has not yet been completed because Anthropic API credits were unavailable. The offline, SDK-compatibility, and Core-backed tests above passed. See [`VALIDATION.md`](VALIDATION.md) for the full validation record.
198
+
199
+ ## Documentation
200
+
201
+ - [Integration contract](INTEGRATION-CONTRACT.md) — evidence events, authorization, and hook mapping
202
+ - [Security and trust model](SECURITY.md) — operator-owned approval, tool boundaries, and recovery
203
+ - [Windows validation and clean-wheel check](WINDOWS-VALIDATION.md)
204
+ - [Extended offline validation](OFFLINE-EXTENDED-VALIDATION.md)
205
+ - [LoopGrid](https://loopgrid.io) · [Claude Agent SDK for Python](https://github.com/anthropics/claude-agent-sdk-python) · [Claude SDK hooks](https://code.claude.com/docs/en/agent-sdk/hooks)
206
+
207
+ This is an independently maintained LoopGrid integration for the Claude Agent SDK.
@@ -0,0 +1,10 @@
1
+ loopgrid_claude_agent/__init__.py,sha256=Ay0ISLQD0YDhtp6nvAlmZlllFEvGx53T28Aqh_23sJg,588
2
+ loopgrid_claude_agent/authorization.py,sha256=c7zR-WFESfr4WyYNXvOLLQFDOtTZ43-BiDePa7Ytu5o,9197
3
+ loopgrid_claude_agent/claims.py,sha256=VK3zftRjgwbqa5ND480pCN4GyEV_xcR4_EIzMqzArQ0,7296
4
+ loopgrid_claude_agent/integration.py,sha256=1WPszmidpOpMT2CuKQ_Na7HIHfKZNEp8IGe4SYZVJK4,23335
5
+ loopgrid_claude_agent-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
6
+ loopgrid_claude_agent-0.1.0.dist-info/licenses/NOTICE.md,sha256=rV5n1C_kr3peC8nBKv_5de6XUcRiFow0ipdGC5sctzM,282
7
+ loopgrid_claude_agent-0.1.0.dist-info/METADATA,sha256=O3TZVxJxpAMnVJdKcDBGwuUuDV4LVSWUcWqPB3Lp2W0,9471
8
+ loopgrid_claude_agent-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
+ loopgrid_claude_agent-0.1.0.dist-info/top_level.txt,sha256=HQlF3_fP5WZCKwRSdSQVf9_Ll_tSuP5LAhF_alyXXkM,22
10
+ loopgrid_claude_agent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1,6 @@
1
+ LoopGrid Claude Agent SDK integration
2
+ Copyright 2026 LoopGrid contributors.
3
+ Licensed under the Apache License, Version 2.0.
4
+
5
+ Claude Agent SDK is developed by Anthropic. This package is an independently
6
+ maintained LoopGrid integration, not an Anthropic-published SDK or endorsement.
@@ -0,0 +1 @@
1
+ loopgrid_claude_agent