agentabi 0.2.2__tar.gz → 0.4.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.
- {agentabi-0.2.2/src/agentabi.egg-info → agentabi-0.4.0}/PKG-INFO +35 -53
- agentabi-0.4.0/README.md +89 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/__init__.py +1 -1
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/middleware/usage.py +8 -1
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/__init__.py +2 -0
- agentabi-0.4.0/src/agentabi/providers/agy_native.py +376 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/base.py +8 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/claude_native.py +118 -22
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/codex_native.py +27 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/gemini_native.py +23 -3
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/gemini_sdk.py +16 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/opencode_native.py +15 -0
- agentabi-0.4.0/src/agentabi/providers/pi_native.py +454 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/registry.py +5 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/__init__.py +12 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/capabilities.py +5 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/events.py +49 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/helpers.py +29 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/session.py +1 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/task.py +16 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/type_guards.py +6 -0
- {agentabi-0.2.2 → agentabi-0.4.0/src/agentabi.egg-info}/PKG-INFO +35 -53
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi.egg-info/SOURCES.txt +2 -0
- agentabi-0.2.2/README.md +0 -107
- {agentabi-0.2.2 → agentabi-0.4.0}/LICENSE +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/pyproject.toml +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/setup.cfg +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/auto_detect.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/middleware/__init__.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/middleware/logging.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/middleware/timeout.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/claude_sdk.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/providers/codex_sdk.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/py.typed +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/session.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/__init__.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi/types/ir/permissions.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi.egg-info/dependency_links.txt +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi.egg-info/requires.txt +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/src/agentabi.egg-info/top_level.txt +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/tests/test_ir_types.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/tests/test_middleware.py +0 -0
- {agentabi-0.2.2 → agentabi-0.4.0}/tests/test_session.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: agentabi
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Unified async Python API for driving coding agent CLIs — Claude Code, Codex, Gemini CLI, and more
|
|
5
5
|
Author-email: Peng Ding <pding.dp@foxmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -65,8 +65,10 @@ One interface. Any coding agent.
|
|
|
65
65
|
|-------|----------|--------|
|
|
66
66
|
| [Claude Code](https://github.com/anthropics/claude-code) | Anthropic | Implemented |
|
|
67
67
|
| [Codex](https://github.com/openai/codex) | OpenAI | Implemented |
|
|
68
|
-
| [
|
|
69
|
-
| [OpenCode](https://opencode
|
|
68
|
+
| [Antigravity (agy)](https://github.com/google/anthropic-agy) | Google | Implemented |
|
|
69
|
+
| [OpenCode](https://github.com/opencode-ai/opencode) | Community | Implemented |
|
|
70
|
+
| [Pi](https://github.com/anthropics/pi) | Community | Implemented |
|
|
71
|
+
| ~~Gemini CLI~~ | Google | Deprecated (use agy) |
|
|
70
72
|
|
|
71
73
|
## Installation
|
|
72
74
|
|
|
@@ -74,80 +76,60 @@ One interface. Any coding agent.
|
|
|
74
76
|
pip install agentabi
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
|
|
79
|
+
> **Note:** You also need at least one agent CLI installed: `claude`, `codex`, `agy`, `opencode`, or `pi`.
|
|
80
|
+
|
|
81
|
+
### Optional SDK dependencies
|
|
78
82
|
|
|
79
83
|
```bash
|
|
80
|
-
pip install agentabi[claude]
|
|
81
|
-
pip install agentabi[codex]
|
|
82
|
-
pip install agentabi[gemini] # Gemini CLI SDK support
|
|
83
|
-
pip install agentabi[all] # All optional SDKs
|
|
84
|
+
pip install agentabi[claude] # Claude Agent SDK
|
|
85
|
+
pip install agentabi[codex] # Codex SDK
|
|
84
86
|
```
|
|
85
87
|
|
|
86
|
-
> **Note:** Each agent's CLI must be installed separately (e.g., `claude`, `codex`, `gemini`, `opencode`).
|
|
87
|
-
|
|
88
88
|
## Quick Start
|
|
89
89
|
|
|
90
|
-
### Run a task
|
|
91
|
-
|
|
92
90
|
```python
|
|
93
91
|
import asyncio
|
|
94
92
|
from agentabi import Session
|
|
95
93
|
|
|
96
94
|
async def main():
|
|
97
95
|
session = Session(agent="claude_code")
|
|
98
|
-
result = await session.run(prompt="
|
|
99
|
-
print(result["
|
|
100
|
-
print(result["result_text"]) # agent's response
|
|
96
|
+
result = await session.run(prompt="What is 2+2?")
|
|
97
|
+
print(result["result_text"])
|
|
101
98
|
|
|
102
99
|
asyncio.run(main())
|
|
103
100
|
```
|
|
104
101
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
```python
|
|
108
|
-
async for event in session.stream(prompt="Explain this code"):
|
|
109
|
-
if event["type"] == "message_delta":
|
|
110
|
-
print(event["text"], end="")
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
### Sync convenience
|
|
114
|
-
|
|
115
|
-
```python
|
|
116
|
-
from agentabi import run_sync
|
|
117
|
-
|
|
118
|
-
result = run_sync(prompt="List Python files", agent="codex")
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
### Discover available agents
|
|
102
|
+
## Key Features
|
|
122
103
|
|
|
123
|
-
|
|
124
|
-
from agentabi import detect_agents, get_agent_capabilities
|
|
104
|
+
### Unified TaskConfig
|
|
125
105
|
|
|
126
|
-
agents
|
|
127
|
-
caps = get_agent_capabilities("claude_code")
|
|
128
|
-
print(caps["supports_streaming"]) # True
|
|
129
|
-
```
|
|
106
|
+
All agents accept the same `TaskConfig` with fields for:
|
|
130
107
|
|
|
131
|
-
|
|
108
|
+
- **Agent selection**: `agent`, `model`
|
|
109
|
+
- **Reasoning control**: `thinking_level` (`"off"`, `"low"`, `"medium"`, `"high"`, `"max"`)
|
|
110
|
+
- **Structured output**: `output_schema` (JSON Schema)
|
|
111
|
+
- **Session management**: `session_id`, `resume`, `ephemeral`
|
|
112
|
+
- **Workspace**: `working_dir`, `additional_dirs`, `files`
|
|
113
|
+
- **Permissions**: `permissions`, `allowed_tools`, `disallowed_tools`
|
|
114
|
+
- **System prompts**: `system_prompt`, `append_system_prompt`
|
|
132
115
|
|
|
133
|
-
|
|
134
|
-
- **Agent-to-Agent Calls** — Translation layer for inter-agent invocation
|
|
135
|
-
- **Benchmarking** — Run the same task across agents, compare results
|
|
136
|
-
- **Fallback & Routing** — Automatic failover and cost-aware routing
|
|
137
|
-
- **Middleware Pipeline** — Inject logging, metering, security scanning, audit trails
|
|
138
|
-
- **CI/CD Integration** — Vendor-agnostic agent integration for pipelines
|
|
116
|
+
### Unified IR Events
|
|
139
117
|
|
|
140
|
-
|
|
118
|
+
All agents emit the same streaming events:
|
|
141
119
|
|
|
142
|
-
`
|
|
120
|
+
- `session_start` / `session_end` — session lifecycle
|
|
121
|
+
- `message_start` / `message_delta` / `message_end` — text streaming
|
|
122
|
+
- `content_block_start` / `content_block_end` — content block boundaries
|
|
123
|
+
- `reasoning_delta` — thinking/reasoning text (Claude, Pi)
|
|
124
|
+
- `tool_use` / `tool_result` — tool calls
|
|
125
|
+
- `usage` — token counts (including `reasoning_tokens`)
|
|
126
|
+
- `error` — error reporting
|
|
143
127
|
|
|
144
|
-
|
|
145
|
-
agentabi → Agent CLI unified interface → like an OS ABI
|
|
146
|
-
llm-rosetta → LLM API format conversion → like a compiler IR
|
|
147
|
-
```
|
|
128
|
+
## Documentation
|
|
148
129
|
|
|
149
|
-
- [
|
|
130
|
+
- [English docs](https://agentabi-en.readthedocs.io/)
|
|
131
|
+
- [中文文档](https://agentabi-zh.readthedocs.io/)
|
|
150
132
|
|
|
151
133
|
## License
|
|
152
134
|
|
|
153
|
-
|
|
135
|
+
MIT
|
agentabi-0.4.0/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# agentabi
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/agentabi/)
|
|
4
|
+
[](https://github.com/Oaklight/agentabi/releases/latest)
|
|
5
|
+
[](https://github.com/Oaklight/agentabi/actions/workflows/ci.yml)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
Unified interface layer for agentic coding CLIs.
|
|
9
|
+
|
|
10
|
+
One interface. Any coding agent.
|
|
11
|
+
|
|
12
|
+
## What is agentabi?
|
|
13
|
+
|
|
14
|
+
`agentabi` provides a stable, unified interface (an "ABI") for interacting with different agentic coding CLIs. Write your integration once, swap agents with a config change.
|
|
15
|
+
|
|
16
|
+
### Supported Agents
|
|
17
|
+
|
|
18
|
+
| Agent | Provider | Status |
|
|
19
|
+
|-------|----------|--------|
|
|
20
|
+
| [Claude Code](https://github.com/anthropics/claude-code) | Anthropic | Implemented |
|
|
21
|
+
| [Codex](https://github.com/openai/codex) | OpenAI | Implemented |
|
|
22
|
+
| [Antigravity (agy)](https://github.com/google/anthropic-agy) | Google | Implemented |
|
|
23
|
+
| [OpenCode](https://github.com/opencode-ai/opencode) | Community | Implemented |
|
|
24
|
+
| [Pi](https://github.com/anthropics/pi) | Community | Implemented |
|
|
25
|
+
| ~~Gemini CLI~~ | Google | Deprecated (use agy) |
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install agentabi
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
> **Note:** You also need at least one agent CLI installed: `claude`, `codex`, `agy`, `opencode`, or `pi`.
|
|
34
|
+
|
|
35
|
+
### Optional SDK dependencies
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install agentabi[claude] # Claude Agent SDK
|
|
39
|
+
pip install agentabi[codex] # Codex SDK
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quick Start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
from agentabi import Session
|
|
47
|
+
|
|
48
|
+
async def main():
|
|
49
|
+
session = Session(agent="claude_code")
|
|
50
|
+
result = await session.run(prompt="What is 2+2?")
|
|
51
|
+
print(result["result_text"])
|
|
52
|
+
|
|
53
|
+
asyncio.run(main())
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Key Features
|
|
57
|
+
|
|
58
|
+
### Unified TaskConfig
|
|
59
|
+
|
|
60
|
+
All agents accept the same `TaskConfig` with fields for:
|
|
61
|
+
|
|
62
|
+
- **Agent selection**: `agent`, `model`
|
|
63
|
+
- **Reasoning control**: `thinking_level` (`"off"`, `"low"`, `"medium"`, `"high"`, `"max"`)
|
|
64
|
+
- **Structured output**: `output_schema` (JSON Schema)
|
|
65
|
+
- **Session management**: `session_id`, `resume`, `ephemeral`
|
|
66
|
+
- **Workspace**: `working_dir`, `additional_dirs`, `files`
|
|
67
|
+
- **Permissions**: `permissions`, `allowed_tools`, `disallowed_tools`
|
|
68
|
+
- **System prompts**: `system_prompt`, `append_system_prompt`
|
|
69
|
+
|
|
70
|
+
### Unified IR Events
|
|
71
|
+
|
|
72
|
+
All agents emit the same streaming events:
|
|
73
|
+
|
|
74
|
+
- `session_start` / `session_end` — session lifecycle
|
|
75
|
+
- `message_start` / `message_delta` / `message_end` — text streaming
|
|
76
|
+
- `content_block_start` / `content_block_end` — content block boundaries
|
|
77
|
+
- `reasoning_delta` — thinking/reasoning text (Claude, Pi)
|
|
78
|
+
- `tool_use` / `tool_result` — tool calls
|
|
79
|
+
- `usage` — token counts (including `reasoning_tokens`)
|
|
80
|
+
- `error` — error reporting
|
|
81
|
+
|
|
82
|
+
## Documentation
|
|
83
|
+
|
|
84
|
+
- [English docs](https://agentabi-en.readthedocs.io/)
|
|
85
|
+
- [中文文档](https://agentabi-zh.readthedocs.io/)
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
MIT
|
|
@@ -27,6 +27,7 @@ class UsageSummary(TypedDict, total=False):
|
|
|
27
27
|
total_cache_read_tokens: int
|
|
28
28
|
total_cache_creation_tokens: int
|
|
29
29
|
total_tokens: int
|
|
30
|
+
total_reasoning_tokens: int
|
|
30
31
|
total_cost_usd: float
|
|
31
32
|
|
|
32
33
|
|
|
@@ -62,6 +63,7 @@ class UsageMeterMiddleware:
|
|
|
62
63
|
self._cache_read_tokens = 0
|
|
63
64
|
self._cache_creation_tokens = 0
|
|
64
65
|
self._total_tokens = 0
|
|
66
|
+
self._reasoning_tokens = 0
|
|
65
67
|
self._cost_usd = 0.0
|
|
66
68
|
|
|
67
69
|
@property
|
|
@@ -83,6 +85,8 @@ class UsageMeterMiddleware:
|
|
|
83
85
|
result["total_cache_read_tokens"] = self._cache_read_tokens
|
|
84
86
|
if self._cache_creation_tokens:
|
|
85
87
|
result["total_cache_creation_tokens"] = self._cache_creation_tokens
|
|
88
|
+
if self._reasoning_tokens:
|
|
89
|
+
result["total_reasoning_tokens"] = self._reasoning_tokens
|
|
86
90
|
return result
|
|
87
91
|
|
|
88
92
|
def reset(self) -> None:
|
|
@@ -94,6 +98,7 @@ class UsageMeterMiddleware:
|
|
|
94
98
|
self._cache_read_tokens = 0
|
|
95
99
|
self._cache_creation_tokens = 0
|
|
96
100
|
self._total_tokens = 0
|
|
101
|
+
self._reasoning_tokens = 0
|
|
97
102
|
self._cost_usd = 0.0
|
|
98
103
|
|
|
99
104
|
def __call__(self, handler: StreamHandler) -> StreamHandler:
|
|
@@ -115,6 +120,7 @@ class UsageMeterMiddleware:
|
|
|
115
120
|
"cache_creation_tokens", 0
|
|
116
121
|
)
|
|
117
122
|
self._total_tokens += usage.get("total_tokens", 0)
|
|
123
|
+
self._reasoning_tokens += usage.get("reasoning_tokens", 0)
|
|
118
124
|
if cost is not None:
|
|
119
125
|
self._cost_usd += cost
|
|
120
126
|
yield event
|
|
@@ -124,7 +130,8 @@ class UsageMeterMiddleware:
|
|
|
124
130
|
def __repr__(self) -> str:
|
|
125
131
|
return (
|
|
126
132
|
f"UsageMeterMiddleware(calls={self._call_count}, "
|
|
127
|
-
f"tokens={self._total_tokens},
|
|
133
|
+
f"tokens={self._total_tokens}, "
|
|
134
|
+
f"reasoning={self._reasoning_tokens}, cost=${self._cost_usd:.4f})"
|
|
128
135
|
)
|
|
129
136
|
|
|
130
137
|
|
|
@@ -5,6 +5,7 @@ Flat provider model: each provider implements the same Protocol
|
|
|
5
5
|
for driving a specific agent CLI or SDK.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
from .agy_native import AgyNativeProvider
|
|
8
9
|
from .base import Provider
|
|
9
10
|
from .registry import (
|
|
10
11
|
AgentNotAvailable,
|
|
@@ -14,6 +15,7 @@ from .registry import (
|
|
|
14
15
|
)
|
|
15
16
|
|
|
16
17
|
__all__ = [
|
|
18
|
+
"AgyNativeProvider",
|
|
17
19
|
"Provider",
|
|
18
20
|
"AgentNotAvailable",
|
|
19
21
|
"resolve_provider",
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""
|
|
2
|
+
agentabi - Antigravity CLI (agy) Native Provider
|
|
3
|
+
|
|
4
|
+
Native subprocess provider for the agy CLI (Google's agentic coding CLI).
|
|
5
|
+
Runs `agy --output-format stream-json [options] -p <prompt>` and parses JSONL output.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shutil
|
|
14
|
+
from collections.abc import AsyncIterator
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from ..types.ir.capabilities import AgentCapabilities
|
|
18
|
+
from ..types.ir.events import (
|
|
19
|
+
ErrorEvent,
|
|
20
|
+
IREvent,
|
|
21
|
+
MessageDeltaEvent,
|
|
22
|
+
MessageEndEvent,
|
|
23
|
+
MessageStartEvent,
|
|
24
|
+
SessionEndEvent,
|
|
25
|
+
SessionStartEvent,
|
|
26
|
+
ToolResultEvent,
|
|
27
|
+
ToolUseEvent,
|
|
28
|
+
UsageEvent,
|
|
29
|
+
UsageInfo,
|
|
30
|
+
)
|
|
31
|
+
from ..types.ir.session import SessionResult
|
|
32
|
+
from ..types.ir.task import TaskConfig
|
|
33
|
+
from .base import collect_subprocess_errors
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AgyNativeProvider:
|
|
37
|
+
"""Native subprocess provider for Antigravity CLI (agy).
|
|
38
|
+
|
|
39
|
+
Runs `agy --output-format stream-json [options] -p <prompt>` as a
|
|
40
|
+
subprocess and parses stream-json events into IR events.
|
|
41
|
+
|
|
42
|
+
agy stream-json event types:
|
|
43
|
+
- event: "init" — session metadata (conversation_id, cwd, tools)
|
|
44
|
+
- event: "step_update" — step progress with step_type variants:
|
|
45
|
+
- "user_input" — user input step (skipped)
|
|
46
|
+
- "agent_response" — assistant response with text_delta and usage
|
|
47
|
+
- "tool_use" — tool invocation
|
|
48
|
+
- "checkpoint" — checkpoint marker (skipped)
|
|
49
|
+
- "error_message" — error during step (skipped, errors in result)
|
|
50
|
+
- event: "result" — final result with status, response, usage
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def is_available() -> bool:
|
|
55
|
+
"""Check if `agy` CLI is available."""
|
|
56
|
+
return shutil.which("agy") is not None
|
|
57
|
+
|
|
58
|
+
def capabilities(self) -> AgentCapabilities:
|
|
59
|
+
"""Declare Antigravity capabilities."""
|
|
60
|
+
return {
|
|
61
|
+
"name": "Antigravity",
|
|
62
|
+
"agent_type": "agy",
|
|
63
|
+
"supports_streaming": True,
|
|
64
|
+
"supports_mcp": True,
|
|
65
|
+
"supports_session_resume": True,
|
|
66
|
+
"supports_system_prompt": False,
|
|
67
|
+
"supports_tool_filtering": False,
|
|
68
|
+
"supports_permissions": True,
|
|
69
|
+
"supports_structured_output": True,
|
|
70
|
+
"supports_additional_dirs": True,
|
|
71
|
+
"supports_multi_turn": True,
|
|
72
|
+
"transport": "subprocess",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async def stream(self, task: TaskConfig) -> AsyncIterator[IREvent]:
|
|
76
|
+
"""Run task via agy CLI and yield IR events."""
|
|
77
|
+
cmd = self._build_command(task)
|
|
78
|
+
merged_env = self._build_env(task)
|
|
79
|
+
|
|
80
|
+
timeout = task.get("timeout")
|
|
81
|
+
proc = await asyncio.create_subprocess_exec(
|
|
82
|
+
*cmd,
|
|
83
|
+
stdout=asyncio.subprocess.PIPE,
|
|
84
|
+
stderr=asyncio.subprocess.PIPE,
|
|
85
|
+
env=merged_env,
|
|
86
|
+
cwd=task.get("working_dir"),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
timed_out = False
|
|
90
|
+
timeout_task: asyncio.Task[None] | None = None
|
|
91
|
+
if timeout:
|
|
92
|
+
|
|
93
|
+
async def _kill_after_timeout() -> None:
|
|
94
|
+
nonlocal timed_out
|
|
95
|
+
await asyncio.sleep(timeout)
|
|
96
|
+
if proc.returncode is None:
|
|
97
|
+
timed_out = True
|
|
98
|
+
proc.kill()
|
|
99
|
+
|
|
100
|
+
timeout_task = asyncio.create_task(_kill_after_timeout())
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
assert proc.stdout is not None
|
|
104
|
+
async for line_bytes in proc.stdout:
|
|
105
|
+
line = line_bytes.decode().rstrip("\n").rstrip("\r")
|
|
106
|
+
if not line:
|
|
107
|
+
continue
|
|
108
|
+
try:
|
|
109
|
+
raw = json.loads(line)
|
|
110
|
+
except json.JSONDecodeError:
|
|
111
|
+
continue
|
|
112
|
+
for event in self._parse_event(raw):
|
|
113
|
+
yield event
|
|
114
|
+
|
|
115
|
+
await proc.wait()
|
|
116
|
+
for err in await collect_subprocess_errors(
|
|
117
|
+
proc, timed_out=timed_out, timeout_seconds=timeout
|
|
118
|
+
):
|
|
119
|
+
yield err
|
|
120
|
+
finally:
|
|
121
|
+
if timeout_task and not timeout_task.done():
|
|
122
|
+
timeout_task.cancel()
|
|
123
|
+
if proc.returncode is None:
|
|
124
|
+
proc.terminate()
|
|
125
|
+
try:
|
|
126
|
+
await asyncio.wait_for(proc.wait(), timeout=5)
|
|
127
|
+
except asyncio.TimeoutError:
|
|
128
|
+
proc.kill()
|
|
129
|
+
await proc.wait()
|
|
130
|
+
|
|
131
|
+
async def run(self, task: TaskConfig) -> SessionResult:
|
|
132
|
+
"""Run task and return aggregated result."""
|
|
133
|
+
from .base import default_run
|
|
134
|
+
|
|
135
|
+
return await default_run(self, task)
|
|
136
|
+
|
|
137
|
+
# ========== Private: environment ==========
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def _build_env(task: TaskConfig) -> dict[str, str]:
|
|
141
|
+
"""Build merged environment with agy-specific variable mapping.
|
|
142
|
+
|
|
143
|
+
Maps generic OPENAI_BASE_URL / OPENAI_API_KEY to agy-specific
|
|
144
|
+
equivalents (GOOGLE_GEMINI_BASE_URL / GEMINI_API_KEY) when the
|
|
145
|
+
agy-native env vars are not already set.
|
|
146
|
+
"""
|
|
147
|
+
task_env = task.get("env") or {}
|
|
148
|
+
merged_env = {**os.environ, **task_env}
|
|
149
|
+
|
|
150
|
+
if not task_env.get("GOOGLE_GEMINI_BASE_URL") and task_env.get(
|
|
151
|
+
"OPENAI_BASE_URL"
|
|
152
|
+
):
|
|
153
|
+
base = task_env["OPENAI_BASE_URL"].rstrip("/")
|
|
154
|
+
if base.endswith("/v1"):
|
|
155
|
+
base = base[:-3]
|
|
156
|
+
merged_env["GOOGLE_GEMINI_BASE_URL"] = base
|
|
157
|
+
|
|
158
|
+
if not task_env.get("GEMINI_API_KEY") and task_env.get("OPENAI_API_KEY"):
|
|
159
|
+
merged_env["GEMINI_API_KEY"] = task_env["OPENAI_API_KEY"]
|
|
160
|
+
|
|
161
|
+
return merged_env
|
|
162
|
+
|
|
163
|
+
# ========== Private: command building ==========
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _build_command(task: TaskConfig) -> list[str]:
|
|
167
|
+
"""Convert TaskConfig to agy CLI arguments."""
|
|
168
|
+
cmd = ["agy", "--output-format", "stream-json"]
|
|
169
|
+
|
|
170
|
+
if "model" in task:
|
|
171
|
+
cmd.extend(["--model", task["model"]])
|
|
172
|
+
|
|
173
|
+
AgyNativeProvider._add_permission_flags(cmd, task)
|
|
174
|
+
AgyNativeProvider._add_session_flags(cmd, task)
|
|
175
|
+
|
|
176
|
+
timeout = task.get("timeout")
|
|
177
|
+
if timeout is not None and timeout > 0:
|
|
178
|
+
cmd.extend(["--print-timeout", f"{int(timeout)}s"])
|
|
179
|
+
|
|
180
|
+
AgyNativeProvider._add_extension_flags(cmd, task)
|
|
181
|
+
|
|
182
|
+
cmd.extend(["-p", task["prompt"]])
|
|
183
|
+
return cmd
|
|
184
|
+
|
|
185
|
+
@staticmethod
|
|
186
|
+
def _add_permission_flags(cmd: list[str], task: TaskConfig) -> None:
|
|
187
|
+
"""Append permission/mode flags."""
|
|
188
|
+
permissions = task.get("permissions")
|
|
189
|
+
if permissions:
|
|
190
|
+
level = permissions.get("level")
|
|
191
|
+
if level == "full_auto":
|
|
192
|
+
cmd.append("--dangerously-skip-permissions")
|
|
193
|
+
elif level == "accept_edits":
|
|
194
|
+
cmd.extend(["--mode", "accept-edits"])
|
|
195
|
+
elif level == "plan":
|
|
196
|
+
cmd.extend(["--mode", "plan"])
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def _add_session_flags(cmd: list[str], task: TaskConfig) -> None:
|
|
200
|
+
"""Append session resume flags."""
|
|
201
|
+
if "session_id" in task and task.get("resume"):
|
|
202
|
+
cmd.extend(["--conversation", task["session_id"]])
|
|
203
|
+
elif task.get("resume"):
|
|
204
|
+
cmd.append("--continue")
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def _add_extension_flags(cmd: list[str], task: TaskConfig) -> None:
|
|
208
|
+
"""Append agent-specific extension flags."""
|
|
209
|
+
ext = task.get("agent_extensions") or {}
|
|
210
|
+
|
|
211
|
+
if "effort" in ext:
|
|
212
|
+
cmd.extend(["--effort", ext["effort"]])
|
|
213
|
+
|
|
214
|
+
if ext.get("sandbox"):
|
|
215
|
+
cmd.append("--sandbox")
|
|
216
|
+
|
|
217
|
+
if ext.get("disable_slash_commands"):
|
|
218
|
+
cmd.append("--disable-slash-commands")
|
|
219
|
+
|
|
220
|
+
if "agent" in ext:
|
|
221
|
+
cmd.extend(["--agent", ext["agent"]])
|
|
222
|
+
|
|
223
|
+
schema = task.get("output_schema") or ext.get("json_schema")
|
|
224
|
+
if schema:
|
|
225
|
+
if isinstance(schema, dict):
|
|
226
|
+
import json as _json
|
|
227
|
+
|
|
228
|
+
schema = _json.dumps(schema)
|
|
229
|
+
cmd.extend(["--json-schema", schema])
|
|
230
|
+
|
|
231
|
+
for d in task.get("additional_dirs") or ext.get("add_dirs") or []:
|
|
232
|
+
cmd.extend(["--add-dir", d])
|
|
233
|
+
|
|
234
|
+
# ========== Private: event parsing ==========
|
|
235
|
+
|
|
236
|
+
@staticmethod
|
|
237
|
+
def _parse_event(raw: dict[str, Any]) -> list[IREvent]:
|
|
238
|
+
"""Convert an agy stream-json event to IR events."""
|
|
239
|
+
event_type = raw.get("event")
|
|
240
|
+
|
|
241
|
+
if event_type == "init":
|
|
242
|
+
return AgyNativeProvider._handle_init(raw)
|
|
243
|
+
elif event_type == "step_update":
|
|
244
|
+
return AgyNativeProvider._handle_step_update(raw)
|
|
245
|
+
elif event_type == "result":
|
|
246
|
+
return AgyNativeProvider._handle_result(raw)
|
|
247
|
+
return []
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
def _handle_init(raw: dict[str, Any]) -> list[IREvent]:
|
|
251
|
+
"""Handle init event — emits SessionStartEvent."""
|
|
252
|
+
start: SessionStartEvent = {
|
|
253
|
+
"type": "session_start",
|
|
254
|
+
"session_id": raw.get("conversation_id", ""),
|
|
255
|
+
"agent": "agy",
|
|
256
|
+
}
|
|
257
|
+
init_data = raw.get("init", {})
|
|
258
|
+
cwd = init_data.get("cwd")
|
|
259
|
+
if cwd:
|
|
260
|
+
start["working_dir"] = cwd
|
|
261
|
+
tools = init_data.get("tools")
|
|
262
|
+
if tools:
|
|
263
|
+
start["tools"] = tools
|
|
264
|
+
return [start]
|
|
265
|
+
|
|
266
|
+
@staticmethod
|
|
267
|
+
def _handle_step_update(raw: dict[str, Any]) -> list[IREvent]:
|
|
268
|
+
"""Handle step_update event — dispatches by step_type."""
|
|
269
|
+
step = raw.get("step_update", {})
|
|
270
|
+
step_type = step.get("step_type", "")
|
|
271
|
+
|
|
272
|
+
if step_type == "agent_response":
|
|
273
|
+
return AgyNativeProvider._handle_agent_response(step)
|
|
274
|
+
elif step_type == "tool_use":
|
|
275
|
+
return AgyNativeProvider._handle_tool_use_step(step)
|
|
276
|
+
# user_input, checkpoint, error_message — skip
|
|
277
|
+
return []
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def _handle_agent_response(step: dict[str, Any]) -> list[IREvent]:
|
|
281
|
+
"""Handle agent_response step — emits message events."""
|
|
282
|
+
results: list[IREvent] = []
|
|
283
|
+
|
|
284
|
+
msg_start: MessageStartEvent = {
|
|
285
|
+
"type": "message_start",
|
|
286
|
+
"role": "assistant",
|
|
287
|
+
}
|
|
288
|
+
results.append(msg_start)
|
|
289
|
+
|
|
290
|
+
text_delta = step.get("text_delta", "")
|
|
291
|
+
if text_delta:
|
|
292
|
+
delta: MessageDeltaEvent = {
|
|
293
|
+
"type": "message_delta",
|
|
294
|
+
"text": text_delta,
|
|
295
|
+
}
|
|
296
|
+
results.append(delta)
|
|
297
|
+
|
|
298
|
+
end: MessageEndEvent = {"type": "message_end"}
|
|
299
|
+
if text_delta:
|
|
300
|
+
end["text"] = text_delta
|
|
301
|
+
results.append(end)
|
|
302
|
+
|
|
303
|
+
return results
|
|
304
|
+
|
|
305
|
+
@staticmethod
|
|
306
|
+
def _handle_tool_use_step(step: dict[str, Any]) -> list[IREvent]:
|
|
307
|
+
"""Handle tool_use step — emits ToolUseEvent and optionally ToolResultEvent."""
|
|
308
|
+
results: list[IREvent] = []
|
|
309
|
+
|
|
310
|
+
tool_event: ToolUseEvent = {
|
|
311
|
+
"type": "tool_use",
|
|
312
|
+
"tool_use_id": step.get("tool_use_id", ""),
|
|
313
|
+
"tool_name": step.get("tool_name", ""),
|
|
314
|
+
"tool_input": step.get("tool_input", {}),
|
|
315
|
+
}
|
|
316
|
+
results.append(tool_event)
|
|
317
|
+
|
|
318
|
+
# If the step has a result, emit ToolResultEvent
|
|
319
|
+
tool_result = step.get("tool_result")
|
|
320
|
+
if tool_result is not None:
|
|
321
|
+
result: ToolResultEvent = {
|
|
322
|
+
"type": "tool_result",
|
|
323
|
+
"tool_use_id": step.get("tool_use_id", ""),
|
|
324
|
+
"content": str(tool_result),
|
|
325
|
+
}
|
|
326
|
+
if step.get("is_error"):
|
|
327
|
+
result["is_error"] = True
|
|
328
|
+
results.append(result)
|
|
329
|
+
|
|
330
|
+
return results
|
|
331
|
+
|
|
332
|
+
@staticmethod
|
|
333
|
+
def _handle_result(raw: dict[str, Any]) -> list[IREvent]:
|
|
334
|
+
"""Handle result event — emits UsageEvent + SessionEndEvent (+ ErrorEvent)."""
|
|
335
|
+
results: list[IREvent] = []
|
|
336
|
+
result_data = raw.get("result", {})
|
|
337
|
+
|
|
338
|
+
# Usage
|
|
339
|
+
raw_usage = result_data.get("usage", {})
|
|
340
|
+
usage: UsageInfo = {}
|
|
341
|
+
if raw_usage.get("input_tokens"):
|
|
342
|
+
usage["input_tokens"] = raw_usage["input_tokens"]
|
|
343
|
+
if raw_usage.get("output_tokens"):
|
|
344
|
+
usage["output_tokens"] = raw_usage["output_tokens"]
|
|
345
|
+
if raw_usage.get("total_tokens"):
|
|
346
|
+
usage["total_tokens"] = raw_usage["total_tokens"]
|
|
347
|
+
if raw_usage.get("cache_read_tokens"):
|
|
348
|
+
usage["cache_read_tokens"] = raw_usage["cache_read_tokens"]
|
|
349
|
+
if raw_usage.get("thinking_tokens"):
|
|
350
|
+
usage["reasoning_tokens"] = raw_usage["thinking_tokens"]
|
|
351
|
+
|
|
352
|
+
usage_event: UsageEvent = {"type": "usage", "usage": usage}
|
|
353
|
+
results.append(usage_event)
|
|
354
|
+
|
|
355
|
+
# Error if status != SUCCESS
|
|
356
|
+
status = result_data.get("status", "")
|
|
357
|
+
if status != "SUCCESS":
|
|
358
|
+
error_msg = result_data.get("error", f"agy exited with status: {status}")
|
|
359
|
+
err: ErrorEvent = {
|
|
360
|
+
"type": "error",
|
|
361
|
+
"error": str(error_msg),
|
|
362
|
+
"is_fatal": True,
|
|
363
|
+
}
|
|
364
|
+
results.append(err)
|
|
365
|
+
|
|
366
|
+
# Session end
|
|
367
|
+
session_end: SessionEndEvent = {"type": "session_end"}
|
|
368
|
+
conv_id = result_data.get("conversation_id")
|
|
369
|
+
if conv_id:
|
|
370
|
+
session_end["session_id"] = conv_id
|
|
371
|
+
results.append(session_end)
|
|
372
|
+
|
|
373
|
+
return results
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
__all__ = ["AgyNativeProvider"]
|