agsrv 0.3.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.
agsrv/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Multi-agent API package."""
agsrv/agent.py ADDED
@@ -0,0 +1,294 @@
1
+ """Agent execution helpers around the stateless Claude Agent SDK ``query()``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import re
7
+ from typing import TYPE_CHECKING, Any, Protocol, cast
8
+
9
+ from claude_agent_sdk import (
10
+ AssistantMessage,
11
+ ClaudeAgentOptions,
12
+ ResultError,
13
+ ResultMessage,
14
+ SystemMessage,
15
+ TextBlock,
16
+ ThinkingBlock,
17
+ ToolResultBlock,
18
+ ToolUseBlock,
19
+ UserMessage,
20
+ query,
21
+ )
22
+
23
+ from agsrv.sandbox import (
24
+ build_sandbox_settings,
25
+ bundled_cli_path,
26
+ prepare_sandbox_cache,
27
+ sandbox_env,
28
+ service_home,
29
+ )
30
+ from agsrv.schemas import QueryResponse
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import AsyncIterator
34
+ from pathlib import Path
35
+
36
+ from claude_agent_sdk import Message
37
+
38
+ from agsrv.config import Settings
39
+ from agsrv.schemas import QueryRequest
40
+
41
+
42
+ class AgentExecutionError(Exception):
43
+ """Raised when an agent run cannot produce a final result."""
44
+
45
+
46
+ class AgentRunner(Protocol):
47
+ """Runs a single ephemeral agent query."""
48
+
49
+ def stream(
50
+ self, prompt: str, options: ClaudeAgentOptions
51
+ ) -> AsyncIterator[Message]:
52
+ """Stream SDK messages for one prompt.
53
+
54
+ Args:
55
+ prompt: User prompt.
56
+ options: SDK options.
57
+ """
58
+ ...
59
+
60
+
61
+ class SdkAgentRunner:
62
+ """Runner backed by ``claude_agent_sdk.query``."""
63
+
64
+ def stream( # ruff: ignore[no-self-use] # implements the AgentRunner protocol
65
+ self, prompt: str, options: ClaudeAgentOptions
66
+ ) -> AsyncIterator[Message]:
67
+ """Stream SDK messages for one prompt.
68
+
69
+ Args:
70
+ prompt: User prompt.
71
+ options: SDK options.
72
+
73
+ Returns:
74
+ Async iterator of SDK messages.
75
+ """
76
+ return query(prompt=prompt, options=options)
77
+
78
+
79
+ def json_safe(value: object) -> Any: # ruff: ignore[any-type]
80
+ """Recursively convert a value into JSON-serializable data.
81
+
82
+ Args:
83
+ value: Arbitrary value.
84
+
85
+ Returns:
86
+ JSON-compatible data; unknown objects become ``str(value)``.
87
+ """
88
+ if value is None or isinstance(value, str | int | float | bool):
89
+ return value
90
+ if isinstance(value, dict):
91
+ return {
92
+ str(k): json_safe(v) for k, v in cast("dict[object, object]", value).items()
93
+ }
94
+ if isinstance(value, list | tuple | set | frozenset):
95
+ return [json_safe(v) for v in cast("list[object]", value)]
96
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
97
+ return json_safe(dataclasses.asdict(value))
98
+ return str(value)
99
+
100
+
101
+ def _snake(name: str) -> str:
102
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower()
103
+
104
+
105
+ def _generic(obj: object) -> dict[str, Any]:
106
+ data = json_safe(obj)
107
+ kind = _snake(type(obj).__name__)
108
+ return {"type": kind, "data": data}
109
+
110
+
111
+ def block_to_dict(block: object) -> dict[str, Any]:
112
+ """Serialize a content block.
113
+
114
+ Args:
115
+ block: SDK content block.
116
+
117
+ Returns:
118
+ JSON-compatible dict with a ``type`` key.
119
+ """
120
+ if isinstance(block, TextBlock):
121
+ return {"type": "text", "text": block.text}
122
+ if isinstance(block, ThinkingBlock):
123
+ return {
124
+ "type": "thinking",
125
+ "thinking": block.thinking,
126
+ "signature": block.signature,
127
+ }
128
+ if isinstance(block, ToolUseBlock):
129
+ return {
130
+ "type": "tool_use",
131
+ "id": block.id,
132
+ "name": block.name,
133
+ "input": json_safe(block.input),
134
+ }
135
+ if isinstance(block, ToolResultBlock):
136
+ return {
137
+ "type": "tool_result",
138
+ "tool_use_id": block.tool_use_id,
139
+ "content": json_safe(block.content),
140
+ "is_error": block.is_error,
141
+ }
142
+ return _generic(block)
143
+
144
+
145
+ def message_to_dict(message: object) -> dict[str, Any]:
146
+ """Serialize an SDK message.
147
+
148
+ Args:
149
+ message: SDK message.
150
+
151
+ Returns:
152
+ JSON-compatible dict with a ``type`` key.
153
+ """
154
+ if isinstance(message, SystemMessage):
155
+ return {
156
+ "type": "system",
157
+ "subtype": message.subtype,
158
+ "data": json_safe(message.data),
159
+ }
160
+ if isinstance(message, AssistantMessage):
161
+ return {
162
+ "type": "assistant",
163
+ "model": message.model,
164
+ "content": [block_to_dict(b) for b in message.content],
165
+ "error": message.error,
166
+ "usage": json_safe(message.usage),
167
+ "stop_reason": message.stop_reason,
168
+ "session_id": message.session_id,
169
+ "uuid": message.uuid,
170
+ }
171
+ if isinstance(message, UserMessage):
172
+ content = (
173
+ message.content
174
+ if isinstance(message.content, str)
175
+ else [block_to_dict(b) for b in message.content]
176
+ )
177
+ return {
178
+ "type": "user",
179
+ "content": content,
180
+ "uuid": message.uuid,
181
+ "parent_tool_use_id": message.parent_tool_use_id,
182
+ }
183
+ if isinstance(message, ResultMessage):
184
+ return {
185
+ "type": "result",
186
+ "subtype": message.subtype,
187
+ "is_error": message.is_error,
188
+ "result": message.result,
189
+ "session_id": message.session_id,
190
+ "num_turns": message.num_turns,
191
+ "duration_ms": message.duration_ms,
192
+ "duration_api_ms": message.duration_api_ms,
193
+ "total_cost_usd": message.total_cost_usd,
194
+ "usage": json_safe(message.usage),
195
+ "stop_reason": message.stop_reason,
196
+ "errors": json_safe(message.errors),
197
+ }
198
+ return _generic(message)
199
+
200
+
201
+ def build_options(
202
+ request: QueryRequest, settings: Settings, cwd: Path, home: Path | None = None
203
+ ) -> ClaudeAgentOptions:
204
+ """Build stateless SDK options from a request and server defaults.
205
+
206
+ Args:
207
+ request: Validated request.
208
+ settings: Server settings.
209
+ cwd: Resolved working directory.
210
+ home: Service home directory for sandboxed runs; looked up if omitted.
211
+
212
+ Returns:
213
+ SDK options; never sets session/resume fields.
214
+ """
215
+ kwargs: dict[str, Any] = {
216
+ "cwd": str(cwd),
217
+ "permission_mode": request.permission_mode or settings.permission_mode,
218
+ "allowed_tools": (
219
+ request.allowed_tools
220
+ if request.allowed_tools is not None
221
+ else list(settings.allowed_tools)
222
+ ),
223
+ # Stateless and hermetic runs: the CLI must not persist a resumable
224
+ # session transcript, and host/project settings (hooks, MCP servers,
225
+ # permission rules) must not leak into runs.
226
+ "setting_sources": [],
227
+ "extra_args": {"no-session-persistence": None},
228
+ "env": {"CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"},
229
+ "strict_mcp_config": True,
230
+ "system_prompt": {"type": "preset", "preset": "claude_code"},
231
+ }
232
+ model = request.model or settings.default_model
233
+ optional: dict[str, Any] = {
234
+ "model": model,
235
+ "max_turns": request.max_turns,
236
+ "effort": request.effort,
237
+ }
238
+ kwargs.update({k: v for k, v in optional.items() if v is not None})
239
+ if request.sandbox:
240
+ home = home or service_home()
241
+ kwargs["cli_path"] = bundled_cli_path()
242
+ prepare_sandbox_cache(home)
243
+ kwargs["sandbox"] = build_sandbox_settings(settings, home)
244
+ kwargs["env"] = {**kwargs["env"], **sandbox_env(home)}
245
+ return ClaudeAgentOptions(**kwargs)
246
+
247
+
248
+ async def collect_result(
249
+ stream: AsyncIterator[Message], *, include_messages: bool = True
250
+ ) -> QueryResponse:
251
+ """Consume a message stream and build the final response.
252
+
253
+ Args:
254
+ stream: SDK message stream.
255
+ include_messages: Whether to include the serialized transcript.
256
+
257
+ Returns:
258
+ Response built from the final ``ResultMessage``.
259
+
260
+ Raises:
261
+ AgentExecutionError: If the stream ends without a ``ResultMessage``.
262
+ ResultError: If the SDK fails before producing a result.
263
+ """
264
+ messages: list[dict[str, Any]] = []
265
+ final: ResultMessage | None = None
266
+ model: str | None = None
267
+ try: # ruff: ignore[too-many-statements-in-try-clause] # consume the complete stream
268
+ async for message in stream:
269
+ if isinstance(message, AssistantMessage):
270
+ model = message.model
271
+ if include_messages:
272
+ messages.append(message_to_dict(message))
273
+ if isinstance(message, ResultMessage):
274
+ final = message
275
+ except ResultError:
276
+ if final is None:
277
+ raise
278
+ if final is None:
279
+ msg = "agent stream ended without a result message"
280
+ raise AgentExecutionError(msg)
281
+ return QueryResponse(
282
+ result=final.result,
283
+ session_id=final.session_id,
284
+ model=model,
285
+ subtype=final.subtype,
286
+ is_error=final.is_error,
287
+ num_turns=final.num_turns,
288
+ duration_ms=final.duration_ms,
289
+ duration_api_ms=final.duration_api_ms,
290
+ total_cost_usd=final.total_cost_usd,
291
+ usage=final.usage,
292
+ stop_reason=final.stop_reason,
293
+ messages=messages,
294
+ )
agsrv/codex_agent.py ADDED
@@ -0,0 +1,278 @@
1
+ """Codex SDK helpers for ephemeral, non-interactive runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from contextlib import aclosing, asynccontextmanager, suppress
8
+ from dataclasses import replace
9
+ from typing import TYPE_CHECKING, Any, cast
10
+
11
+ from openai_codex import (
12
+ ApprovalMode,
13
+ AsyncCodex,
14
+ AsyncThread,
15
+ AsyncTurnHandle,
16
+ CodexConfig,
17
+ Sandbox,
18
+ )
19
+ from openai_codex._initialize_metadata import ( # ruff: ignore[import-private-name]
20
+ validate_initialize_metadata,
21
+ )
22
+ from openai_codex._run import _collect_async_turn_result # pyright: ignore[reportPrivateUsage] # ruff: ignore[import-private-name]
23
+ from openai_codex.generated.v2_all import (
24
+ GetAccountRateLimitsResponse,
25
+ TurnCompletedNotification,
26
+ TurnStatus,
27
+ )
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import AsyncGenerator
31
+
32
+ from openai_codex._run import TurnResult # pyright: ignore[reportPrivateUsage]
33
+ from openai_codex.generated.v2_all import ReasoningEffort
34
+ from openai_codex.models import JsonObject, Notification
35
+
36
+
37
+ def decline_approval(method: str, params: JsonObject | None) -> JsonObject:
38
+ """Decline server-initiated approval requests.
39
+
40
+ Returns:
41
+ A denial decision for the SDK transport.
42
+ """
43
+ _ = (method, params)
44
+ return {"decision": "decline"}
45
+
46
+
47
+ def make_client(binary: str | None) -> AsyncCodex:
48
+ """Create a client with a fail-closed approval handler.
49
+
50
+ Args:
51
+ binary: Optional Codex binary path.
52
+
53
+ Returns:
54
+ An uninitialized SDK client.
55
+ """
56
+ client = AsyncCodex(CodexConfig(codex_bin=binary))
57
+ client._client._sync._approval_handler = decline_approval # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
58
+ return client
59
+
60
+
61
+ @asynccontextmanager
62
+ async def client_context(binary: str | None) -> AsyncGenerator[AsyncCodex, None]:
63
+ """Start the transport separately so a stalled handshake can be closed.
64
+
65
+ Yields:
66
+ The initialized client.
67
+
68
+ Raises:
69
+ asyncio.CancelledError: If cancelled during cleanup.
70
+ """
71
+ client = make_client(binary)
72
+ sync = client._client._sync # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
73
+ startup_executor = ThreadPoolExecutor(max_workers=1)
74
+ start = asyncio.get_running_loop().run_in_executor(startup_executor, sync.start)
75
+
76
+ async def cleanup() -> None:
77
+ with suppress(Exception):
78
+ await start
79
+ startup_executor.shutdown(wait=True)
80
+ # Kill first: SDK close closes stdin before signaling, and a writer may
81
+ # hold its lock while blocked on a full pipe.
82
+ proc = sync._proc # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
83
+ if proc is not None:
84
+ with suppress(ProcessLookupError):
85
+ proc.kill()
86
+ # A stalled SDK RPC must not prevent its transport from closing.
87
+ with ThreadPoolExecutor(max_workers=1) as executor:
88
+ await asyncio.get_running_loop().run_in_executor(
89
+ executor,
90
+ sync.close,
91
+ )
92
+
93
+ try:
94
+ await asyncio.wait({start})
95
+ start.result()
96
+ payload = await client._client.initialize() # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
97
+ client._init = validate_initialize_metadata(payload) # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
98
+ client._initialized = True # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
99
+ yield client
100
+ finally:
101
+ closing = asyncio.create_task(cleanup())
102
+ cancelled = False
103
+ while not closing.done():
104
+ try:
105
+ await asyncio.shield(closing)
106
+ except asyncio.CancelledError:
107
+ cancelled = True
108
+ closing.result()
109
+ if cancelled:
110
+ raise asyncio.CancelledError
111
+
112
+
113
+ def _window(window: dict[str, Any] | None) -> dict[str, Any] | None:
114
+ if window is None:
115
+ return None
116
+ return {
117
+ "used_percent": window.get("usedPercent"),
118
+ "resets_at": window.get("resetsAt"),
119
+ }
120
+
121
+
122
+ async def probe(binary: str | None) -> bool:
123
+ """Initialize the configured Codex binary.
124
+
125
+ Returns:
126
+ Whether initialization succeeded.
127
+ """
128
+ try:
129
+ async with client_context(binary):
130
+ return True
131
+ except Exception: # ruff: ignore[blind-except] # any initialization failure means unhealthy
132
+ return False
133
+
134
+
135
+ async def read_rate_limits(binary: str | None) -> dict[str, Any]:
136
+ """Read the current account's rate limits from the Codex app server.
137
+
138
+ Args:
139
+ binary: Optional Codex binary path.
140
+
141
+ Returns:
142
+ Normalized fields and the SDK payload.
143
+ """
144
+ async with client_context(binary) as client:
145
+ response = await client._client.request( # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
146
+ "account/rateLimits/read", None, response_model=GetAccountRateLimitsResponse
147
+ )
148
+ raw = response.model_dump(mode="json", by_alias=True)
149
+ limits = raw["rateLimits"]
150
+ return {
151
+ "plan": limits.get("planType"),
152
+ "primary": _window(limits.get("primary")),
153
+ "secondary": _window(limits.get("secondary")),
154
+ "reached_type": limits.get("rateLimitReachedType"),
155
+ "reset_credits": raw.get("rateLimitResetCredits"),
156
+ "backend": raw,
157
+ }
158
+
159
+
160
+ async def collect_turn(handle: AsyncTurnHandle) -> TurnResult:
161
+ """Collect SDK results without discarding failed terminal turns.
162
+
163
+ Returns:
164
+ The SDK-collected result with its original terminal status and error.
165
+ """
166
+ terminal: TurnCompletedNotification | None = None
167
+
168
+ async def events() -> AsyncGenerator[Notification, None]:
169
+ nonlocal terminal
170
+ async with aclosing(
171
+ cast("AsyncGenerator[Notification, None]", handle.stream())
172
+ ) as stream:
173
+ async for event in stream:
174
+ output = event
175
+ payload = event.payload
176
+ if (
177
+ isinstance(payload, TurnCompletedNotification)
178
+ and payload.turn.id == handle.id
179
+ ):
180
+ terminal = payload
181
+ if payload.turn.status == TurnStatus.failed:
182
+ # The SDK raises after collecting a failed turn.
183
+ turn = payload.turn.model_copy(
184
+ update={"status": TurnStatus.completed}
185
+ )
186
+ output = replace(
187
+ event, payload=payload.model_copy(update={"turn": turn})
188
+ )
189
+ yield output # ruff: ignore[yield-in-context-manager-in-async-generator]
190
+
191
+ async with aclosing(events()) as stream:
192
+ result = await _collect_async_turn_result(stream, turn_id=handle.id)
193
+ # The collector only returns when it receives a matching terminal event.
194
+ terminal = cast("TurnCompletedNotification", terminal)
195
+ result.status = terminal.turn.status
196
+ result.error = terminal.turn.error
197
+ return result
198
+
199
+
200
+ async def run_codex(
201
+ *,
202
+ prompt: str,
203
+ cwd: str,
204
+ model: str | None,
205
+ effort: str | None,
206
+ sandbox: str,
207
+ network_access: bool,
208
+ binary: str | None,
209
+ ) -> dict[str, Any]:
210
+ """Run a single ephemeral Codex turn.
211
+
212
+ Args:
213
+ prompt: User input.
214
+ cwd: Resolved workspace directory.
215
+ model: Optional requested model.
216
+ effort: Optional reasoning effort.
217
+ sandbox: Sandbox mode.
218
+ network_access: Whether sandbox network access is enabled.
219
+ binary: Optional Codex binary path.
220
+
221
+ Returns:
222
+ The collected turn and thread metadata.
223
+ """
224
+ async with client_context(binary) as client:
225
+ started = await client._client.thread_start({ # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
226
+ "cwd": cwd,
227
+ "model": model,
228
+ "ephemeral": True,
229
+ "approvalPolicy": "never",
230
+ "sandbox": sandbox,
231
+ })
232
+ thread = started.thread
233
+ if network_access:
234
+ policy: dict[str, Any] = {
235
+ "type": "readOnly" if sandbox == "read-only" else "workspaceWrite",
236
+ "networkAccess": True,
237
+ }
238
+ turn, subscription = await client._client._start_turn( # pyright: ignore[reportPrivateUsage] # ruff: ignore[private-member-access]
239
+ thread.id,
240
+ prompt,
241
+ {
242
+ "threadId": thread.id,
243
+ "input": [{"type": "text", "text": prompt}],
244
+ "cwd": cwd,
245
+ "approvalPolicy": "never",
246
+ "sandboxPolicy": policy,
247
+ "effort": effort,
248
+ },
249
+ for_handle=True,
250
+ )
251
+ handle = AsyncTurnHandle(
252
+ client, thread.id, turn.turn.id, _subscription=subscription
253
+ )
254
+ else:
255
+ handle = await AsyncThread(client, thread.id).turn(
256
+ prompt,
257
+ cwd=cwd,
258
+ approval_mode=ApprovalMode.deny_all,
259
+ sandbox=Sandbox(sandbox),
260
+ effort=cast("ReasoningEffort | None", effort),
261
+ )
262
+ result = await collect_turn(handle)
263
+ items = [item.model_dump(mode="json", by_alias=True) for item in result.items]
264
+ commands = [item for item in items if item.get("type") == "commandExecution"]
265
+ return {
266
+ "agent": "codex",
267
+ "result": result.final_response,
268
+ "model": getattr(thread, "model", None),
269
+ "is_error": result.status != TurnStatus.completed
270
+ or result.error is not None,
271
+ "duration_ms": result.duration_ms or 0,
272
+ "usage": result.usage.model_dump(mode="json") if result.usage else None,
273
+ "backend": {
274
+ "id": result.id,
275
+ "status": result.status.value,
276
+ "commands": commands,
277
+ },
278
+ }