einstein-harness 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.
Files changed (74) hide show
  1. bench/__init__.py +23 -0
  2. bench/bench.py +309 -0
  3. bench/extra.py +152 -0
  4. browser/__init__.py +23 -0
  5. browser/agent.py +286 -0
  6. bus/__init__.py +1 -0
  7. bus/events_bus.py +147 -0
  8. channels/__init__.py +26 -0
  9. channels/base.py +297 -0
  10. channels/dingtalk_channel.py +130 -0
  11. channels/feishu_channel.py +195 -0
  12. channels/webhook_registry.yaml +44 -0
  13. cockpit/__init__.py +18 -0
  14. cockpit/briefing.py +216 -0
  15. cockpit/dashboard.py +255 -0
  16. cockpit/remote.py +197 -0
  17. compat/__init__.py +18 -0
  18. compat/dsh_converter.py +331 -0
  19. core/__init__.py +1 -0
  20. core/agent.py +156 -0
  21. core/code_mode.py +332 -0
  22. core/events.py +187 -0
  23. core/loop.py +261 -0
  24. core/tools.py +122 -0
  25. einstein_harness-0.3.0.dist-info/METADATA +386 -0
  26. einstein_harness-0.3.0.dist-info/RECORD +74 -0
  27. einstein_harness-0.3.0.dist-info/WHEEL +5 -0
  28. einstein_harness-0.3.0.dist-info/entry_points.txt +2 -0
  29. einstein_harness-0.3.0.dist-info/licenses/LICENSE +21 -0
  30. einstein_harness-0.3.0.dist-info/top_level.txt +19 -0
  31. guard/__init__.py +1 -0
  32. guard/gatekeeper.py +243 -0
  33. guard/permissions.py +189 -0
  34. interfaces/__init__.py +23 -0
  35. interfaces/acp_server.py +357 -0
  36. interfaces/bundles.py +398 -0
  37. interfaces/cli.py +136 -0
  38. interfaces/multimodal.py +233 -0
  39. interfaces/packaging/__init__.py +1 -0
  40. interfaces/web_server.py +345 -0
  41. interfaces/wire.py +260 -0
  42. mcptools/__init__.py +27 -0
  43. mcptools/client.py +504 -0
  44. mcptools/server_registry.yaml +78 -0
  45. memory/__init__.py +1 -0
  46. memory/memfs.py +206 -0
  47. memory/tiers.py +270 -0
  48. observe/__init__.py +1 -0
  49. observe/replay.py +189 -0
  50. observe/tracing.py +223 -0
  51. orchestrate/__init__.py +1 -0
  52. orchestrate/graph.py +406 -0
  53. orchestrate/interrupts.py +160 -0
  54. orchestrate/modes.py +202 -0
  55. orchestrate/parallel.py +271 -0
  56. org/__init__.py +6 -0
  57. org/locks.py +198 -0
  58. org/proxy.py +177 -0
  59. org/registry.py +251 -0
  60. providers/__init__.py +1 -0
  61. providers/deepseek_backend.py +36 -0
  62. providers/openai_compat.py +198 -0
  63. providers/zai_backend.py +37 -0
  64. sandbox_docker/__init__.py +34 -0
  65. sandbox_docker/provider.py +310 -0
  66. schedule/__init__.py +6 -0
  67. schedule/scheduler.py +475 -0
  68. session/__init__.py +1 -0
  69. session/compaction.py +222 -0
  70. session/jsonl_session.py +182 -0
  71. workload/__init__.py +1 -0
  72. workload/crew_registry.yaml +54 -0
  73. workload/run_crew_demo.py +49 -0
  74. workload/writing_crew.py +402 -0
bench/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """bench — 硬压测:四项压力测试(并发会话 / 事件链吞吐 / 大图 / 无损压缩)。
2
+
3
+ 跑法::
4
+
5
+ python3 -m bench.bench # 标准档,出数据报告
6
+ python3 -m bench.bench --quick # 快速档(冒烟 <15s)
7
+ python3 -m bench.bench --out bench/报告.md
8
+ """
9
+
10
+ from .bench import (
11
+ bench_compaction_1000,
12
+ bench_concurrent_sessions,
13
+ bench_eventlog_100k,
14
+ bench_graph_50,
15
+ render_markdown,
16
+ run_all,
17
+ )
18
+
19
+ __all__ = [
20
+ "bench_concurrent_sessions", "bench_eventlog_100k",
21
+ "bench_graph_50", "bench_compaction_1000",
22
+ "run_all", "render_markdown",
23
+ ]
bench/bench.py ADDED
@@ -0,0 +1,309 @@
1
+ """bench.bench — Einstein-Harness 硬压测(四项,出数据报告)。
2
+
3
+ 设计哲学(设计文档 v1.4 铁律 3):框架不能当第二个黑盒——性能也要可测量。
4
+ 四项压测对应四个关键主张:
5
+
6
+ B1 并发会话 —— L2 运行时扛多任务:10 会话同时跑 loop(EchoBackend,
7
+ 排除模型网络噪声,量的是 harness 本身的调度/事件链开销)
8
+ B2 事件链吞吐 —— append-only JSONL 的写入代价:10 万事件顺序落盘耗时
9
+ + 读回重放耗时(全轨迹可审计必须可承受)
10
+ B3 大图执行 —— L3 编排层扛复杂工作流:50 节点串行大图 + 每步 checkpoint,
11
+ 量执行吞吐与 checkpoint 放大系数
12
+ B4 无损压缩 —— 核心差异化主张的规模验证:1000 条消息压缩 → 快照 +
13
+ 锚点索引,校验三点:锚点可恢复 / 字节守恒 / 抽样完整
14
+
15
+ 每项输出 dict 指标;run_all() 汇总 + markdown 报告。
16
+ 机器噪声提示:报告附机型与 Python 版本,数据为单机参考值。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import platform
23
+ import statistics
24
+ import sys
25
+ import tempfile
26
+ import time
27
+ from concurrent.futures import ThreadPoolExecutor
28
+ from pathlib import Path
29
+ from typing import Any, Callable
30
+
31
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # einstein-harness root
32
+
33
+
34
+ def _py() -> str:
35
+ return f"{platform.python_implementation()} {platform.python_version()} · {platform.machine()}"
36
+
37
+
38
+ # ==========================================================================
39
+ # B1: 并发 10 会话同时跑 loop
40
+ # ==========================================================================
41
+
42
+ def bench_concurrent_sessions(n_sessions: int = 10) -> dict[str, Any]:
43
+ """10 个 AgentLoop 在线程池里同时跑完整 gather→act→verify 循环。"""
44
+ from core.agent import Agent, AgentSpec, EchoBackend
45
+ from core.loop import AgentLoop
46
+ from core.tools import default_toolbox
47
+ from core.events import EventLog
48
+
49
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b1_"))
50
+ work = tmp / "ws"
51
+ work.mkdir()
52
+
53
+ def one_session(i: int) -> dict[str, Any]:
54
+ backend = EchoBackend([
55
+ {"tool_calls": [{"name": "write_file",
56
+ "arguments": {"path": str(work / f"s{i}.txt"), "content": f"session-{i}"}}]},
57
+ {"text": f"session {i} done"},
58
+ ])
59
+ agent = Agent(
60
+ spec=AgentSpec(name=f"b1-agent-{i}", instructions="write then stop",
61
+ include_tools=("write_file",)),
62
+ backend=backend, toolbox=default_toolbox(), workspace=str(work),
63
+ )
64
+ loop = AgentLoop(agent, EventLog(tmp / f"s{i}.jsonl"))
65
+ t0 = time.perf_counter()
66
+ r = loop.run(f"run session {i}")
67
+ dt = time.perf_counter() - t0
68
+ assert r.final_text == f"session {i} done", r
69
+ assert (work / f"s{i}.txt").read_text() == f"session-{i}"
70
+ return {"session": i, "steps": r.steps, "wall_s": dt,
71
+ "events": len(EventLog(tmp / f"s{i}.jsonl").events())}
72
+
73
+ t_all = time.perf_counter()
74
+ with ThreadPoolExecutor(max_workers=n_sessions) as pool:
75
+ per = list(pool.map(one_session, range(n_sessions)))
76
+ wall_all = time.perf_counter() - t_all
77
+
78
+ walls = [p["wall_s"] for p in per]
79
+ return {
80
+ "bench": "B1 并发会话",
81
+ "n_sessions": n_sessions,
82
+ "wall_total_s": round(wall_all, 4),
83
+ "wall_mean_s": round(statistics.mean(walls), 4),
84
+ "wall_max_s": round(max(walls), 4),
85
+ "throughput_sessions_per_s": round(n_sessions / wall_all, 2),
86
+ "all_correct": all(p["steps"] == 2 for p in per),
87
+ }
88
+
89
+
90
+ # ==========================================================================
91
+ # B2: EventLog 写入 10 万事件耗时
92
+ # ==========================================================================
93
+
94
+ def bench_eventlog_100k(n_events: int = 100_000) -> dict[str, Any]:
95
+ """append-only JSONL 写吞吐 + 读回重放吞吐(全轨迹审计的成本底价)。"""
96
+ from core.events import AgentMessage, EventLog
97
+
98
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b2_"))
99
+ log = EventLog(tmp / "100k.jsonl")
100
+
101
+ t0 = time.perf_counter()
102
+ for i in range(n_events):
103
+ log.append(AgentMessage(content=f"msg-{i}: 压测消息,含中文与数字 {i}"))
104
+ write_s = time.perf_counter() - t0
105
+
106
+ t1 = time.perf_counter()
107
+ evs = log.events()
108
+ replay_s = time.perf_counter() - t1
109
+ assert len(evs) == n_events
110
+
111
+ size_mb = log.path.stat().st_size / 1e6
112
+ return {
113
+ "bench": "B2 事件链吞吐",
114
+ "n_events": n_events,
115
+ "write_s": round(write_s, 3),
116
+ "write_events_per_s": round(n_events / write_s),
117
+ "replay_s": round(replay_s, 3),
118
+ "replay_events_per_s": round(n_events / replay_s),
119
+ "log_size_mb": round(size_mb, 2),
120
+ "bytes_per_event": round(log.path.stat().st_size / n_events),
121
+ }
122
+
123
+
124
+ # ==========================================================================
125
+ # B3: graph 50 节点大图执行 + checkpoint
126
+ # ==========================================================================
127
+
128
+ def bench_graph_50(n_nodes: int = 50, reps: int = 5) -> dict[str, Any]:
129
+ """50 节点串行大图:每 super-step 落 checkpoint(LangGraph 式持久化的代价)。"""
130
+ from orchestrate.graph import CheckpointStore, StateGraph
131
+
132
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b3_"))
133
+ results: list[float] = []
134
+ n_checkpoints = 0
135
+
136
+ for rep in range(reps):
137
+ store = CheckpointStore(tmp / f"cp-{rep}.jsonl")
138
+ g = StateGraph()
139
+ for i in range(n_nodes):
140
+ g.add_node(f"n{i}", (lambda s, c, _i=i: {"v": s.get("v", 0) + 1, "last": _i}))
141
+ g.set_entry("n0")
142
+ for i in range(n_nodes - 1):
143
+ g.add_edge(f"n{i}", f"n{i+1}")
144
+ g.add_edge(f"n{n_nodes-1}", None)
145
+
146
+ t0 = time.perf_counter()
147
+ r = g.run({"v": 0}, store, max_supersteps=n_nodes + 10)
148
+ dt = time.perf_counter() - t0
149
+ assert r.stopped_reason == "" and r.final_state["v"] == n_nodes, r
150
+ results.append(dt)
151
+ n_checkpoints = len(store.load_all())
152
+
153
+ wall = statistics.mean(results)
154
+ return {
155
+ "bench": "B3 大图执行",
156
+ "n_nodes": n_nodes,
157
+ "reps": reps,
158
+ "wall_mean_s": round(wall, 4),
159
+ "wall_min_s": round(min(results), 4),
160
+ "supersteps_per_s": round(n_nodes / wall, 1),
161
+ "checkpoints_written": n_checkpoints,
162
+ "checkpoint_amplification": round(n_checkpoints / n_nodes, 2),
163
+ "ms_per_superstep": round(wall * 1000 / n_nodes, 3),
164
+ }
165
+
166
+
167
+ # ==========================================================================
168
+ # B4: 无损压缩 1000 条消息(快照 + 锚点完整性)
169
+ # ==========================================================================
170
+
171
+ def bench_compaction_1000(n_messages: int = 1000, sample: int = 5) -> dict[str, Any]:
172
+ """无损上下文协议规模验证:1000 消息 → 全量快照 + 锚点索引 → 完整性三查。
173
+
174
+ 完整性主张(协议原文):
175
+ ① 锚点可恢复:抽样锚点一跳取回原文,与渲染上下文逐字一致
176
+ ② 字节守恒:快照文件包含全部渲染行(零删除)
177
+ ③ verify 自检通过:协议「抽 3 条锚点验证」规则的机器执行
178
+ """
179
+ from session.compaction import LosslessCompactor
180
+ from core.events import AgentMessage, EventLog
181
+
182
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b4_"))
183
+ log = EventLog(tmp / "s.jsonl")
184
+ for i in range(n_messages):
185
+ log.append(AgentMessage(content=f"消息{i}:无损失上下文协议压测,正文长度填充 {'x' * (i % 50 + 20)}"))
186
+
187
+ comp = LosslessCompactor(snapshot_dir=tmp / "snapshots", unit_lines=4)
188
+ events = log.events()
189
+
190
+ t0 = time.perf_counter()
191
+ result = comp.compact(events)
192
+ compact_s = time.perf_counter() - t0
193
+
194
+ # ① 锚点可恢复(随机抽样,与原文逐字比对)
195
+ anchors = result.anchors
196
+ context = comp.render_context(events)
197
+ ctx_lines = context.splitlines()
198
+ t1 = time.perf_counter()
199
+ checked = 0
200
+ mismatches = 0
201
+ step = max(1, len(anchors) // sample)
202
+ for a in anchors[::step][:sample]:
203
+ recovered = comp.recover_anchor(a).splitlines()
204
+ expect = ctx_lines[a.start_line - 1: a.end_line]
205
+ checked += 1
206
+ if recovered != expect:
207
+ mismatches += 1
208
+ recover_s = time.perf_counter() - t1
209
+
210
+ # ② 字节守恒:快照中原始行数量 == 渲染行数量
211
+ snap_text = Path(result.snapshot_path).read_text(encoding="utf-8")
212
+ snap_body = [ln for ln in snap_text.splitlines()[4:] if ln.strip()]
213
+ byte_conserved = len(snap_body) == len(ctx_lines) and all(
214
+ ln.split("| ", 1)[1] == e for ln, e in zip(snap_body, ctx_lines))
215
+
216
+ # ③ verify 自检
217
+ verdict = comp.verify(result, samples=3)
218
+
219
+ ratio = result.ratio()
220
+ return {
221
+ "bench": "B4 无损压缩",
222
+ "n_messages": n_messages,
223
+ "anchors": len(anchors),
224
+ "compact_s": round(compact_s, 4),
225
+ "compact_msgs_per_s": round(n_messages / compact_s),
226
+ "snapshot_mb": round(Path(result.snapshot_path).stat().st_size / 1e6, 3),
227
+ "anchor_index_ratio": round(ratio, 4),
228
+ "anchors_sampled": checked,
229
+ "recover_mismatches": mismatches,
230
+ "recover_mean_ms": round(recover_s * 1000 / max(1, checked), 3),
231
+ "byte_conserved": bool(byte_conserved),
232
+ "verify_ok": bool(verdict["ok"]),
233
+ "lossless": bool(byte_conserved and mismatches == 0 and verdict["ok"]),
234
+ }
235
+
236
+
237
+ # ==========================================================================
238
+ # 汇总报告
239
+ # ==========================================================================
240
+
241
+ def run_all(out_path: str | Path | None = None, quick: bool = False) -> dict[str, Any]:
242
+ """跑四项压测并出 markdown 报告。quick=True 用小参数(冒烟用 <15s)。"""
243
+ if quick:
244
+ suite: list[tuple[str, Callable[[], dict[str, Any]]]] = [
245
+ ("B1", lambda: bench_concurrent_sessions(n_sessions=4)),
246
+ ("B2", lambda: bench_eventlog_100k(n_events=5_000)),
247
+ ("B3", lambda: bench_graph_50(n_nodes=20, reps=2)),
248
+ ("B4", lambda: bench_compaction_1000(n_messages=300)),
249
+ ]
250
+ else:
251
+ suite = [
252
+ ("B1", bench_concurrent_sessions),
253
+ ("B2", bench_eventlog_100k),
254
+ ("B3", bench_graph_50),
255
+ ("B4", bench_compaction_1000),
256
+ ]
257
+
258
+ out: dict[str, Any] = {"meta": {"python": _py(), "quick": quick,
259
+ "ts": time.strftime("%Y-%m-%d %H:%M:%S")}, "results": []}
260
+ for name, fn in suite:
261
+ t0 = time.perf_counter()
262
+ r = fn()
263
+ r["bench_wall_s"] = round(time.perf_counter() - t0, 3)
264
+ out["results"].append(r)
265
+ print(f"[bench] {r['bench']}: {r['bench_wall_s']}s", file=sys.stderr)
266
+
267
+ if out_path is not None:
268
+ Path(out_path).parent.mkdir(parents=True, exist_ok=True)
269
+ Path(out_path).write_text(render_markdown(out), encoding="utf-8")
270
+ return out
271
+
272
+
273
+ def render_markdown(report: dict[str, Any]) -> str:
274
+ """压测报告 → markdown(喂给 README / 战报)。"""
275
+ lines = [
276
+ "# Einstein-Harness 压测报告",
277
+ "",
278
+ f"> 环境: {report['meta']['python']} · {'快速档' if report['meta']['quick'] else '标准档'} · "
279
+ f"{report['meta']['ts']}",
280
+ "> 单机参考值(macOS arm64 / APFS),不同机器数值会有浮动,量级与比值是结论重点。",
281
+ "",
282
+ ]
283
+ for r in report["results"]:
284
+ lines.append(f"## {r['bench']}")
285
+ lines.append("")
286
+ lines.append("| 指标 | 值 |")
287
+ lines.append("|---|---|")
288
+ for k, v in r.items():
289
+ if k in ("bench", "bench_wall_s"):
290
+ continue
291
+ lines.append(f"| {k} | {v} |")
292
+ lines.append(f"| 本项压测耗时 | {r['bench_wall_s']}s |")
293
+ lines.append("")
294
+ return "\n".join(lines)
295
+
296
+
297
+ if __name__ == "__main__":
298
+ import argparse
299
+
300
+ ap = argparse.ArgumentParser(description="Einstein-Harness 硬压测")
301
+ ap.add_argument("--quick", action="store_true", help="快速档(冒烟用)")
302
+ ap.add_argument("--out", default="", help="markdown 报告输出路径")
303
+ ap.add_argument("--json", action="store_true", help="额外打印 JSON 指标")
304
+ args = ap.parse_args()
305
+ out_path = args.out or None
306
+ report = run_all(out_path=out_path, quick=args.quick)
307
+ print(render_markdown(report))
308
+ if args.json:
309
+ print(json.dumps(report, ensure_ascii=False, indent=2))
bench/extra.py ADDED
@@ -0,0 +1,152 @@
1
+ """bench.extra — B 路新增三模块压测(调度器吞吐/动态并行扩展/CodeMode 校验)。
2
+
3
+ 与 bench.bench 四项(B1-B4)同风格:量级与比值是结论重点,绝对耗时是参考。
4
+ - B5 调度器:1000 个 cron job 的 tick 决策开销(不含动作体)——纯调度吞吐
5
+ - B6 动态并行:Send fan-out 32 worker(线程池并行 + 独立 EventLog)总吞吐
6
+ - B7 CodeMode:AST 白名单校验吞吐 + 受限执行吞吐(校验是每次执行的前置成本)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # einstein-harness root
17
+
18
+
19
+ def bench_scheduler_tick(n_jobs: int = 1000) -> dict:
20
+ """1000 个 job 的 Scheduler.tick():纯调度决策吞吐(动作体为空操作)。"""
21
+ from schedule.scheduler import Scheduler
22
+
23
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b5_"))
24
+ sched = Scheduler(tmp, heartbeat_every_seconds=3600)
25
+ fired_holder: list[int] = []
26
+
27
+ def noop(payload=None): # noqa: ANN001 — 压测动作体故意为空
28
+ fired_holder.append(1)
29
+
30
+ sched.register_action("noop", noop)
31
+ for i in range(n_jobs):
32
+ sched.add_interval(every_seconds=60, action=noop, name=f"job{i}")
33
+ # 全部到点
34
+ for job in sched.jobs():
35
+ job.next_fire_at = 0.0
36
+
37
+ t0 = time.time()
38
+ fired = sched.tick()
39
+ dt = time.time() - t0
40
+ return {
41
+ "bench": "B5-scheduler",
42
+ "n_jobs": n_jobs,
43
+ "fired": len(fired),
44
+ "tick_seconds": round(dt, 4),
45
+ "jobs_per_s": int(n_jobs / dt) if dt > 0 else -1,
46
+ "audit_records": len(sched.fire_history(10**9)),
47
+ "all_allow": all(r.verdict == "allow" for r in sched.fire_history(10**9)),
48
+ }
49
+
50
+
51
+ def bench_parallel(n_workers: int = 32) -> dict:
52
+ """Send fan-out N worker(函数型,线程池并行 + 独立 EventLog)。"""
53
+ from orchestrate.parallel import SendParallel, Send
54
+
55
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b6_"))
56
+ pool = SendParallel(tmp / "logs", max_workers=n_workers)
57
+
58
+ def worker_fn(args, ctx):
59
+ s = 0
60
+ for i in range(1000):
61
+ s += i
62
+ return {"sum": s, "tag": args.get("tag")}
63
+
64
+ pool.register_worker("cpu", worker_fn)
65
+
66
+ def orchestrator(state, ctx):
67
+ return [Send("cpu", {"tag": i}) for i in range(state["n"])]
68
+
69
+ t0 = time.time()
70
+ result = pool.run(orchestrator, {"n": n_workers}, shared_key="outputs")
71
+ dt = time.time() - t0
72
+ logs = list((tmp / "logs").glob("*.jsonl"))
73
+ return {
74
+ "bench": "B6-parallel",
75
+ "n_workers": n_workers,
76
+ "n_ok": result.n_ok,
77
+ "n_failed": len(result.failed),
78
+ "outputs_merged": len(result.shared["outputs"]),
79
+ "seconds": round(dt, 4),
80
+ "workers_per_s": int(n_workers / dt) if dt > 0 else -1,
81
+ "independent_logs": len(logs),
82
+ "logs_match_workers": len(logs) == n_workers,
83
+ }
84
+
85
+
86
+ def bench_code_mode(n_iters: int = 300) -> dict:
87
+ """CodeMode:AST 校验吞吐 + 受限执行吞吐(同一段 20 行代码)。"""
88
+ from core.code_mode import CodeExecutor, validate_code
89
+
90
+ code_ok = "\n".join([
91
+ "def work(items):",
92
+ " total = 0",
93
+ " for it in items:",
94
+ " if it > 0:",
95
+ " total += scale(it)",
96
+ " return total",
97
+ "",
98
+ "vals = [1, 2, 3, 4, 5]",
99
+ "print(work(vals))",
100
+ ])
101
+
102
+ def scale(x):
103
+ return x * 10
104
+
105
+ import tempfile
106
+ tmp = Path(tempfile.mkdtemp(prefix="bench_b7_"))
107
+ ex = CodeExecutor({"scale": scale}, audit_path=tmp / "audit.jsonl")
108
+
109
+ t0 = time.time()
110
+ for _ in range(n_iters):
111
+ v = validate_code(code_ok, allowed_tools=frozenset({"scale"}))
112
+ assert v == []
113
+ t_validate = time.time() - t0
114
+
115
+ t0 = time.time()
116
+ for _ in range(n_iters):
117
+ r = ex.execute(code_ok)
118
+ assert r["ok"] and "150" in r["result"]
119
+ t_exec = time.time() - t0
120
+
121
+ t0 = time.time()
122
+ for _ in range(n_iters):
123
+ v = validate_code("import os\n" + code_ok)
124
+ assert v
125
+ t_deny = time.time() - t0
126
+
127
+ return {
128
+ "bench": "B7-codemode",
129
+ "n_iters": n_iters,
130
+ "validate_per_s": int(n_iters / t_validate) if t_validate > 0 else -1,
131
+ "execute_per_s": int(n_iters / t_exec) if t_exec > 0 else -1,
132
+ "deny_per_s": int(n_iters / t_deny) if t_deny > 0 else -1,
133
+ "audit_lines": sum(1 for _ in (tmp / "audit.jsonl").open()),
134
+ }
135
+
136
+
137
+ def run_extra() -> dict:
138
+ return {
139
+ "machine": f"{sys.platform}",
140
+ "results": [
141
+ bench_scheduler_tick(),
142
+ bench_parallel(),
143
+ bench_code_mode(),
144
+ ],
145
+ }
146
+
147
+
148
+ if __name__ == "__main__":
149
+ import json
150
+ report = run_extra()
151
+ for r in report["results"]:
152
+ print(json.dumps(r, ensure_ascii=False))
browser/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """browser/ — Playwright 浏览器子代理(L1 执行层).
2
+
3
+ Public surface:
4
+ BrowserAgent — mode-scoped tool registration (read_only | take_over)
5
+ BrowserSession — one headless chromium context (mechanism only)
6
+ BrowserUnavailable — honest-degrade signal when playwright/chromium missing
7
+
8
+ 纪律:每个动作都是普通 Tool 调用 → 全部过 guard 守门;截图/大纲落盘留路径。
9
+ """
10
+
11
+ from .agent import (
12
+ BrowserAgent,
13
+ BrowserSession,
14
+ BrowserUnavailable,
15
+ PLAYWRIGHT_AVAILABLE,
16
+ )
17
+
18
+ __all__ = [
19
+ "BrowserAgent",
20
+ "BrowserSession",
21
+ "BrowserUnavailable",
22
+ "PLAYWRIGHT_AVAILABLE",
23
+ ]