monkeyscode 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.
Files changed (33) hide show
  1. monkeyscode-1.0.0/.gitignore +9 -0
  2. monkeyscode-1.0.0/LICENSE +21 -0
  3. monkeyscode-1.0.0/PKG-INFO +152 -0
  4. monkeyscode-1.0.0/README.md +121 -0
  5. monkeyscode-1.0.0/monkeyscode/__init__.py +178 -0
  6. monkeyscode-1.0.0/monkeyscode/_http.py +83 -0
  7. monkeyscode-1.0.0/monkeyscode/admin.py +141 -0
  8. monkeyscode-1.0.0/monkeyscode/agent.py +772 -0
  9. monkeyscode-1.0.0/monkeyscode/ci.py +288 -0
  10. monkeyscode-1.0.0/monkeyscode/cli_process.py +730 -0
  11. monkeyscode-1.0.0/monkeyscode/daemon.py +201 -0
  12. monkeyscode-1.0.0/monkeyscode/events.py +323 -0
  13. monkeyscode-1.0.0/monkeyscode/export.py +319 -0
  14. monkeyscode-1.0.0/monkeyscode/hooks.py +190 -0
  15. monkeyscode-1.0.0/monkeyscode/mcp.py +283 -0
  16. monkeyscode-1.0.0/monkeyscode/orchestrator.py +170 -0
  17. monkeyscode-1.0.0/monkeyscode/otel.py +181 -0
  18. monkeyscode-1.0.0/monkeyscode/py.typed +1 -0
  19. monkeyscode-1.0.0/monkeyscode/runs.py +138 -0
  20. monkeyscode-1.0.0/monkeyscode/sandbox.py +125 -0
  21. monkeyscode-1.0.0/monkeyscode/session.py +227 -0
  22. monkeyscode-1.0.0/monkeyscode/subagent.py +195 -0
  23. monkeyscode-1.0.0/monkeyscode/telemetry.py +204 -0
  24. monkeyscode-1.0.0/monkeyscode/tools.py +133 -0
  25. monkeyscode-1.0.0/monkeyscode/watcher.py +137 -0
  26. monkeyscode-1.0.0/pyproject.toml +70 -0
  27. monkeyscode-1.0.0/tests/conftest.py +8 -0
  28. monkeyscode-1.0.0/tests/fixtures/fake_mc.py +46 -0
  29. monkeyscode-1.0.0/tests/test_ci.py +120 -0
  30. monkeyscode-1.0.0/tests/test_events.py +104 -0
  31. monkeyscode-1.0.0/tests/test_parity.py +254 -0
  32. monkeyscode-1.0.0/tests/test_sdk_gaps.py +203 -0
  33. monkeyscode-1.0.0/tests/test_tools.py +111 -0
@@ -0,0 +1,9 @@
1
+ # Python
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
5
+ venv/
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MonkeysCloud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,152 @@
1
+ Metadata-Version: 2.5
2
+ Name: monkeyscode
3
+ Version: 1.0.0
4
+ Summary: MonkeysCode SDK — programmatic agent control for Python
5
+ Project-URL: Homepage, https://monkeyscode.com
6
+ Project-URL: Documentation, https://monkeyscode.com/docs/sdk/python
7
+ Project-URL: Repository, https://github.com/MonkeysCloud/monkeyscode
8
+ Project-URL: Issues, https://github.com/MonkeysCloud/monkeyscode/issues
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: ai,automation,coding-agent,monkeyscode,sdk
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: pydantic>=2.0
25
+ Provides-Extra: dev
26
+ Requires-Dist: mypy>=1.10; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.5; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # MonkeysCode Python SDK
33
+
34
+ Programmatic agent control for Python. Run coding agents, stream events, define custom tools, and integrate with CI/CD pipelines.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install monkeyscode
40
+ ```
41
+
42
+ ## Quick Start
43
+
44
+ ```python
45
+ from monkeyscode import MonkeysCode
46
+ import asyncio
47
+
48
+ async def main():
49
+ agent = MonkeysCode(api_key="mc_...")
50
+ result = await agent.run("Fix all Python type errors")
51
+ print(f"✓ {result.summary}")
52
+ print(f" Files: {len(result.files_changed)}, Cost: ${result.cost:.4f}")
53
+
54
+ asyncio.run(main())
55
+ ```
56
+
57
+ ## Streaming
58
+
59
+ ```python
60
+ async for event in agent.stream("Refactor auth module"):
61
+ if event.type == "text":
62
+ print(event.content, end="", flush=True)
63
+ elif event.type == "tool_call":
64
+ print(f" 🔧 {event.tool}")
65
+ ```
66
+
67
+ ## Custom Tools
68
+
69
+ ```python
70
+ from monkeyscode import define_tool
71
+
72
+ @define_tool(
73
+ name="deploy",
74
+ description="Deploy the application",
75
+ parameters={"env": {"type": "string", "enum": ["staging", "prod"]}},
76
+ )
77
+ async def deploy(env: str) -> dict:
78
+ return {"deployed": True, "url": f"https://{env}.example.com"}
79
+
80
+ agent.add_tool(deploy)
81
+ ```
82
+
83
+ ## Goal Mode
84
+
85
+ ```python
86
+ result = await agent.goal(
87
+ "All tests pass",
88
+ verify_command="pytest",
89
+ max_iterations=5,
90
+ )
91
+ print(f"Goal met: {result.goal_met} in {result.iterations} iterations")
92
+ ```
93
+
94
+ ## Sessions
95
+
96
+ ```python
97
+ from monkeyscode import Session
98
+
99
+ session = await Session.create(agent, workspace="/my/project")
100
+ await session.run("Add auth module")
101
+ await session.run("Now add tests for it") # Carries context
102
+ session.close()
103
+ ```
104
+
105
+ ## Local agent (`mc` subprocess)
106
+
107
+ The client above calls the hosted API. To run the agent **on this machine**
108
+ with your settings, permission rules, hooks and MCP servers, drive an
109
+ installed `mc` (standard library only):
110
+
111
+ ```python
112
+ from monkeyscode.cli_process import (
113
+ CliOptions, MonkeysCodeClient, PermissionAllow, PermissionDeny, ResultMessage, query,
114
+ )
115
+
116
+ async for event in query("explain src/main.ts"):
117
+ if isinstance(event, ResultMessage):
118
+ print(event.result, event.cost_usd)
119
+
120
+ async def can_use_tool(tool, tool_input, ctx):
121
+ if str(tool_input.get("path", "")).startswith("docs/"):
122
+ return PermissionAllow()
123
+ return PermissionDeny(message="only docs/ may be written")
124
+
125
+ async with MonkeysCodeClient(CliOptions(can_use_tool=can_use_tool, max_cost_usd=1)) as client:
126
+ await client.send("write docs/intro.md")
127
+ result = await client.receive_result()
128
+ ```
129
+
130
+ `query_cli` and `MonkeysCodeClient` are also exported from `monkeyscode`.
131
+ Guide: [docs/cli/sdk.md](../../docs/cli/sdk.md); a runnable three-turn
132
+ example: [`examples/three_turn_approval.py`](examples/three_turn_approval.py).
133
+
134
+ ## CI/CD
135
+
136
+ ```python
137
+ from monkeyscode.ci import ci_run, to_sarif
138
+ import json
139
+
140
+ result = await ci_run(
141
+ prompt="Review this PR for security issues",
142
+ diff=open("pr.diff").read(),
143
+ )
144
+
145
+ sarif = to_sarif(result)
146
+ with open("results.sarif", "w") as f:
147
+ json.dump(sarif, f, indent=2)
148
+ ```
149
+
150
+ ## License
151
+
152
+ MIT
@@ -0,0 +1,121 @@
1
+ # MonkeysCode Python SDK
2
+
3
+ Programmatic agent control for Python. Run coding agents, stream events, define custom tools, and integrate with CI/CD pipelines.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install monkeyscode
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ from monkeyscode import MonkeysCode
15
+ import asyncio
16
+
17
+ async def main():
18
+ agent = MonkeysCode(api_key="mc_...")
19
+ result = await agent.run("Fix all Python type errors")
20
+ print(f"✓ {result.summary}")
21
+ print(f" Files: {len(result.files_changed)}, Cost: ${result.cost:.4f}")
22
+
23
+ asyncio.run(main())
24
+ ```
25
+
26
+ ## Streaming
27
+
28
+ ```python
29
+ async for event in agent.stream("Refactor auth module"):
30
+ if event.type == "text":
31
+ print(event.content, end="", flush=True)
32
+ elif event.type == "tool_call":
33
+ print(f" 🔧 {event.tool}")
34
+ ```
35
+
36
+ ## Custom Tools
37
+
38
+ ```python
39
+ from monkeyscode import define_tool
40
+
41
+ @define_tool(
42
+ name="deploy",
43
+ description="Deploy the application",
44
+ parameters={"env": {"type": "string", "enum": ["staging", "prod"]}},
45
+ )
46
+ async def deploy(env: str) -> dict:
47
+ return {"deployed": True, "url": f"https://{env}.example.com"}
48
+
49
+ agent.add_tool(deploy)
50
+ ```
51
+
52
+ ## Goal Mode
53
+
54
+ ```python
55
+ result = await agent.goal(
56
+ "All tests pass",
57
+ verify_command="pytest",
58
+ max_iterations=5,
59
+ )
60
+ print(f"Goal met: {result.goal_met} in {result.iterations} iterations")
61
+ ```
62
+
63
+ ## Sessions
64
+
65
+ ```python
66
+ from monkeyscode import Session
67
+
68
+ session = await Session.create(agent, workspace="/my/project")
69
+ await session.run("Add auth module")
70
+ await session.run("Now add tests for it") # Carries context
71
+ session.close()
72
+ ```
73
+
74
+ ## Local agent (`mc` subprocess)
75
+
76
+ The client above calls the hosted API. To run the agent **on this machine**
77
+ with your settings, permission rules, hooks and MCP servers, drive an
78
+ installed `mc` (standard library only):
79
+
80
+ ```python
81
+ from monkeyscode.cli_process import (
82
+ CliOptions, MonkeysCodeClient, PermissionAllow, PermissionDeny, ResultMessage, query,
83
+ )
84
+
85
+ async for event in query("explain src/main.ts"):
86
+ if isinstance(event, ResultMessage):
87
+ print(event.result, event.cost_usd)
88
+
89
+ async def can_use_tool(tool, tool_input, ctx):
90
+ if str(tool_input.get("path", "")).startswith("docs/"):
91
+ return PermissionAllow()
92
+ return PermissionDeny(message="only docs/ may be written")
93
+
94
+ async with MonkeysCodeClient(CliOptions(can_use_tool=can_use_tool, max_cost_usd=1)) as client:
95
+ await client.send("write docs/intro.md")
96
+ result = await client.receive_result()
97
+ ```
98
+
99
+ `query_cli` and `MonkeysCodeClient` are also exported from `monkeyscode`.
100
+ Guide: [docs/cli/sdk.md](../../docs/cli/sdk.md); a runnable three-turn
101
+ example: [`examples/three_turn_approval.py`](examples/three_turn_approval.py).
102
+
103
+ ## CI/CD
104
+
105
+ ```python
106
+ from monkeyscode.ci import ci_run, to_sarif
107
+ import json
108
+
109
+ result = await ci_run(
110
+ prompt="Review this PR for security issues",
111
+ diff=open("pr.diff").read(),
112
+ )
113
+
114
+ sarif = to_sarif(result)
115
+ with open("results.sarif", "w") as f:
116
+ json.dump(sarif, f, indent=2)
117
+ ```
118
+
119
+ ## License
120
+
121
+ MIT
@@ -0,0 +1,178 @@
1
+ """
2
+ MonkeysCode Python SDK.
3
+
4
+ Programmatic agent control for Python. Supports streaming, custom tools,
5
+ goal mode, session management, and CI/CD integrations.
6
+
7
+ Usage::
8
+
9
+ from monkeyscode import MonkeysCode
10
+
11
+ agent = MonkeysCode(api_key="mc_...")
12
+ result = await agent.run("Fix all Python type errors")
13
+ print(result.summary)
14
+
15
+ For streaming::
16
+
17
+ async for event in agent.stream("Refactor auth module"):
18
+ if event.type == "text":
19
+ print(event.content, end="", flush=True)
20
+ """
21
+
22
+ from monkeyscode.admin import AdminClient
23
+ from monkeyscode.agent import MonkeysCode, MonkeysCodeOptions
24
+ from monkeyscode.cli_process import (
25
+ AssistantMessage,
26
+ CliOptions,
27
+ InitMessage,
28
+ McProcessError,
29
+ McSchemaError,
30
+ MonkeysCodeClient,
31
+ PermissionAllow,
32
+ PermissionDeny,
33
+ ResultMessage,
34
+ ToolPermissionContext,
35
+ UserMessage,
36
+ )
37
+ from monkeyscode.cli_process import query as query_cli
38
+ from monkeyscode.daemon import DaemonClient, DaemonClientOptions, DaemonEvent, DaemonRunParams
39
+ from monkeyscode.events import (
40
+ AgentEvent,
41
+ AgentResult,
42
+ CompleteEvent,
43
+ ErrorEvent,
44
+ FileChange,
45
+ FileEditEvent,
46
+ GoalOptions,
47
+ GoalResult,
48
+ TextEvent,
49
+ TokenUsage,
50
+ ToolCallEvent,
51
+ ToolResultEvent,
52
+ )
53
+ from monkeyscode.export import to_html, to_markdown, to_transcript
54
+ from monkeyscode.hooks import (
55
+ HookManager,
56
+ PostToolContext,
57
+ PostToolHook,
58
+ PreToolContext,
59
+ PreToolHook,
60
+ PreToolResult,
61
+ )
62
+ from monkeyscode.mcp import McpManager, McpServerConfig, McpServerStatus, McpTool, McpToolResult
63
+ from monkeyscode.orchestrator import AgentSlotResult, OrchestratorResult, run_fan_out, run_parallel
64
+ from monkeyscode.otel import OtelExporter, OtelOptions
65
+ from monkeyscode.runs import RunRecord, RunStore
66
+ from monkeyscode.sandbox import (
67
+ SandboxOptions,
68
+ SandboxResult,
69
+ detect_sandbox_mode,
70
+ is_docker_available,
71
+ run_in_sandbox,
72
+ )
73
+ from monkeyscode.session import Session, SessionOptions
74
+ from monkeyscode.subagent import (
75
+ SubagentOptions,
76
+ SubagentResult,
77
+ cap_summary,
78
+ spawn_subagent,
79
+ )
80
+ from monkeyscode.telemetry import TelemetryCollector, TelemetryOptions, with_telemetry
81
+ from monkeyscode.tools import ToolDefinition, define_tool
82
+ from monkeyscode.watcher import WatchOptions, format_change_batch, watch_files
83
+
84
+ __version__ = "1.0.0"
85
+
86
+ # Grouped by module on purpose; the order of __all__ has no runtime effect.
87
+ __all__ = [ # noqa: RUF022
88
+ # Events
89
+ "AgentEvent",
90
+ "AgentResult",
91
+ "CompleteEvent",
92
+ "ErrorEvent",
93
+ "FileChange",
94
+ "FileEditEvent",
95
+ "GoalOptions",
96
+ "GoalResult",
97
+ # Agent
98
+ "MonkeysCode",
99
+ "MonkeysCodeOptions",
100
+ # Session
101
+ "Session",
102
+ "SessionOptions",
103
+ "TextEvent",
104
+ "TokenUsage",
105
+ "ToolCallEvent",
106
+ "ToolDefinition",
107
+ "ToolResultEvent",
108
+ # Tools
109
+ "define_tool",
110
+ # Hooks
111
+ "HookManager",
112
+ "PreToolContext",
113
+ "PreToolHook",
114
+ "PreToolResult",
115
+ "PostToolContext",
116
+ "PostToolHook",
117
+ # Subagent
118
+ "SubagentOptions",
119
+ "SubagentResult",
120
+ "cap_summary",
121
+ "spawn_subagent",
122
+ # Admin
123
+ "AdminClient",
124
+ # Local engine over the mc subprocess (cli_process)
125
+ "query_cli",
126
+ "MonkeysCodeClient",
127
+ "CliOptions",
128
+ "InitMessage",
129
+ "AssistantMessage",
130
+ "UserMessage",
131
+ "ResultMessage",
132
+ "PermissionAllow",
133
+ "PermissionDeny",
134
+ "ToolPermissionContext",
135
+ "McSchemaError",
136
+ "McProcessError",
137
+ # Export
138
+ "to_markdown",
139
+ "to_html",
140
+ "to_transcript",
141
+ # Daemon
142
+ "DaemonClient",
143
+ "DaemonClientOptions",
144
+ "DaemonRunParams",
145
+ "DaemonEvent",
146
+ # MCP
147
+ "McpManager",
148
+ "McpServerConfig",
149
+ "McpTool",
150
+ "McpToolResult",
151
+ "McpServerStatus",
152
+ # Watcher
153
+ "watch_files",
154
+ "format_change_batch",
155
+ "WatchOptions",
156
+ # Orchestrator
157
+ "run_parallel",
158
+ "run_fan_out",
159
+ "OrchestratorResult",
160
+ "AgentSlotResult",
161
+ # Telemetry
162
+ "TelemetryCollector",
163
+ "TelemetryOptions",
164
+ "with_telemetry",
165
+ # OTEL
166
+ "OtelExporter",
167
+ "OtelOptions",
168
+ # Runs
169
+ "RunStore",
170
+ "RunRecord",
171
+ # Sandbox
172
+ "run_in_sandbox",
173
+ "SandboxOptions",
174
+ "SandboxResult",
175
+ "is_docker_available",
176
+ "detect_sandbox_mode",
177
+ ]
178
+
@@ -0,0 +1,83 @@
1
+ """
2
+ MonkeysCode SDK — SSE HTTP Client.
3
+
4
+ Internal module that handles SSE (Server-Sent Events) streaming
5
+ via httpx. Used by the MonkeysCode agent class.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import AsyncIterator
12
+ from typing import Any
13
+
14
+ import httpx
15
+
16
+
17
+ async def stream_sse(
18
+ url: str,
19
+ *,
20
+ method: str = "POST",
21
+ headers: dict[str, str] | None = None,
22
+ json_body: dict[str, Any] | None = None,
23
+ timeout: float = 300.0,
24
+ ) -> AsyncIterator[dict[str, Any]]:
25
+ """
26
+ Stream SSE events from an HTTP endpoint.
27
+
28
+ Yields parsed JSON objects from ``data:`` lines in the SSE stream.
29
+ Automatically handles:
30
+ - Multi-line buffering
31
+ - ``[DONE]`` sentinel
32
+ - Malformed lines (skipped silently)
33
+
34
+ Args:
35
+ url: The endpoint URL.
36
+ method: HTTP method (default: POST).
37
+ headers: Request headers.
38
+ json_body: JSON request body (for POST).
39
+ timeout: Request timeout in seconds.
40
+
41
+ Yields:
42
+ Parsed JSON dictionaries from each SSE ``data:`` line.
43
+ """
44
+ all_headers = {
45
+ "Accept": "text/event-stream",
46
+ "Content-Type": "application/json",
47
+ **(headers or {}),
48
+ }
49
+
50
+ async with httpx.AsyncClient(timeout=httpx.Timeout(timeout)) as client:
51
+ async with client.stream(
52
+ method,
53
+ url,
54
+ headers=all_headers,
55
+ json=json_body,
56
+ ) as response:
57
+ response.raise_for_status()
58
+
59
+ buffer = ""
60
+ async for chunk in response.aiter_text():
61
+ buffer += chunk
62
+ lines = buffer.split("\n")
63
+ buffer = lines.pop() # Keep incomplete last line
64
+
65
+ for line in lines:
66
+ line = line.strip()
67
+
68
+ if not line:
69
+ continue
70
+
71
+ if not line.startswith("data: "):
72
+ continue
73
+
74
+ data = line[6:].strip()
75
+
76
+ if data == "[DONE]":
77
+ return
78
+
79
+ try:
80
+ yield json.loads(data)
81
+ except json.JSONDecodeError:
82
+ # Skip malformed SSE lines
83
+ continue
@@ -0,0 +1,141 @@
1
+ """
2
+ MonkeysCode SDK — Admin API Client.
3
+
4
+ REST client for team managers to monitor agent activity,
5
+ usage, and costs across their organization.
6
+
7
+ Usage::
8
+
9
+ from monkeyscode.admin import AdminClient
10
+
11
+ admin = AdminClient(api_key="mc_...")
12
+
13
+ usage = await admin.get_usage(period="30d")
14
+ print(f"Total cost: ${usage['total_cost']:.2f}")
15
+
16
+ runs = await admin.list_runs(limit=20)
17
+ for run in runs["runs"]:
18
+ print(f" {run['id']} — {run['user']['name']} — ${run['cost']:.4f}")
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Any
24
+
25
+ import httpx
26
+
27
+ DEFAULT_BASE_URL = "https://api.monkeyscode.com"
28
+
29
+
30
+ class AdminClient:
31
+ """
32
+ Admin API client for monitoring team agent usage.
33
+
34
+ Requires an API key with admin/owner permissions on the organization.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ *,
40
+ api_key: str,
41
+ base_url: str | None = None,
42
+ ) -> None:
43
+ self._api_key = api_key
44
+ self._base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
45
+
46
+ # ── Usage ─────────────────────────────────────────────────────────
47
+
48
+ async def get_usage(
49
+ self,
50
+ *,
51
+ period: str = "30d",
52
+ user: str | None = None,
53
+ model: str | None = None,
54
+ ) -> dict[str, Any]:
55
+ """
56
+ Get usage report for the organization.
57
+
58
+ Returns dict with: total_cost, total_runs, total_tokens,
59
+ by_model, by_user, daily.
60
+ """
61
+ params: dict[str, str] = {"period": period}
62
+ if user:
63
+ params["user"] = user
64
+ if model:
65
+ params["model"] = model
66
+ return await self._request("GET", "/v1/admin/usage", params=params)
67
+
68
+ # ── Runs ──────────────────────────────────────────────────────────
69
+
70
+ async def list_runs(
71
+ self,
72
+ *,
73
+ limit: int = 50,
74
+ cursor: str | None = None,
75
+ status: str | None = None,
76
+ user: str | None = None,
77
+ model: str | None = None,
78
+ ) -> dict[str, Any]:
79
+ """
80
+ List agent runs across the organization.
81
+
82
+ Returns dict with: runs, cursor, has_more, total.
83
+ """
84
+ params: dict[str, str] = {"limit": str(limit)}
85
+ if cursor:
86
+ params["cursor"] = cursor
87
+ if status:
88
+ params["status"] = status
89
+ if user:
90
+ params["user"] = user
91
+ if model:
92
+ params["model"] = model
93
+ return await self._request("GET", "/v1/admin/runs", params=params)
94
+
95
+ async def get_run(self, run_id: str) -> dict[str, Any]:
96
+ """Get details for a specific run."""
97
+ return await self._request("GET", f"/v1/admin/runs/{run_id}")
98
+
99
+ async def cancel_run(self, run_id: str) -> dict[str, Any]:
100
+ """Cancel a running agent."""
101
+ return await self._request("POST", f"/v1/admin/runs/{run_id}/cancel")
102
+
103
+ # ── Active Agents ─────────────────────────────────────────────────
104
+
105
+ async def get_active_agents(self) -> list[dict[str, Any]]:
106
+ """List currently active agents across the organization."""
107
+ return await self._request("GET", "/v1/admin/agents")
108
+
109
+ # ── Team Members ──────────────────────────────────────────────────
110
+
111
+ async def list_members(self) -> list[dict[str, Any]]:
112
+ """List team members and their usage stats."""
113
+ return await self._request("GET", "/v1/admin/members")
114
+
115
+ # ── Internal ──────────────────────────────────────────────────────
116
+
117
+ async def _request(
118
+ self,
119
+ method: str,
120
+ path: str,
121
+ *,
122
+ params: dict[str, str] | None = None,
123
+ json_body: dict[str, Any] | None = None,
124
+ ) -> Any:
125
+ url = f"{self._base_url}{path}"
126
+ headers = {
127
+ "Authorization": f"Bearer {self._api_key}",
128
+ "Content-Type": "application/json",
129
+ "User-Agent": "monkeyscode-sdk-python/1.0.0",
130
+ }
131
+
132
+ async with httpx.AsyncClient() as client:
133
+ response = await client.request(
134
+ method,
135
+ url,
136
+ headers=headers,
137
+ params=params,
138
+ json=json_body,
139
+ )
140
+ response.raise_for_status()
141
+ return response.json()