arga-clone 0.2.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.
- arga_clone-0.2.0.dist-info/METADATA +2570 -0
- arga_clone-0.2.0.dist-info/RECORD +32 -0
- arga_clone-0.2.0.dist-info/WHEEL +5 -0
- arga_clone-0.2.0.dist-info/entry_points.txt +2 -0
- arga_clone-0.2.0.dist-info/licenses/LICENSE +21 -0
- arga_clone-0.2.0.dist-info/top_level.txt +1 -0
- argaclone/__init__.py +13 -0
- argaclone/chaos.py +280 -0
- argaclone/cli.py +229 -0
- argaclone/client.py +227 -0
- argaclone/gateway.py +323 -0
- argaclone/graders.py +244 -0
- argaclone/mcp_server.py +237 -0
- argaclone/runner.py +383 -0
- argaclone/scenarios.py +443 -0
- argaclone/server.py +557 -0
- argaclone/store.py +461 -0
- argaclone/twin_spec.py +384 -0
- argaclone/twins/__init__.py +15 -0
- argaclone/twins/base.py +436 -0
- argaclone/twins/calendar_twin.py +331 -0
- argaclone/twins/drive_twin.py +334 -0
- argaclone/twins/github_twin.py +2086 -0
- argaclone/twins/gmail_twin.py +413 -0
- argaclone/twins/hubspot_twin.py +212 -0
- argaclone/twins/jira_twin.py +265 -0
- argaclone/twins/linear_twin.py +480 -0
- argaclone/twins/notion_twin.py +415 -0
- argaclone/twins/salesforce_twin.py +456 -0
- argaclone/twins/slack_twin.py +573 -0
- argaclone/twins/stripe_twin.py +1013 -0
- argaclone/webhooks.py +209 -0
argaclone/server.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
"""HTTP 服务:一个进程同时充当 admin API 与全部 twin。
|
|
2
|
+
|
|
3
|
+
一个进程、一个端口、按 Host 分流,是这个复刻品能跑起来的关键:
|
|
4
|
+
- 本地 `curl -H "Host: stripe.<run>.twins.local"` 就能当 Stripe 用;
|
|
5
|
+
- 生产里换成 `*.twins.example.com` 通配解析即可,代码不用改。
|
|
6
|
+
|
|
7
|
+
admin 面故意不鉴权:它只在 127.0.0.1 上监听,且内容本身就是仿真世界的东西。
|
|
8
|
+
真要做多租户,第一件事是把 admin 加 token——但那是另一件事,别在这里假装做完了。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
import re
|
|
16
|
+
import threading
|
|
17
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
from urllib.parse import urlparse
|
|
21
|
+
|
|
22
|
+
from . import chaos, webhooks
|
|
23
|
+
from .gateway import Gateway
|
|
24
|
+
from .graders import grade
|
|
25
|
+
from .runner import Runner, empty_trace
|
|
26
|
+
from .scenarios import Scenario, ScenarioStore, apply_scenario, generate_from_prompt
|
|
27
|
+
from .store import RunExpired, RunNotFound, StaleRunVersion, Store
|
|
28
|
+
from .twins.base import TwinRegistry
|
|
29
|
+
from .twins.github_twin import GitHubTwin
|
|
30
|
+
from .twins.hubspot_twin import HubSpotTwin
|
|
31
|
+
from .twins.calendar_twin import CalendarTwin
|
|
32
|
+
from .twins.drive_twin import DriveTwin
|
|
33
|
+
from .twins.gmail_twin import GmailTwin
|
|
34
|
+
from .twins.jira_twin import JiraTwin
|
|
35
|
+
from .twins.linear_twin import LinearTwin
|
|
36
|
+
from .twins.notion_twin import NotionTwin
|
|
37
|
+
from .twins.slack_twin import SlackTwin
|
|
38
|
+
from .twins.salesforce_twin import SalesforceTwin
|
|
39
|
+
from .twins.stripe_twin import StripeTwin
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def build_registry() -> TwinRegistry:
|
|
43
|
+
reg = TwinRegistry()
|
|
44
|
+
reg.register(StripeTwin())
|
|
45
|
+
reg.register(SlackTwin())
|
|
46
|
+
reg.register(GitHubTwin())
|
|
47
|
+
reg.register(HubSpotTwin())
|
|
48
|
+
reg.register(SalesforceTwin())
|
|
49
|
+
# 这三个是用 twin_spec 工厂建的(声明式资源 + scope 家族 + 分页 + 错误形状),
|
|
50
|
+
# 不是手写 CRUD —— 见 README「工厂」一节
|
|
51
|
+
reg.register(JiraTwin())
|
|
52
|
+
reg.register(LinearTwin())
|
|
53
|
+
reg.register(NotionTwin())
|
|
54
|
+
# Google Workspace 三件套:共享 run-scoped 文件状态与 people 身份
|
|
55
|
+
reg.register(GmailTwin())
|
|
56
|
+
reg.register(DriveTwin())
|
|
57
|
+
reg.register(CalendarTwin())
|
|
58
|
+
return reg
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def run_public_view(run) -> dict[str, Any]:
|
|
62
|
+
return {
|
|
63
|
+
"run_id": run.run_id,
|
|
64
|
+
"twins": run.twins,
|
|
65
|
+
"ttl_seconds": run.ttl_seconds,
|
|
66
|
+
"remaining_seconds": run.remaining(),
|
|
67
|
+
"created_at": run.created_at,
|
|
68
|
+
"locked": run.locked,
|
|
69
|
+
"expired": run.expired(),
|
|
70
|
+
"endpoints": {
|
|
71
|
+
t: f"http://{t}.{run.run_id}.twins.local" for t in run.twins
|
|
72
|
+
},
|
|
73
|
+
"scenario_id": run.extras.get("scenario_id"),
|
|
74
|
+
"credentials": run.extras.get("credentials", {}),
|
|
75
|
+
# 严格凭据模式要能从 run 视图里看到:客户端靠它判断"该不该用 provision
|
|
76
|
+
# 下发的那个 token",否则它只能靠试错发现。
|
|
77
|
+
"strict_tokens": bool(run.extras.get("strict_tokens")),
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class App:
|
|
82
|
+
def __init__(self, scenario_dir: Path, admin_token: str | None = None,
|
|
83
|
+
data_dir: Path | str | None = None) -> None:
|
|
84
|
+
# admin_token=None 是刻意的默认:本机单人调试时不该为了看一眼 run 列表去配令牌。
|
|
85
|
+
# 一旦要给别人连(或多租户),这就是必须拧的那颗螺丝 —— serve --admin-token。
|
|
86
|
+
self.admin_token = admin_token
|
|
87
|
+
self.store = Store(data_dir)
|
|
88
|
+
self.registry = build_registry()
|
|
89
|
+
self.gateway = Gateway(self.store, self.registry)
|
|
90
|
+
self.scenarios = ScenarioStore(scenario_dir)
|
|
91
|
+
self.runners: dict[str, Runner] = {}
|
|
92
|
+
self._runners_lock = threading.Lock()
|
|
93
|
+
|
|
94
|
+
# ---------- run 操作 ----------
|
|
95
|
+
|
|
96
|
+
def provision(self, body: dict[str, Any]) -> dict[str, Any]:
|
|
97
|
+
twins = body.get("twins") or ["stripe"]
|
|
98
|
+
if isinstance(twins, str):
|
|
99
|
+
twins = [t.strip() for t in twins.split(",") if t.strip()]
|
|
100
|
+
unknown = [t for t in twins if not self.registry.has(t)]
|
|
101
|
+
if unknown:
|
|
102
|
+
raise ValueError(f"unknown twins: {unknown}; available: {self.registry.names()}")
|
|
103
|
+
|
|
104
|
+
ttl = int(body.get("ttl") or body.get("ttl_seconds") or 600)
|
|
105
|
+
if ttl < 1:
|
|
106
|
+
raise ValueError("ttl must be >= 1")
|
|
107
|
+
run = self.store.create(twins, ttl, strict_tokens=bool(body.get("strict_tokens")))
|
|
108
|
+
# 没有 scenario 的 run 也必须有可用的世界:twin 的初始状态在创建时就落地,
|
|
109
|
+
# 否则任何一次请求都会在 state[provider] 上 KeyError。
|
|
110
|
+
for t in twins:
|
|
111
|
+
run.state[t] = self.registry.get(t).initial_state()
|
|
112
|
+
|
|
113
|
+
scenario: Scenario | None = None
|
|
114
|
+
sid = body.get("scenario_id")
|
|
115
|
+
if sid:
|
|
116
|
+
scenario = self.scenarios.get(sid)
|
|
117
|
+
if scenario is None:
|
|
118
|
+
raise ValueError(f"scenario not found: {sid}")
|
|
119
|
+
elif body.get("prompt"):
|
|
120
|
+
scenario = Scenario(
|
|
121
|
+
id="",
|
|
122
|
+
name=body.get("name") or "inline",
|
|
123
|
+
seed=generate_from_prompt(body["prompt"], twins),
|
|
124
|
+
prompt=body["prompt"],
|
|
125
|
+
generation_mode=body.get("generation_mode") or "fast",
|
|
126
|
+
)
|
|
127
|
+
self.scenarios.save(scenario)
|
|
128
|
+
|
|
129
|
+
if scenario is not None:
|
|
130
|
+
apply_scenario(scenario, run, self.store, self.registry)
|
|
131
|
+
run.extras["scenario_id"] = scenario.id
|
|
132
|
+
|
|
133
|
+
# 关键时序:所有 seed 落完之后才打基线。早一步打,reset 就会把 seed 弄丢。
|
|
134
|
+
self.store.snapshot(run.run_id)
|
|
135
|
+
return run_public_view(self.store.get(run.run_id))
|
|
136
|
+
|
|
137
|
+
def get_run(self, run_id: str) -> dict[str, Any]:
|
|
138
|
+
return run_public_view(self.store.get(run_id))
|
|
139
|
+
|
|
140
|
+
def list_runs(self) -> dict[str, Any]:
|
|
141
|
+
return {"runs": [run_public_view(r) for r in self.store.all_runs()], "stub_reports": {}}
|
|
142
|
+
|
|
143
|
+
def reset(self, run_id: str) -> dict[str, Any]:
|
|
144
|
+
self.store.reset(run_id)
|
|
145
|
+
# 重置是一次新尝试:动作历史必须清空,否则上一次的写请求会跟着这次判分走,
|
|
146
|
+
# "重放同一 agent 得到同一结论"就变成了"上一次的痕迹让这次判过"。
|
|
147
|
+
self.runners.pop(run_id, None)
|
|
148
|
+
return run_public_view(self.store.get(run_id))
|
|
149
|
+
|
|
150
|
+
def extend(self, run_id: str, ttl: int) -> dict[str, Any]:
|
|
151
|
+
self.store.extend(run_id, ttl)
|
|
152
|
+
return run_public_view(self.store.get(run_id))
|
|
153
|
+
|
|
154
|
+
def lock(self, run_id: str) -> dict[str, Any]:
|
|
155
|
+
self.store.lock(run_id)
|
|
156
|
+
return run_public_view(self.store.get(run_id))
|
|
157
|
+
|
|
158
|
+
def teardown(self, run_id: str) -> dict[str, Any]:
|
|
159
|
+
self.store.drop(run_id)
|
|
160
|
+
self.runners.pop(run_id, None)
|
|
161
|
+
return {"deleted": True, "run_id": run_id}
|
|
162
|
+
|
|
163
|
+
def state(self, run_id: str) -> dict[str, Any]:
|
|
164
|
+
run = self.store.get(run_id, allow_expired=True)
|
|
165
|
+
return {
|
|
166
|
+
"run_id": run.run_id,
|
|
167
|
+
"state": run.state,
|
|
168
|
+
"shared_people": run.state.get("shared", {}).get("people", {}),
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
def stub_hits(self, run_id: str, provider: str | None = None) -> dict[str, Any]:
|
|
172
|
+
return self.store.stub_report(run_id, provider)
|
|
173
|
+
|
|
174
|
+
# ---------- 动作执行与判分 ----------
|
|
175
|
+
|
|
176
|
+
def runner_for(self, run_id: str) -> Runner:
|
|
177
|
+
"""拿这个 run 的 runner,必要时创建。
|
|
178
|
+
|
|
179
|
+
为什么必须按 run 复用一个 runner 而不是每次新建:runner 持有全部
|
|
180
|
+
calls,而判据里的 `trace.writes.count`、`trace.path_sequence` 判的是
|
|
181
|
+
"这一整轮做过什么"。每次 act 都新建 runner 会让 trace 只剩最后一批
|
|
182
|
+
动作 —— 一个分三步干活的 agent 会被判成"只发了最后一条消息",
|
|
183
|
+
而它前面发的那两条(包括发错频道的)全部消失。这是最隐蔽的假绿。
|
|
184
|
+
"""
|
|
185
|
+
runner = self.runners.get(run_id)
|
|
186
|
+
if runner is None:
|
|
187
|
+
# ThreadingHTTPServer:同一个 run 的两个并发请求会同时走到这里。
|
|
188
|
+
# 没有锁的话两次都可能看到 None 并各自建一个 runner,于是 trace 被劈成
|
|
189
|
+
# 两半 —— 每个都"看着完整",判据只看得到最后被写回的那个。这跟"每次
|
|
190
|
+
# act 新建 runner"是同一个 bug 的并发版本,且更难复现。
|
|
191
|
+
with self._runners_lock:
|
|
192
|
+
runner = self.runners.get(run_id)
|
|
193
|
+
if runner is None:
|
|
194
|
+
runner = Runner(self.gateway, run_id)
|
|
195
|
+
self.runners[run_id] = runner
|
|
196
|
+
return runner
|
|
197
|
+
|
|
198
|
+
def commit_trace(self, run_id: str) -> dict[str, Any]:
|
|
199
|
+
"""把 runner 累积的 trace 落到 run 上,供 grade 使用。
|
|
200
|
+
|
|
201
|
+
逐步驱动的 agent(真模型 tool-call 循环)不能走 act —— 它每步都要
|
|
202
|
+
看返回再决定。所以那条路径需要显式提交一次 trace,否则 grade 看到的是
|
|
203
|
+
空 trace,判据里所有 trace.* 都会读成 None。
|
|
204
|
+
"""
|
|
205
|
+
trace = self.runner_for(run_id).trace()
|
|
206
|
+
self.store.get(run_id, allow_expired=True).extras["last_trace"] = trace
|
|
207
|
+
return trace
|
|
208
|
+
|
|
209
|
+
def act(self, run_id: str, actions: list[dict[str, Any]]) -> dict[str, Any]:
|
|
210
|
+
self.store.get(run_id) # 过期就抛
|
|
211
|
+
trace = self.runner_for(run_id).run(actions)
|
|
212
|
+
run = self.store.get(run_id, allow_expired=True)
|
|
213
|
+
run.extras["last_trace"] = trace
|
|
214
|
+
return trace
|
|
215
|
+
|
|
216
|
+
def grade(self, run_id: str, spec: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
217
|
+
run = self.store.get(run_id, allow_expired=True)
|
|
218
|
+
the_spec = spec
|
|
219
|
+
if the_spec is None:
|
|
220
|
+
sid = run.extras.get("scenario_id")
|
|
221
|
+
scenario = self.scenarios.get(sid) if sid else None
|
|
222
|
+
if scenario is not None:
|
|
223
|
+
the_spec = (scenario.capabilities or {}).get("grade")
|
|
224
|
+
if not the_spec:
|
|
225
|
+
return {"verdict": "ERROR", "error": "no grade spec provided and none in scenario"}
|
|
226
|
+
trace = run.extras.get("last_trace") or empty_trace()
|
|
227
|
+
report = grade(the_spec, run.state, trace)
|
|
228
|
+
out = report.to_dict()
|
|
229
|
+
out["trace"] = trace
|
|
230
|
+
return out
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class Handler(BaseHTTPRequestHandler):
|
|
234
|
+
protocol_version = "HTTP/1.1"
|
|
235
|
+
app: App # 由 serve() 注入
|
|
236
|
+
|
|
237
|
+
def log_message(self, fmt: str, *args: Any) -> None: # noqa: D401
|
|
238
|
+
# 静音:测试里几百个请求刷屏没价值
|
|
239
|
+
return
|
|
240
|
+
|
|
241
|
+
# ---- 工具 ----
|
|
242
|
+
|
|
243
|
+
def _read_body(self) -> bytes:
|
|
244
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
245
|
+
return self.rfile.read(length) if length else b""
|
|
246
|
+
|
|
247
|
+
def _send(self, status: int, payload: Any, extra_headers: dict[str, str] | None = None) -> None:
|
|
248
|
+
if isinstance(payload, (bytes, bytearray)):
|
|
249
|
+
raw = bytes(payload)
|
|
250
|
+
elif payload is None:
|
|
251
|
+
raw = b""
|
|
252
|
+
else:
|
|
253
|
+
raw = json.dumps(payload).encode()
|
|
254
|
+
self.send_response(status)
|
|
255
|
+
self.send_header("Content-Type", "application/json")
|
|
256
|
+
self.send_header("Content-Length", str(len(raw)))
|
|
257
|
+
for k, v in (extra_headers or {}).items():
|
|
258
|
+
self.send_header(k, v)
|
|
259
|
+
self.end_headers()
|
|
260
|
+
if raw:
|
|
261
|
+
self.wfile.write(raw)
|
|
262
|
+
|
|
263
|
+
def _headers_lower(self) -> dict[str, str]:
|
|
264
|
+
return {k.lower(): v for k, v in self.headers.items()}
|
|
265
|
+
|
|
266
|
+
# ---- 方法 ----
|
|
267
|
+
|
|
268
|
+
def do_GET(self) -> None:
|
|
269
|
+
self._dispatch("GET")
|
|
270
|
+
|
|
271
|
+
def do_POST(self) -> None:
|
|
272
|
+
self._dispatch("POST")
|
|
273
|
+
|
|
274
|
+
def do_DELETE(self) -> None:
|
|
275
|
+
self._dispatch("DELETE")
|
|
276
|
+
|
|
277
|
+
def do_PATCH(self) -> None:
|
|
278
|
+
self._dispatch("PATCH")
|
|
279
|
+
|
|
280
|
+
# ---- admin 鉴权 ----
|
|
281
|
+
|
|
282
|
+
def _admin_scoped(self, path: str, headers: dict[str, str]) -> bool:
|
|
283
|
+
"""这个请求是否属于"管理面"(需要 admin 令牌)。
|
|
284
|
+
|
|
285
|
+
三类都算:服务级 /admin/*、twin 级 /admin/*(三种寻址都算)、以及 /mcp
|
|
286
|
+
—— MCP 的 provision/act/grade 与被保护的 admin 路由是同一份权力,
|
|
287
|
+
只挡 HTTP 那一半等于没挡。
|
|
288
|
+
数据面(/v1/...、/api/...)不在此列,它有自己的凭据体系。
|
|
289
|
+
"""
|
|
290
|
+
if path == "/mcp":
|
|
291
|
+
return True
|
|
292
|
+
if path.startswith("/__twin/"):
|
|
293
|
+
m = re.match(r"^/__twin/[^/]+/[^/]+(/.*)?$", path)
|
|
294
|
+
return bool(m and (m.group(1) or "").startswith("/admin"))
|
|
295
|
+
return path.startswith("/admin")
|
|
296
|
+
|
|
297
|
+
def _admin_token_ok(self, headers: dict[str, str]) -> bool:
|
|
298
|
+
token = self.app.admin_token
|
|
299
|
+
if not token:
|
|
300
|
+
return True
|
|
301
|
+
given = (headers.get("x-admin-token") or "").strip()
|
|
302
|
+
if not given:
|
|
303
|
+
auth = headers.get("authorization") or ""
|
|
304
|
+
scheme, _, value = auth.partition(" ")
|
|
305
|
+
if scheme.lower() == "bearer":
|
|
306
|
+
given = value.strip()
|
|
307
|
+
# 定长比较:令牌比较不该泄露前缀匹配长度
|
|
308
|
+
return bool(given) and hmac.compare_digest(given, token)
|
|
309
|
+
|
|
310
|
+
def _dispatch(self, method: str) -> None:
|
|
311
|
+
body = self._read_body()
|
|
312
|
+
path = urlparse(self.path).path
|
|
313
|
+
|
|
314
|
+
headers = self._headers_lower()
|
|
315
|
+
if self.app.admin_token and self._admin_scoped(path, headers) and not self._admin_token_ok(headers):
|
|
316
|
+
self._send(
|
|
317
|
+
401,
|
|
318
|
+
{
|
|
319
|
+
"error": "admin_auth_required",
|
|
320
|
+
"detail": "send Authorization: Bearer <admin token> or X-Admin-Token",
|
|
321
|
+
},
|
|
322
|
+
{"WWW-Authenticate": 'Bearer realm="argaclone-admin"'},
|
|
323
|
+
)
|
|
324
|
+
return
|
|
325
|
+
|
|
326
|
+
try:
|
|
327
|
+
if path == "/healthz":
|
|
328
|
+
self._send(200, {"ok": True})
|
|
329
|
+
return
|
|
330
|
+
if path == "/mcp":
|
|
331
|
+
self._mcp(method, body)
|
|
332
|
+
return
|
|
333
|
+
if path.startswith("/admin") and not self.app.gateway.is_twin_target(
|
|
334
|
+
self.headers.get("Host", ""), self._headers_lower()
|
|
335
|
+
):
|
|
336
|
+
self._admin(method, path, body)
|
|
337
|
+
return
|
|
338
|
+
|
|
339
|
+
resp = self.app.gateway.handle(
|
|
340
|
+
method, self.headers.get("Host", ""), self.path, self._headers_lower(), body
|
|
341
|
+
)
|
|
342
|
+
self._send(resp.status, resp.body, resp.headers)
|
|
343
|
+
except RunNotFound as exc:
|
|
344
|
+
self._send(404, {"error": "run_not_found", "detail": str(exc)})
|
|
345
|
+
except RunExpired as exc:
|
|
346
|
+
self._send(410, {"error": "run_expired", "detail": str(exc)})
|
|
347
|
+
except StaleRunVersion as exc:
|
|
348
|
+
# 409 而不是 500:这是"你的改动基于旧世界",调用方重读一次就能继续。
|
|
349
|
+
# 报 500 会让调用方以为服务坏了,然后重试同一份旧世界 —— 无限循环。
|
|
350
|
+
self._send(409, {"error": "stale_run_version", "detail": str(exc),
|
|
351
|
+
"_twin_hint": "重新 GET /admin/runs/<id>/state 再改"})
|
|
352
|
+
except Exception as exc: # noqa: BLE001 - 服务端不该因为一个坏请求整个炸掉
|
|
353
|
+
self._send(500, {"error": "internal", "detail": f"{type(exc).__name__}: {exc}"})
|
|
354
|
+
|
|
355
|
+
# ---- MCP ----
|
|
356
|
+
|
|
357
|
+
def _mcp(self, method: str, body: bytes) -> None:
|
|
358
|
+
"""MCP 走 POST /mcp,JSON-RPC 2.0。
|
|
359
|
+
|
|
360
|
+
延迟 import:mcp_server 需要 App 的类型,server 需要 McpEndpoint,
|
|
361
|
+
顶部 import 会成环。这里放在方法里避免。
|
|
362
|
+
"""
|
|
363
|
+
from .mcp_server import McpEndpoint
|
|
364
|
+
|
|
365
|
+
if method != "POST":
|
|
366
|
+
self._send(405, {"error": "method_not_allowed", "detail": "use POST /mcp"})
|
|
367
|
+
return
|
|
368
|
+
try:
|
|
369
|
+
payload = json.loads(body or b"{}")
|
|
370
|
+
except json.JSONDecodeError as exc:
|
|
371
|
+
self._send(400, {"jsonrpc": "2.0", "id": None,
|
|
372
|
+
"error": {"code": -32700, "message": f"Parse error: {exc}"}})
|
|
373
|
+
return
|
|
374
|
+
out = McpEndpoint(self.app).handle(payload)
|
|
375
|
+
if out is None:
|
|
376
|
+
# 通知:202 Accepted,无 body(协议要求)
|
|
377
|
+
self.send_response(202)
|
|
378
|
+
self.send_header("Content-Length", "0")
|
|
379
|
+
self.end_headers()
|
|
380
|
+
return
|
|
381
|
+
self._send(200, out)
|
|
382
|
+
|
|
383
|
+
# ---- admin ----
|
|
384
|
+
def _admin(self, method: str, path: str, body: bytes) -> None:
|
|
385
|
+
payload: dict[str, Any] = {}
|
|
386
|
+
if body:
|
|
387
|
+
try:
|
|
388
|
+
payload = json.loads(body)
|
|
389
|
+
except json.JSONDecodeError:
|
|
390
|
+
self._send(400, {"error": "invalid_json"})
|
|
391
|
+
return
|
|
392
|
+
|
|
393
|
+
parts = [p for p in path.strip("/").split("/") if p]
|
|
394
|
+
|
|
395
|
+
# /admin/scenarios[...]
|
|
396
|
+
if parts[:2] == ["admin", "scenarios"]:
|
|
397
|
+
self._admin_scenarios(method, parts[2:], payload)
|
|
398
|
+
return
|
|
399
|
+
|
|
400
|
+
# /admin/runs[...]
|
|
401
|
+
if parts[:2] == ["admin", "runs"]:
|
|
402
|
+
self._admin_runs(method, parts[2:], payload)
|
|
403
|
+
return
|
|
404
|
+
|
|
405
|
+
self._send(404, {"error": "no such admin route", "path": path})
|
|
406
|
+
|
|
407
|
+
def _admin_runs(self, method: str, rest: list[str], payload: dict[str, Any]) -> None:
|
|
408
|
+
app = self.app
|
|
409
|
+
|
|
410
|
+
if not rest:
|
|
411
|
+
if method == "GET":
|
|
412
|
+
self._send(200, app.list_runs())
|
|
413
|
+
return
|
|
414
|
+
if method == "POST":
|
|
415
|
+
try:
|
|
416
|
+
self._send(201, app.provision(payload))
|
|
417
|
+
except ValueError as exc:
|
|
418
|
+
self._send(400, {"error": str(exc)})
|
|
419
|
+
return
|
|
420
|
+
self._send(405, {"error": "method not allowed"})
|
|
421
|
+
return
|
|
422
|
+
|
|
423
|
+
run_id = rest[0]
|
|
424
|
+
action = rest[1] if len(rest) > 1 else ""
|
|
425
|
+
|
|
426
|
+
if len(rest) == 1:
|
|
427
|
+
if method == "GET":
|
|
428
|
+
self._send(200, app.get_run(run_id))
|
|
429
|
+
return
|
|
430
|
+
if method == "DELETE":
|
|
431
|
+
self._send(200, app.teardown(run_id))
|
|
432
|
+
return
|
|
433
|
+
self._send(405, {"error": "method not allowed"})
|
|
434
|
+
return
|
|
435
|
+
|
|
436
|
+
if action == "reset" and method == "POST":
|
|
437
|
+
self._send(200, app.reset(run_id))
|
|
438
|
+
elif action == "extend" and method == "POST":
|
|
439
|
+
self._send(200, app.extend(run_id, int(payload.get("ttl") or 600)))
|
|
440
|
+
elif action == "lock" and method == "POST":
|
|
441
|
+
self._send(200, app.lock(run_id))
|
|
442
|
+
elif action == "state" and method == "GET":
|
|
443
|
+
self._send(200, app.state(run_id))
|
|
444
|
+
elif action == "stub-hits":
|
|
445
|
+
if method == "GET":
|
|
446
|
+
self._send(200, app.stub_hits(run_id, payload.get("provider")))
|
|
447
|
+
elif method == "POST":
|
|
448
|
+
self.app.store.clear_stub_hits(run_id)
|
|
449
|
+
self._send(200, {"cleared": True})
|
|
450
|
+
else:
|
|
451
|
+
self._send(405, {"error": "method not allowed"})
|
|
452
|
+
elif action == "actions" and method == "POST":
|
|
453
|
+
self._send(200, app.act(run_id, payload.get("actions") or []))
|
|
454
|
+
elif action == "grade" and method == "POST":
|
|
455
|
+
self._send(200, app.grade(run_id, payload.get("spec")))
|
|
456
|
+
elif action == "faults":
|
|
457
|
+
# 故障注入:GET 看规则与命中数,POST 加一条,DELETE 清空。
|
|
458
|
+
# 挂在 run 上而不是服务上,因为"这次重试题要坏一次"是 run 的剧本,
|
|
459
|
+
# 服务级的规则会污染同时跑的其它 episode。
|
|
460
|
+
run = app.store.get(run_id)
|
|
461
|
+
if method == "GET":
|
|
462
|
+
self._send(200, chaos.report(run))
|
|
463
|
+
elif method == "POST":
|
|
464
|
+
try:
|
|
465
|
+
fault = chaos.add_fault(run, payload)
|
|
466
|
+
except ValueError as exc:
|
|
467
|
+
self._send(400, {"error": str(exc)})
|
|
468
|
+
return
|
|
469
|
+
app.store.save(run)
|
|
470
|
+
self._send(201, fault)
|
|
471
|
+
elif method == "DELETE":
|
|
472
|
+
chaos.clear(run, "faults")
|
|
473
|
+
app.store.save(run)
|
|
474
|
+
self._send(200, {"cleared": "faults"})
|
|
475
|
+
else:
|
|
476
|
+
self._send(405, {"error": "method not allowed"})
|
|
477
|
+
elif action == "webhooks":
|
|
478
|
+
# 事件订阅:注册 → 世界变了自动 POST → 投递记录可查。
|
|
479
|
+
run = app.store.get(run_id)
|
|
480
|
+
if method == "GET":
|
|
481
|
+
self._send(200, webhooks.report(run))
|
|
482
|
+
elif method == "POST":
|
|
483
|
+
try:
|
|
484
|
+
hook = webhooks.register(run, payload)
|
|
485
|
+
except ValueError as exc:
|
|
486
|
+
self._send(400, {"error": str(exc)})
|
|
487
|
+
return
|
|
488
|
+
app.store.save(run)
|
|
489
|
+
# 密钥**只在注册这一次**明文回:之后报告里只给前 8 位。
|
|
490
|
+
self._send(201, hook)
|
|
491
|
+
elif method == "DELETE":
|
|
492
|
+
hook_id = str(payload.get("id") or (rest[2] if len(rest) > 2 else ""))
|
|
493
|
+
removed = webhooks.remove(run, hook_id)
|
|
494
|
+
app.store.save(run)
|
|
495
|
+
self._send(200 if removed else 404, {"removed": removed})
|
|
496
|
+
else:
|
|
497
|
+
self._send(405, {"error": "method not allowed"})
|
|
498
|
+
elif action == "rate-limit":
|
|
499
|
+
run = app.store.get(run_id)
|
|
500
|
+
if method == "GET":
|
|
501
|
+
self._send(200, chaos.report(run))
|
|
502
|
+
elif method == "POST":
|
|
503
|
+
try:
|
|
504
|
+
rule = chaos.add_rate_limit(run, payload)
|
|
505
|
+
except ValueError as exc:
|
|
506
|
+
self._send(400, {"error": str(exc)})
|
|
507
|
+
return
|
|
508
|
+
app.store.save(run)
|
|
509
|
+
self._send(201, rule)
|
|
510
|
+
elif method == "DELETE":
|
|
511
|
+
chaos.clear(run, "rate_limits")
|
|
512
|
+
app.store.save(run)
|
|
513
|
+
self._send(200, {"cleared": "rate_limits"})
|
|
514
|
+
else:
|
|
515
|
+
self._send(405, {"error": "method not allowed"})
|
|
516
|
+
else:
|
|
517
|
+
self._send(404, {"error": "no such run action", "action": action})
|
|
518
|
+
|
|
519
|
+
def _admin_scenarios(self, method: str, rest: list[str], payload: dict[str, Any]) -> None:
|
|
520
|
+
store = self.app.scenarios
|
|
521
|
+
if not rest:
|
|
522
|
+
if method == "GET":
|
|
523
|
+
self._send(200, {"scenarios": [s.to_dict() for s in store.list()]})
|
|
524
|
+
return
|
|
525
|
+
if method == "POST":
|
|
526
|
+
scenario = Scenario.from_dict(payload)
|
|
527
|
+
store.save(scenario)
|
|
528
|
+
self._send(201, scenario.to_dict())
|
|
529
|
+
return
|
|
530
|
+
self._send(405, {"error": "method not allowed"})
|
|
531
|
+
return
|
|
532
|
+
|
|
533
|
+
sid = rest[0]
|
|
534
|
+
if method == "GET":
|
|
535
|
+
s = store.get(sid)
|
|
536
|
+
if s is None:
|
|
537
|
+
self._send(404, {"error": "scenario_not_found", "id": sid})
|
|
538
|
+
return
|
|
539
|
+
self._send(200, s.to_dict())
|
|
540
|
+
elif method == "DELETE":
|
|
541
|
+
self._send(200, {"deleted": store.delete(sid), "id": sid})
|
|
542
|
+
else:
|
|
543
|
+
self._send(405, {"error": "method not allowed"})
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def make_server(app: App, host: str = "127.0.0.1", port: int = 0) -> ThreadingHTTPServer:
|
|
547
|
+
handler = type("BoundHandler", (Handler,), {"app": app})
|
|
548
|
+
server = ThreadingHTTPServer((host, port), handler)
|
|
549
|
+
server.daemon_threads = True
|
|
550
|
+
return server
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def serve(app: App, host: str = "127.0.0.1", port: int = 8787) -> ThreadingHTTPServer:
|
|
554
|
+
server = make_server(app, host, port)
|
|
555
|
+
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
556
|
+
thread.start()
|
|
557
|
+
return server
|