|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# tRPC-Agent-Python is licensed under Apache-2.0. |
| 6 | +"""Run the tool safety guard quickstart project. |
| 7 | +
|
| 8 | +This script demonstrates the same guard in three integration points: |
| 9 | +direct scan, Tool Filter, and CodeExecutor wrapper. It writes a structured |
| 10 | +summary under ``out/`` without executing any untrusted sample script. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import argparse |
| 16 | +import asyncio |
| 17 | +import json |
| 18 | +import sys |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +HERE = Path(__file__).resolve().parent |
| 23 | +REPO_ROOT = HERE.parents[2] |
| 24 | +if str(REPO_ROOT) not in sys.path: |
| 25 | + sys.path.insert(0, str(REPO_ROOT)) |
| 26 | + |
| 27 | +from trpc_agent_sdk.code_executors import CodeBlock # noqa: E402 |
| 28 | +from trpc_agent_sdk.code_executors import CodeExecutionInput # noqa: E402 |
| 29 | +from trpc_agent_sdk.context import create_agent_context # noqa: E402 |
| 30 | +from trpc_agent_sdk.filter import FilterResult # noqa: E402 |
| 31 | +from trpc_agent_sdk.tools.safety import SafetyGuardedCodeExecutor # noqa: E402 |
| 32 | +from trpc_agent_sdk.tools.safety import ToolSafetyFilter # noqa: E402 |
| 33 | +from trpc_agent_sdk.tools.safety import ToolSafetyGuard # noqa: E402 |
| 34 | +from trpc_agent_sdk.tools.safety import ToolSafetyPolicy # noqa: E402 |
| 35 | +from trpc_agent_sdk.tools.safety import ToolSafetyScanRequest # noqa: E402 |
| 36 | + |
| 37 | +try: |
| 38 | + from examples.tool_safety_guard.quickstart.tool_service import DryRunScriptExecutor # noqa: E402 |
| 39 | + from examples.tool_safety_guard.quickstart.tool_service import dry_run_tool # noqa: E402 |
| 40 | + from examples.tool_safety_guard.quickstart.tool_service import read_script # noqa: E402 |
| 41 | +except ModuleNotFoundError: |
| 42 | + from tool_service import DryRunScriptExecutor # noqa: E402 |
| 43 | + from tool_service import dry_run_tool # noqa: E402 |
| 44 | + from tool_service import read_script # noqa: E402 |
| 45 | + |
| 46 | +DEFAULT_POLICY = HERE / "policy.yaml" |
| 47 | +DEFAULT_OUT = HERE / "out" |
| 48 | +DEFAULT_CASES = [ |
| 49 | + ("safe_report", HERE / "scripts" / "safe_report.py", "python"), |
| 50 | + ("external_upload", HERE / "scripts" / "external_upload.py", "python"), |
| 51 | + ("read_secret", HERE / "scripts" / "read_secret.py", "python"), |
| 52 | + ("review_subprocess", HERE / "scripts" / "review_subprocess.py", "python"), |
| 53 | + ("dangerous_cleanup", HERE / "scripts" / "dangerous_cleanup.sh", "bash"), |
| 54 | +] |
| 55 | + |
| 56 | + |
| 57 | +def _write_json(path: Path, payload: Any) -> None: |
| 58 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 59 | + path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") |
| 60 | + |
| 61 | + |
| 62 | +async def _run_filter_case(guard: ToolSafetyGuard, script: str, language: str) -> dict[str, Any]: |
| 63 | + filter_ = ToolSafetyFilter(guard=guard) |
| 64 | + |
| 65 | + async def handle() -> FilterResult: |
| 66 | + return FilterResult(rsp=await dry_run_tool(script, language=language)) |
| 67 | + |
| 68 | + result = await filter_.run( |
| 69 | + create_agent_context(), |
| 70 | + { |
| 71 | + "script": script, |
| 72 | + "language": language, |
| 73 | + "cwd": str(HERE), |
| 74 | + }, |
| 75 | + handle, |
| 76 | + ) |
| 77 | + return { |
| 78 | + "continued": bool(result.is_continue), |
| 79 | + "response": result.rsp, |
| 80 | + } |
| 81 | + |
| 82 | + |
| 83 | +async def _run_executor_case(guard: ToolSafetyGuard, script: str, language: str) -> dict[str, Any]: |
| 84 | + executor = SafetyGuardedCodeExecutor( |
| 85 | + delegate=DryRunScriptExecutor(work_dir=str(HERE)), |
| 86 | + guard=guard, |
| 87 | + ) |
| 88 | + result = await executor.execute_code( |
| 89 | + invocation_context=None, # type: ignore[arg-type] |
| 90 | + code_execution_input=CodeExecutionInput(code_blocks=[CodeBlock(language=language, code=script)]), |
| 91 | + ) |
| 92 | + return { |
| 93 | + "outcome": result.outcome.value if hasattr(result.outcome, "value") else str(result.outcome), |
| 94 | + "output": result.output, |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | +async def run_quickstart(*, policy_path: Path = DEFAULT_POLICY, output_dir: Path = DEFAULT_OUT) -> dict[str, Any]: |
| 99 | + policy = ToolSafetyPolicy.load(policy_path) |
| 100 | + audit_path = output_dir / "audit.jsonl" |
| 101 | + guard = ToolSafetyGuard(policy=policy, audit_log_path=audit_path) |
| 102 | + cases = [] |
| 103 | + |
| 104 | + for name, path, language in DEFAULT_CASES: |
| 105 | + script = read_script(path) |
| 106 | + report = guard.scan( |
| 107 | + ToolSafetyScanRequest( |
| 108 | + script=script, |
| 109 | + language=language, |
| 110 | + cwd=str(HERE), |
| 111 | + tool_metadata={ |
| 112 | + "name": name, |
| 113 | + "script_path": str(path), |
| 114 | + }, |
| 115 | + )) |
| 116 | + filter_result = await _run_filter_case(guard, script, language) |
| 117 | + executor_result = await _run_executor_case(guard, script, language) |
| 118 | + cases.append({ |
| 119 | + "name": name, |
| 120 | + "script": str(path.relative_to(HERE)), |
| 121 | + "language": language, |
| 122 | + "decision": report.decision.value if hasattr(report.decision, "value") else str(report.decision), |
| 123 | + "risk_level": report.risk_level.value if hasattr(report.risk_level, "value") else str(report.risk_level), |
| 124 | + "blocked": report.blocked, |
| 125 | + "rule_ids": [finding.rule_id for finding in report.findings], |
| 126 | + "summary": report.summary, |
| 127 | + "filter": filter_result, |
| 128 | + "code_executor": executor_result, |
| 129 | + }) |
| 130 | + |
| 131 | + summary = { |
| 132 | + "policy": { |
| 133 | + "name": policy.name, |
| 134 | + "version": policy.version, |
| 135 | + "path": str(policy_path), |
| 136 | + }, |
| 137 | + "case_count": len(cases), |
| 138 | + "decision_counts": { |
| 139 | + decision: sum(1 for case in cases if case["decision"] == decision) |
| 140 | + for decision in sorted({case["decision"] for case in cases}) |
| 141 | + }, |
| 142 | + "cases": cases, |
| 143 | + "audit_log": str(audit_path), |
| 144 | + } |
| 145 | + _write_json(output_dir / "quickstart_report.json", summary) |
| 146 | + return summary |
| 147 | + |
| 148 | + |
| 149 | +def _parse_args() -> argparse.Namespace: |
| 150 | + parser = argparse.ArgumentParser(description="Run the tool safety guard quickstart.") |
| 151 | + parser.add_argument("--policy", type=Path, default=DEFAULT_POLICY) |
| 152 | + parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUT) |
| 153 | + return parser.parse_args() |
| 154 | + |
| 155 | + |
| 156 | +def main() -> None: |
| 157 | + args = _parse_args() |
| 158 | + summary = asyncio.run(run_quickstart(policy_path=args.policy.resolve(), output_dir=args.output_dir.resolve())) |
| 159 | + print("Tool safety quickstart decisions:") |
| 160 | + for case in summary["cases"]: |
| 161 | + print(f"- {case['name']}: {case['decision']} ({', '.join(case['rule_ids']) or 'no findings'})") |
| 162 | + print(f"Report written to: {summary['audit_log']}") |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + main() |
0 commit comments