maigp-claude-agent-sdk 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ .eggs/
9
+
10
+ # Node
11
+ node_modules/
12
+ dist/
13
+
14
+ # Go
15
+ bin/
16
+
17
+ # Rust
18
+ target/
19
+
20
+ # .NET
21
+ bin/
22
+ obj/
23
+
24
+ # Java
25
+ *.class
26
+ out/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+ .kiro/
32
+ *.swp
33
+
34
+ # OS
35
+ .DS_Store
36
+ Thumbs.db
37
+
38
+ # Secrets (never commit)
39
+ .env
40
+ *.pem
41
+ *.key
42
+ *.pdf
43
+ BACKLOG/
44
+ patent/
45
+ docs/.archive/
46
+ review/
47
+
48
+ # Generated navigable spec split — derived from the monoliths by
49
+ # specification/tools/spec_split.py; the manifest + monoliths are the
50
+ # source of truth, not this output. Same convention as Mars (spec/*/*/).
51
+ specification/*/*/
52
+ specification/split-index.md
53
+
54
+ # Local rendering/preview site — self-contained, not part of the
55
+ # published specification, never pushed.
56
+ site/
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.5
2
+ Name: maigp-claude-agent-sdk
3
+ Version: 1.0.0
4
+ Summary: AIGP governance adapter for the Claude Agent SDK (agent-loop level: query/ClaudeSDKClient, tool use). Distinct from aigp-anthropic, which wraps raw Messages API calls.
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: maigp-agent-core>=1.0.0
7
+ Provides-Extra: dev
8
+ Requires-Dist: pytest; extra == 'dev'
9
+ Requires-Dist: pytest-asyncio; extra == 'dev'
@@ -0,0 +1,24 @@
1
+ """AIGP adapter for the Claude Agent SDK (Anthropic).
2
+
3
+ Governs the Claude Agent SDK at the AGENT-LOOP level — the `query()` / `ClaudeSDKClient`
4
+ message stream, including tool-use turns — not just a single Messages API call. (For raw
5
+ `anthropic.messages.create`, use the separate `aigp-anthropic` wrapper.)
6
+
7
+ Usage:
8
+ from claude_agent_sdk import query # Claude Agent SDK
9
+ from aigp_claude_agent_sdk import AigpClaudeAgentGovernance
10
+
11
+ gov = AigpClaudeAgentGovernance(gov_url="https://gov.example.com", app_id="my-agent",
12
+ hmac_secret="secret")
13
+
14
+ async for message in gov.query("Analyze this finding", agent_name="analyst",
15
+ model_id="claude-opus-4-8"):
16
+ ...
17
+ # ✓ CHECK before the stream · tool_use turns governed · usage accumulated · RECORD+TRACE after
18
+ """
19
+
20
+ __version__ = "1.0.0"
21
+
22
+ from .handler import AigpClaudeAgentGovernance
23
+
24
+ __all__ = ["AigpClaudeAgentGovernance"]
@@ -0,0 +1,92 @@
1
+ """Claude Agent SDK governance handler.
2
+
3
+ Wraps the Claude Agent SDK's agent loop (the `query()` async message stream / ClaudeSDKClient)
4
+ with AIGP governance: CHECK before the stream, tool-use governance + usage accumulation as
5
+ messages arrive, RECORD/TRACE at completion.
6
+
7
+ The SDK's ``query`` is injected (duck-typed) so this adapter does not hard-depend on a specific
8
+ SDK version. It inspects streamed messages for ResultMessage usage and ToolUseBlock turns.
9
+ """
10
+
11
+ import logging
12
+
13
+ from aigp_agent_core import AgentGovernance
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _message_usage(message) -> dict:
19
+ """Extract usage from a Claude Agent SDK ResultMessage (or dict)."""
20
+ usage = getattr(message, "usage", None)
21
+ if usage is None and isinstance(message, dict):
22
+ usage = message.get("usage")
23
+ if not usage:
24
+ return {}
25
+ def _get(o, *names):
26
+ for n in names:
27
+ v = o.get(n) if isinstance(o, dict) else getattr(o, n, None)
28
+ if v is not None:
29
+ return v
30
+ return 0
31
+ return {
32
+ "input_tokens": _get(usage, "input_tokens"),
33
+ "output_tokens": _get(usage, "output_tokens"),
34
+ }
35
+
36
+
37
+ def _tool_names(message) -> list[str]:
38
+ """Extract tool_use tool names from a streamed assistant message."""
39
+ names = []
40
+ content = getattr(message, "content", None)
41
+ if content is None and isinstance(message, dict):
42
+ content = message.get("content")
43
+ for block in content or []:
44
+ btype = getattr(block, "type", None) if not isinstance(block, dict) else block.get("type")
45
+ if btype == "tool_use":
46
+ name = getattr(block, "name", None) if not isinstance(block, dict) else block.get("name")
47
+ if name:
48
+ names.append(name)
49
+ return names
50
+
51
+
52
+ class AigpClaudeAgentGovernance:
53
+ """Govern Claude Agent SDK runs with AIGP."""
54
+
55
+ def __init__(self, gov_url: str, app_id: str, hmac_secret: str, *, query=None, **kwargs):
56
+ self._gov = AgentGovernance(gov_url, app_id, hmac_secret, **kwargs)
57
+ self._app_id = app_id
58
+ self._query = query # optional: the SDK's query() coroutine-generator; else import lazily
59
+
60
+ async def query(self, prompt, *, agent_name: str = "", model_id: str = "",
61
+ user_id: str = "", **query_kwargs):
62
+ """Governed Claude Agent SDK query. Async-generator mirroring the SDK's `query()`.
63
+
64
+ Yields each streamed message; governs tool-use turns; on completion sends RECORD/TRACE
65
+ with accumulated usage. On error, reports and re-raises.
66
+ """
67
+ name = agent_name or self._app_id
68
+ self._gov.pre_invoke(name, str(model_id), user_id)
69
+ total = {"input_tokens": 0, "output_tokens": 0}
70
+ try:
71
+ async for message in self._invoke_query(prompt, **query_kwargs):
72
+ for tool in _tool_names(message):
73
+ await self._gov.on_tool_call(tool)
74
+ u = _message_usage(message)
75
+ if u:
76
+ total["input_tokens"] += u.get("input_tokens", 0)
77
+ total["output_tokens"] += u.get("output_tokens", 0)
78
+ yield message
79
+ self._gov.on_model_call(usage=total)
80
+ await self._gov.post_invoke()
81
+ except Exception as e:
82
+ await self._gov.on_error(e)
83
+ raise
84
+
85
+ async def _invoke_query(self, prompt, **kw):
86
+ if self._query is not None:
87
+ async for m in self._query(prompt=prompt, **kw):
88
+ yield m
89
+ return
90
+ from claude_agent_sdk import query # type: ignore
91
+ async for m in query(prompt=prompt, **kw):
92
+ yield m
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "maigp-claude-agent-sdk"
7
+ version = "1.0.0"
8
+ description = "AIGP governance adapter for the Claude Agent SDK (agent-loop level: query/ClaudeSDKClient, tool use). Distinct from aigp-anthropic, which wraps raw Messages API calls."
9
+ requires-python = ">=3.11"
10
+ dependencies = ["maigp-agent-core>=1.0.0"]
11
+
12
+ [project.optional-dependencies]
13
+ dev = ["pytest", "pytest-asyncio"]
14
+
15
+ [tool.hatch.build.targets.wheel]
16
+ packages = ["aigp_claude_agent_sdk"]
File without changes
@@ -0,0 +1,62 @@
1
+ """Tests for the AIGP Claude Agent SDK adapter — mocked core + injected fake query stream."""
2
+
3
+ from unittest.mock import AsyncMock, MagicMock
4
+
5
+ import pytest
6
+
7
+
8
+ @pytest.fixture(autouse=True)
9
+ def mock_core(monkeypatch):
10
+ import sys
11
+ core = MagicMock()
12
+
13
+ class MockAgentGovernance:
14
+ def __init__(self, *a, **k):
15
+ self._app_id = "cas-1"
16
+ self.pre_invoke = MagicMock(return_value="req-cas-1")
17
+ self.on_model_call = MagicMock()
18
+ self.post_invoke = AsyncMock()
19
+ self.on_error = AsyncMock()
20
+ self.on_tool_call = AsyncMock()
21
+
22
+ core.AgentGovernance = MockAgentGovernance
23
+ monkeypatch.setitem(sys.modules, "aigp_agent_core", core)
24
+ return core
25
+
26
+
27
+ def _fake_query_factory(fail=False):
28
+ async def _q(prompt, **kw):
29
+ if fail:
30
+ raise RuntimeError("stream failed")
31
+ # assistant turn with a tool_use block
32
+ yield {"content": [{"type": "tool_use", "name": "web_search"}]}
33
+ # result turn with usage
34
+ yield {"usage": {"input_tokens": 15, "output_tokens": 25}}
35
+ return _q
36
+
37
+
38
+ @pytest.fixture
39
+ def gov(mock_core):
40
+ from aigp_claude_agent_sdk import AigpClaudeAgentGovernance
41
+ return AigpClaudeAgentGovernance("http://gov.test", "cas-1", "s", query=_fake_query_factory())
42
+
43
+
44
+ @pytest.mark.asyncio
45
+ async def test_query_streams_governs_tools_and_records(gov):
46
+ messages = [m async for m in gov.query("analyze", agent_name="analyst", model_id="claude-opus-4-8")]
47
+ assert len(messages) == 2 # stream passed through
48
+ gov._gov.pre_invoke.assert_called_once()
49
+ gov._gov.on_tool_call.assert_awaited_once() # tool_use governed
50
+ usage = gov._gov.on_model_call.call_args.kwargs["usage"]
51
+ assert usage == {"input_tokens": 15, "output_tokens": 25}
52
+ gov._gov.post_invoke.assert_awaited_once()
53
+
54
+
55
+ @pytest.mark.asyncio
56
+ async def test_query_reports_error(mock_core):
57
+ from aigp_claude_agent_sdk import AigpClaudeAgentGovernance
58
+ gov = AigpClaudeAgentGovernance("http://gov.test", "cas-1", "s", query=_fake_query_factory(fail=True))
59
+ with pytest.raises(RuntimeError):
60
+ async for _ in gov.query("x"):
61
+ pass
62
+ gov._gov.on_error.assert_awaited_once()