open-agent-router 0.1.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.
- agent_router/__init__.py +6 -0
- agent_router/adapters/__init__.py +19 -0
- agent_router/adapters/base.py +175 -0
- agent_router/adapters/claude.py +79 -0
- agent_router/adapters/cline.py +120 -0
- agent_router/adapters/kimi.py +70 -0
- agent_router/adapters/opencode.py +88 -0
- agent_router/api.py +666 -0
- agent_router/auth.py +175 -0
- agent_router/classifier.py +790 -0
- agent_router/cli.py +1521 -0
- agent_router/client.py +163 -0
- agent_router/clock.py +70 -0
- agent_router/collectors/__init__.py +1 -0
- agent_router/collectors/claude_statusline.py +64 -0
- agent_router/collectors/opencode_stats.py +136 -0
- agent_router/config.example.toml +202 -0
- agent_router/config.py +1289 -0
- agent_router/dispatcher.py +1266 -0
- agent_router/events.py +247 -0
- agent_router/export.py +480 -0
- agent_router/jobs.py +295 -0
- agent_router/jobstore.py +941 -0
- agent_router/ledger.py +181 -0
- agent_router/lifecycle.py +70 -0
- agent_router/mcp_server.py +157 -0
- agent_router/pacing.py +117 -0
- agent_router/periods.py +122 -0
- agent_router/plugins.py +22 -0
- agent_router/policy.py +217 -0
- agent_router/prices.py +51 -0
- agent_router/registry.py +163 -0
- agent_router/runner.py +513 -0
- agent_router/service.py +427 -0
- agent_router/settings_store.py +91 -0
- agent_router/sinks.py +113 -0
- agent_router/spend.py +80 -0
- agent_router/static/app.css +74 -0
- agent_router/static/app.js +74 -0
- agent_router/statusline.py +125 -0
- agent_router/store.py +351 -0
- agent_router/templates/_advice.html +49 -0
- agent_router/templates/_job.html +134 -0
- agent_router/templates/_jobs.html +43 -0
- agent_router/templates/_limits.html +39 -0
- agent_router/templates/base.html +29 -0
- agent_router/templates/calibrate.html +39 -0
- agent_router/templates/index.html +15 -0
- agent_router/templates/job.html +4 -0
- agent_router/templates/jobs.html +4 -0
- agent_router/templates/login.html +9 -0
- agent_router/templates/message.html +5 -0
- agent_router/web.py +444 -0
- agent_router/worktree.py +346 -0
- open_agent_router-0.1.0.dist-info/METADATA +286 -0
- open_agent_router-0.1.0.dist-info/RECORD +59 -0
- open_agent_router-0.1.0.dist-info/WHEEL +4 -0
- open_agent_router-0.1.0.dist-info/entry_points.txt +12 -0
- open_agent_router-0.1.0.dist-info/licenses/LICENSE +21 -0
agent_router/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Harness adapters: command building and output parsing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from agent_router.adapters.base import (
|
|
6
|
+
MAX_ARG_CHARS,
|
|
7
|
+
Adapter,
|
|
8
|
+
RunOutcome,
|
|
9
|
+
looks_like_limit,
|
|
10
|
+
with_preamble,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"MAX_ARG_CHARS",
|
|
15
|
+
"Adapter",
|
|
16
|
+
"RunOutcome",
|
|
17
|
+
"looks_like_limit",
|
|
18
|
+
"with_preamble",
|
|
19
|
+
]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Shared helpers for harness adapters: run outcome, preamble, and limit detection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Literal, Protocol
|
|
11
|
+
|
|
12
|
+
from agent_router.config import Mode
|
|
13
|
+
from agent_router.runner import Invocation, ResolvedExecutable
|
|
14
|
+
|
|
15
|
+
MAX_ARG_CHARS = 20_000
|
|
16
|
+
ERROR_MAX_CHARS = 500
|
|
17
|
+
EMPTY_OUTPUT = "empty output"
|
|
18
|
+
|
|
19
|
+
_RULES = (
|
|
20
|
+
"- Work only inside the current working directory.",
|
|
21
|
+
"- Do not run `git commit`, `git push`, or any command that rewrites git history.",
|
|
22
|
+
"- Do not start long-running background processes.",
|
|
23
|
+
"- When finished, reply with a concise final report of what you did or found.",
|
|
24
|
+
)
|
|
25
|
+
_READ_RULE = "- This is a read-only task: do not create, modify, or delete any files."
|
|
26
|
+
|
|
27
|
+
_LIMIT_SIGNS = re.compile(
|
|
28
|
+
r"rate[ _-]?limit|usage[ _-]?limit|quota|limit reached|too many requests|(?<!\d)429(?!\d)",
|
|
29
|
+
re.IGNORECASE,
|
|
30
|
+
)
|
|
31
|
+
_RESET_AT = re.compile(
|
|
32
|
+
r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class RunOutcome:
|
|
38
|
+
status: Literal["ok", "error", "limit"]
|
|
39
|
+
text: str = ""
|
|
40
|
+
tokens_in: int | None = None
|
|
41
|
+
tokens_out: int | None = None
|
|
42
|
+
cost_usd: float | None = None
|
|
43
|
+
session_id: str | None = None
|
|
44
|
+
limit_reset_at: datetime | None = None
|
|
45
|
+
error: str | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Adapter(Protocol):
|
|
49
|
+
name: str
|
|
50
|
+
|
|
51
|
+
def build(
|
|
52
|
+
self, text: str, mode: Mode, model: str, exe: ResolvedExecutable, prompt_file: Path
|
|
53
|
+
) -> Invocation: ...
|
|
54
|
+
|
|
55
|
+
def parse(self, stdout: str, stderr: str, exit_code: int | None) -> RunOutcome: ...
|
|
56
|
+
|
|
57
|
+
def is_final_line(self, line: str) -> bool: ...
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def with_preamble(prompt: str, mode: Mode) -> str:
|
|
61
|
+
"""Prompt prefixed with executor rules; read mode adds a ban on changing files."""
|
|
62
|
+
lines = ["[agent-router] You are executing a delegated task for an orchestrator.", "Rules:"]
|
|
63
|
+
lines.extend(_RULES)
|
|
64
|
+
if mode == "read":
|
|
65
|
+
lines.append(_READ_RULE)
|
|
66
|
+
lines.append("---")
|
|
67
|
+
return "\n".join(lines) + "\n" + prompt
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def looks_like_limit(text: str) -> bool:
|
|
71
|
+
"""Whether a harness service message looks like hitting the subscription limit."""
|
|
72
|
+
return bool(_LIMIT_SIGNS.search(text))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def reset_time(text: str) -> datetime | None:
|
|
76
|
+
"""Limit reset time from a message: the first ISO 8601 timestamp with a timezone."""
|
|
77
|
+
for match in _RESET_AT.finditer(text):
|
|
78
|
+
raw = match.group(0).replace(" ", "T")
|
|
79
|
+
if raw.endswith("Z"):
|
|
80
|
+
raw = raw[:-1] + "+00:00"
|
|
81
|
+
try:
|
|
82
|
+
found = datetime.fromisoformat(raw)
|
|
83
|
+
except ValueError:
|
|
84
|
+
continue
|
|
85
|
+
if found.tzinfo is not None:
|
|
86
|
+
return found
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def executable(exe: ResolvedExecutable) -> str:
|
|
91
|
+
if exe.path is None:
|
|
92
|
+
raise ValueError("harness executable not found")
|
|
93
|
+
return str(exe.path)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def json_lines(stdout: str) -> tuple[list[dict[str, Any]], list[str]]:
|
|
97
|
+
"""Output lines split into JSON objects and everything else (harness service messages)."""
|
|
98
|
+
events: list[dict[str, Any]] = []
|
|
99
|
+
other: list[str] = []
|
|
100
|
+
for raw in stdout.splitlines():
|
|
101
|
+
line = raw.strip()
|
|
102
|
+
if not line:
|
|
103
|
+
continue
|
|
104
|
+
try:
|
|
105
|
+
value = json.loads(line)
|
|
106
|
+
except ValueError:
|
|
107
|
+
other.append(line)
|
|
108
|
+
continue
|
|
109
|
+
if isinstance(value, dict):
|
|
110
|
+
events.append(value)
|
|
111
|
+
else:
|
|
112
|
+
other.append(line)
|
|
113
|
+
return events, other
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def as_int(value: object) -> int:
|
|
117
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
118
|
+
return 0
|
|
119
|
+
return max(0, int(value))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _short(text: str) -> str:
|
|
123
|
+
text = text.strip()
|
|
124
|
+
return text if len(text) <= ERROR_MAX_CHARS else text[-ERROR_MAX_CHARS:]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _last_line(text: str) -> str:
|
|
128
|
+
for line in reversed(text.splitlines()):
|
|
129
|
+
if line.strip():
|
|
130
|
+
return line.strip()
|
|
131
|
+
return ""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def settle(
|
|
135
|
+
*,
|
|
136
|
+
exit_code: int | None,
|
|
137
|
+
text: str,
|
|
138
|
+
service: list[str],
|
|
139
|
+
stderr: str,
|
|
140
|
+
limit_hint: bool = False,
|
|
141
|
+
harness_error: str | None = None,
|
|
142
|
+
tokens_in: int | None = None,
|
|
143
|
+
tokens_out: int | None = None,
|
|
144
|
+
cost_usd: float | None = None,
|
|
145
|
+
session_id: str | None = None,
|
|
146
|
+
) -> RunOutcome:
|
|
147
|
+
"""Shared outcome resolution order.
|
|
148
|
+
|
|
149
|
+
Zero exit code with non-empty text is always ok. Otherwise limit, if limit signs appear
|
|
150
|
+
in the service messages (`service`, stderr) or the harness itself reported the error as
|
|
151
|
+
a limit (`limit_hint`); otherwise error. The model response text is not checked for
|
|
152
|
+
limit signs.
|
|
153
|
+
"""
|
|
154
|
+
common = {
|
|
155
|
+
"tokens_in": tokens_in,
|
|
156
|
+
"tokens_out": tokens_out,
|
|
157
|
+
"cost_usd": cost_usd,
|
|
158
|
+
"session_id": session_id,
|
|
159
|
+
}
|
|
160
|
+
if exit_code == 0 and text.strip():
|
|
161
|
+
return RunOutcome("ok", text=text, **common)
|
|
162
|
+
notes = "\n".join([*service, stderr])
|
|
163
|
+
if harness_error:
|
|
164
|
+
message = harness_error
|
|
165
|
+
elif exit_code == 0:
|
|
166
|
+
message = EMPTY_OUTPUT
|
|
167
|
+
else:
|
|
168
|
+
message = _last_line(stderr) or _last_line("\n".join(service))
|
|
169
|
+
if not message:
|
|
170
|
+
message = "process did not exit" if exit_code is None else f"exit code {exit_code}"
|
|
171
|
+
if limit_hint or looks_like_limit(notes):
|
|
172
|
+
return RunOutcome(
|
|
173
|
+
"limit", text=text, limit_reset_at=reset_time(notes), error=_short(message), **common
|
|
174
|
+
)
|
|
175
|
+
return RunOutcome("error", text=text, error=_short(message), **common)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Claude Code adapter: `claude -p --output-format json`, prompt passed via stdin.
|
|
2
|
+
|
|
3
|
+
The output format is taken from the documentation; it has not been verified live.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from agent_router.adapters.base import RunOutcome, as_int, executable, json_lines, settle
|
|
13
|
+
from agent_router.config import Mode
|
|
14
|
+
from agent_router.registry import HarnessSpec
|
|
15
|
+
from agent_router.runner import Invocation, ResolvedExecutable
|
|
16
|
+
|
|
17
|
+
_PERMISSION = {"read": "plan", "write": "acceptEdits"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _result_object(stdout: str) -> tuple[dict[str, Any] | None, list[str]]:
|
|
21
|
+
"""Result object: the whole stdout as one JSON document, or the last object line."""
|
|
22
|
+
try:
|
|
23
|
+
whole = json.loads(stdout)
|
|
24
|
+
except ValueError:
|
|
25
|
+
whole = None
|
|
26
|
+
if isinstance(whole, dict):
|
|
27
|
+
return whole, []
|
|
28
|
+
events, other = json_lines(stdout)
|
|
29
|
+
for event in reversed(events):
|
|
30
|
+
if "result" in event or "is_error" in event:
|
|
31
|
+
return event, other
|
|
32
|
+
return None, other
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ClaudeAdapter:
|
|
36
|
+
name = "claude"
|
|
37
|
+
|
|
38
|
+
def build(
|
|
39
|
+
self, text: str, mode: Mode, model: str, exe: ResolvedExecutable, prompt_file: Path
|
|
40
|
+
) -> Invocation:
|
|
41
|
+
argv = [executable(exe), "-p", "--output-format", "json", "--model", model]
|
|
42
|
+
argv += ["--permission-mode", _PERMISSION[mode]]
|
|
43
|
+
return Invocation(tuple(argv), stdin_text=text)
|
|
44
|
+
|
|
45
|
+
def parse(self, stdout: str, stderr: str, exit_code: int | None) -> RunOutcome:
|
|
46
|
+
result, service = _result_object(stdout)
|
|
47
|
+
if result is None:
|
|
48
|
+
return settle(exit_code=exit_code, text="", service=service, stderr=stderr)
|
|
49
|
+
raw = result.get("result")
|
|
50
|
+
answer = raw if isinstance(raw, str) else ""
|
|
51
|
+
failed = result.get("is_error") is True
|
|
52
|
+
usage = result.get("usage")
|
|
53
|
+
usage = usage if isinstance(usage, dict) else {}
|
|
54
|
+
cost = result.get("total_cost_usd")
|
|
55
|
+
session = result.get("session_id")
|
|
56
|
+
harness_error: str | None = None
|
|
57
|
+
if failed:
|
|
58
|
+
# with is_error, the result field holds the harness's message, not the model's reply
|
|
59
|
+
harness_error = answer.strip() or str(result.get("subtype") or "harness error")
|
|
60
|
+
service = [*service, harness_error]
|
|
61
|
+
return settle(
|
|
62
|
+
exit_code=exit_code,
|
|
63
|
+
text="" if failed else answer,
|
|
64
|
+
service=service,
|
|
65
|
+
stderr=stderr,
|
|
66
|
+
harness_error=harness_error,
|
|
67
|
+
tokens_in=as_int(usage.get("input_tokens")) if "input_tokens" in usage else None,
|
|
68
|
+
tokens_out=as_int(usage.get("output_tokens")) if "output_tokens" in usage else None,
|
|
69
|
+
cost_usd=float(cost)
|
|
70
|
+
if isinstance(cost, (int, float)) and not isinstance(cost, bool)
|
|
71
|
+
else None,
|
|
72
|
+
session_id=session if isinstance(session, str) else None,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def is_final_line(self, line: str) -> bool:
|
|
76
|
+
return False
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
HARNESS = HarnessSpec("claude", ClaudeAdapter(), ("claude",), spend="journal")
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Cline CLI adapter: JSONL output, provider/model split, and prompt after `--`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_router.adapters.base import (
|
|
9
|
+
EMPTY_OUTPUT,
|
|
10
|
+
MAX_ARG_CHARS,
|
|
11
|
+
RunOutcome,
|
|
12
|
+
as_int,
|
|
13
|
+
executable,
|
|
14
|
+
json_lines,
|
|
15
|
+
looks_like_limit,
|
|
16
|
+
settle,
|
|
17
|
+
)
|
|
18
|
+
from agent_router.config import Mode
|
|
19
|
+
from agent_router.registry import HarnessSpec
|
|
20
|
+
from agent_router.runner import Invocation, ResolvedExecutable
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def file_phrase(prompt_file: Path) -> str:
|
|
24
|
+
return f"Read the task from the file {prompt_file.as_posix()} and execute it exactly."
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _error_details(event: dict[str, Any]) -> tuple[str, bool]:
|
|
28
|
+
kind = event.get("type")
|
|
29
|
+
if kind == "error":
|
|
30
|
+
message = event.get("message")
|
|
31
|
+
return (message if isinstance(message, str) else ""), event.get(
|
|
32
|
+
"errorClass"
|
|
33
|
+
) == "rate_limit"
|
|
34
|
+
if kind != "agent_event":
|
|
35
|
+
return "", False
|
|
36
|
+
nested = event.get("event")
|
|
37
|
+
if not isinstance(nested, dict) or nested.get("type") != "error":
|
|
38
|
+
return "", False
|
|
39
|
+
error = nested.get("error")
|
|
40
|
+
error = error if isinstance(error, dict) else {}
|
|
41
|
+
message = error.get("message")
|
|
42
|
+
rate_limit = event.get("errorClass") == "rate_limit" or nested.get("errorClass") == "rate_limit"
|
|
43
|
+
return (message if isinstance(message, str) else ""), rate_limit
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ClineAdapter:
|
|
47
|
+
name = "cline"
|
|
48
|
+
|
|
49
|
+
def build(
|
|
50
|
+
self, text: str, mode: Mode, model: str, exe: ResolvedExecutable, prompt_file: Path
|
|
51
|
+
) -> Invocation:
|
|
52
|
+
provider, separator, name = model.partition("/")
|
|
53
|
+
if not separator or not provider or not name:
|
|
54
|
+
raise ValueError("cline model must be <provider>/<model>")
|
|
55
|
+
argv = [executable(exe), "--json", "-P", provider, "-m", name]
|
|
56
|
+
argv += ["--plan"] if mode == "read" else ["--auto-approve", "true"]
|
|
57
|
+
by_file = exe.is_shim or len(text) > MAX_ARG_CHARS
|
|
58
|
+
argv += ["--", file_phrase(prompt_file) if by_file else text]
|
|
59
|
+
return Invocation(tuple(argv))
|
|
60
|
+
|
|
61
|
+
def parse(self, stdout: str, stderr: str, exit_code: int | None) -> RunOutcome:
|
|
62
|
+
events, other = json_lines(stdout)
|
|
63
|
+
result: dict[str, Any] | None = None
|
|
64
|
+
session_id: str | None = None
|
|
65
|
+
top_level_error = ""
|
|
66
|
+
nested_error = ""
|
|
67
|
+
limit_hint = False
|
|
68
|
+
for event in events:
|
|
69
|
+
kind = event.get("type")
|
|
70
|
+
if kind is None:
|
|
71
|
+
continue
|
|
72
|
+
if kind == "run_result":
|
|
73
|
+
result = event
|
|
74
|
+
elif kind == "hook_event" and session_id is None:
|
|
75
|
+
task_id = event.get("taskId")
|
|
76
|
+
if isinstance(task_id, str):
|
|
77
|
+
session_id = task_id
|
|
78
|
+
message, rate_limit = _error_details(event)
|
|
79
|
+
limit_hint = limit_hint or rate_limit
|
|
80
|
+
if kind == "error" and not top_level_error:
|
|
81
|
+
top_level_error = message
|
|
82
|
+
elif kind == "agent_event" and not nested_error:
|
|
83
|
+
nested_error = message
|
|
84
|
+
|
|
85
|
+
usage = result.get("usage") if result is not None else None
|
|
86
|
+
usage = usage if isinstance(usage, dict) else {}
|
|
87
|
+
raw_text = result.get("text") if result is not None else None
|
|
88
|
+
text = raw_text if isinstance(raw_text, str) else ""
|
|
89
|
+
failed = exit_code != 0 or (result is not None and result.get("finishReason") == "error")
|
|
90
|
+
harness_error = (text or top_level_error or nested_error) if failed else None
|
|
91
|
+
if result is None and harness_error is None:
|
|
92
|
+
return RunOutcome("error", error=EMPTY_OUTPUT, session_id=session_id)
|
|
93
|
+
cost = usage.get("totalCost")
|
|
94
|
+
service = list(other)
|
|
95
|
+
if harness_error:
|
|
96
|
+
service.append(harness_error)
|
|
97
|
+
limit_hint = limit_hint or looks_like_limit(harness_error)
|
|
98
|
+
return settle(
|
|
99
|
+
exit_code=1 if failed and exit_code == 0 else exit_code,
|
|
100
|
+
text=text,
|
|
101
|
+
service=service,
|
|
102
|
+
stderr=stderr,
|
|
103
|
+
limit_hint=limit_hint,
|
|
104
|
+
harness_error=harness_error,
|
|
105
|
+
tokens_in=as_int(usage.get("inputTokens")) if "inputTokens" in usage else None,
|
|
106
|
+
tokens_out=as_int(usage.get("outputTokens")) if "outputTokens" in usage else None,
|
|
107
|
+
cost_usd=float(cost)
|
|
108
|
+
if isinstance(cost, (int, float)) and not isinstance(cost, bool) and cost > 0
|
|
109
|
+
else None,
|
|
110
|
+
session_id=session_id,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
def is_final_line(self, line: str) -> bool:
|
|
114
|
+
events, _ = json_lines(line)
|
|
115
|
+
return bool(events) and events[0].get("type") == "run_result"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
HARNESS = HarnessSpec(
|
|
119
|
+
"cline", ClineAdapter(), ("cline", "cline-cli"), spend="journal", proxy_capable=False
|
|
120
|
+
)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Kimi Code CLI adapter: `kimi -p <text> -m <model> --output-format stream-json`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from agent_router.adapters.base import (
|
|
8
|
+
MAX_ARG_CHARS,
|
|
9
|
+
RunOutcome,
|
|
10
|
+
executable,
|
|
11
|
+
json_lines,
|
|
12
|
+
settle,
|
|
13
|
+
)
|
|
14
|
+
from agent_router.config import Mode
|
|
15
|
+
from agent_router.registry import HarnessSpec
|
|
16
|
+
from agent_router.runner import Invocation, ResolvedExecutable
|
|
17
|
+
|
|
18
|
+
_RESUME_HINT = "session.resume_hint"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def file_phrase(prompt_file: Path) -> str:
|
|
22
|
+
"""Short prompt reference: the job itself lives in a file inside the job directory."""
|
|
23
|
+
return f"Read the task from the file {prompt_file.as_posix()} and execute it exactly."
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class KimiAdapter:
|
|
27
|
+
"""Read mode is enforced by the prompt preamble: `--plan` is incompatible with `-p`."""
|
|
28
|
+
|
|
29
|
+
name = "kimi"
|
|
30
|
+
|
|
31
|
+
def build(
|
|
32
|
+
self, text: str, mode: Mode, model: str, exe: ResolvedExecutable, prompt_file: Path
|
|
33
|
+
) -> Invocation:
|
|
34
|
+
argv = [executable(exe), "-p"]
|
|
35
|
+
by_file = exe.is_shim or len(text) > MAX_ARG_CHARS
|
|
36
|
+
argv.append(file_phrase(prompt_file) if by_file else text)
|
|
37
|
+
argv += ["-m", model, "--output-format", "stream-json"]
|
|
38
|
+
if by_file:
|
|
39
|
+
argv += ["--add-dir", prompt_file.parent.as_posix()]
|
|
40
|
+
return Invocation(tuple(argv))
|
|
41
|
+
|
|
42
|
+
def parse(self, stdout: str, stderr: str, exit_code: int | None) -> RunOutcome:
|
|
43
|
+
events, other = json_lines(stdout)
|
|
44
|
+
text = ""
|
|
45
|
+
session_id: str | None = None
|
|
46
|
+
service = list(other)
|
|
47
|
+
for event in events:
|
|
48
|
+
role = event.get("role")
|
|
49
|
+
if role == "assistant":
|
|
50
|
+
content = event.get("content")
|
|
51
|
+
if isinstance(content, str) and content.strip():
|
|
52
|
+
text = content
|
|
53
|
+
elif role == "meta":
|
|
54
|
+
kind = str(event.get("type", ""))
|
|
55
|
+
if kind == _RESUME_HINT and isinstance(event.get("session_id"), str):
|
|
56
|
+
session_id = event["session_id"]
|
|
57
|
+
elif "error" in kind.lower():
|
|
58
|
+
service.append(str(event.get("content") or event.get("message") or kind))
|
|
59
|
+
return settle(
|
|
60
|
+
exit_code=exit_code, text=text, service=service, stderr=stderr, session_id=session_id
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def is_final_line(self, line: str) -> bool:
|
|
64
|
+
if _RESUME_HINT not in line:
|
|
65
|
+
return False
|
|
66
|
+
events, _ = json_lines(line)
|
|
67
|
+
return bool(events) and events[0].get("type") == _RESUME_HINT
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
HARNESS = HarnessSpec("kimi", KimiAdapter(), ("kimi",), spend="journal")
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""OpenCode adapter: `opencode run --format json --archived --model <model>`, prompt via stdin."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from agent_router.adapters.base import RunOutcome, as_int, executable, json_lines, settle
|
|
9
|
+
from agent_router.config import Mode
|
|
10
|
+
from agent_router.registry import HarnessSpec
|
|
11
|
+
from agent_router.runner import Invocation, ResolvedExecutable
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _part(event: dict[str, Any]) -> dict[str, Any]:
|
|
15
|
+
part = event.get("part")
|
|
16
|
+
return part if isinstance(part, dict) else {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class OpenCodeAdapter:
|
|
20
|
+
"""Read mode uses the plan agent (creates no files), write mode passes `--auto`."""
|
|
21
|
+
|
|
22
|
+
name = "opencode"
|
|
23
|
+
|
|
24
|
+
def build(
|
|
25
|
+
self, text: str, mode: Mode, model: str, exe: ResolvedExecutable, prompt_file: Path
|
|
26
|
+
) -> Invocation:
|
|
27
|
+
argv = [executable(exe), "run", "--format", "json", "--archived", "--model", model]
|
|
28
|
+
argv += ["--agent", "plan"] if mode == "read" else ["--auto"]
|
|
29
|
+
return Invocation(tuple(argv), stdin_text=text)
|
|
30
|
+
|
|
31
|
+
def parse(self, stdout: str, stderr: str, exit_code: int | None) -> RunOutcome:
|
|
32
|
+
events, other = json_lines(stdout)
|
|
33
|
+
texts: list[tuple[object, str]] = []
|
|
34
|
+
tokens_in = tokens_out = 0
|
|
35
|
+
cost = 0.0
|
|
36
|
+
steps = 0
|
|
37
|
+
session_id: str | None = None
|
|
38
|
+
harness_error: str | None = None
|
|
39
|
+
limit_hint = False
|
|
40
|
+
service = list(other)
|
|
41
|
+
for event in events:
|
|
42
|
+
kind = event.get("type")
|
|
43
|
+
if session_id is None and isinstance(event.get("sessionID"), str):
|
|
44
|
+
session_id = event["sessionID"]
|
|
45
|
+
part = _part(event)
|
|
46
|
+
if kind == "text":
|
|
47
|
+
if isinstance(part.get("text"), str):
|
|
48
|
+
texts.append((part.get("messageID"), part["text"]))
|
|
49
|
+
elif kind == "step_finish":
|
|
50
|
+
tokens = part.get("tokens")
|
|
51
|
+
if isinstance(tokens, dict):
|
|
52
|
+
steps += 1
|
|
53
|
+
tokens_in += as_int(tokens.get("input"))
|
|
54
|
+
tokens_out += as_int(tokens.get("output")) + as_int(tokens.get("reasoning"))
|
|
55
|
+
value = part.get("cost")
|
|
56
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
57
|
+
cost += float(value)
|
|
58
|
+
elif kind == "error":
|
|
59
|
+
error = event.get("error")
|
|
60
|
+
error = error if isinstance(error, dict) else {}
|
|
61
|
+
error_type = str(error.get("type", ""))
|
|
62
|
+
message = str(error.get("message", "")) or error_type or "harness error"
|
|
63
|
+
harness_error = f"{error_type}: {message}" if error_type else message
|
|
64
|
+
service.append(harness_error)
|
|
65
|
+
lowered = error_type.lower()
|
|
66
|
+
limit_hint = limit_hint or "limit" in lowered or "quota" in lowered
|
|
67
|
+
text = ""
|
|
68
|
+
if texts:
|
|
69
|
+
last_message = texts[-1][0]
|
|
70
|
+
text = "\n".join(chunk for message, chunk in texts if message == last_message)
|
|
71
|
+
return settle(
|
|
72
|
+
exit_code=exit_code,
|
|
73
|
+
text=text,
|
|
74
|
+
service=service,
|
|
75
|
+
stderr=stderr,
|
|
76
|
+
limit_hint=limit_hint,
|
|
77
|
+
harness_error=harness_error,
|
|
78
|
+
tokens_in=tokens_in if steps else None,
|
|
79
|
+
tokens_out=tokens_out if steps else None,
|
|
80
|
+
cost_usd=cost if cost > 0 else None,
|
|
81
|
+
session_id=session_id,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def is_final_line(self, line: str) -> bool:
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
HARNESS = HarnessSpec("opencode", OpenCodeAdapter(), ("opencode",), spend="counter")
|