monkeyscode 1.0.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,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
+
monkeyscode/_http.py ADDED
@@ -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
monkeyscode/admin.py ADDED
@@ -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()