|
| 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 | +"""Tool safety guard quickstart application logic. |
| 7 | +
|
| 8 | +This module is shaped like other quickstart ``agent/agent.py`` files, but it is |
| 9 | +model-free on purpose: the issue being demonstrated is pre-execution script |
| 10 | +safety for tools and code executors, so the sample can run without API keys. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +from collections.abc import Iterable |
| 17 | +from pathlib import Path |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +from trpc_agent_sdk.code_executors import CodeBlock |
| 21 | +from trpc_agent_sdk.code_executors import CodeExecutionInput |
| 22 | +from trpc_agent_sdk.context import create_agent_context |
| 23 | +from trpc_agent_sdk.filter import FilterResult |
| 24 | +from trpc_agent_sdk.tools.safety import SafetyGuardedCodeExecutor |
| 25 | +from trpc_agent_sdk.tools.safety import ToolSafetyFilter |
| 26 | +from trpc_agent_sdk.tools.safety import ToolSafetyGuard |
| 27 | +from trpc_agent_sdk.tools.safety import ToolSafetyPolicy |
| 28 | +from trpc_agent_sdk.tools.safety import ToolSafetyScanRequest |
| 29 | + |
| 30 | +from .config import DEFAULT_CASES |
| 31 | +from .config import DEFAULT_OUT |
| 32 | +from .config import DEFAULT_POLICY |
| 33 | +from .config import QUICKSTART_DIR |
| 34 | +from .config import ScriptSafetyCase |
| 35 | +from .tools import DryRunScriptExecutor |
| 36 | +from .tools import dry_run_tool |
| 37 | +from .tools import read_script |
| 38 | + |
| 39 | + |
| 40 | +def _enum_value(value: Any) -> str: |
| 41 | + return value.value if hasattr(value, "value") else str(value) |
| 42 | + |
| 43 | + |
| 44 | +def _write_json(path: Path, payload: Any) -> None: |
| 45 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 46 | + path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") |
| 47 | + |
| 48 | + |
| 49 | +async def _run_filter_case(guard: ToolSafetyGuard, script: str, language: str) -> dict[str, Any]: |
| 50 | + filter_ = ToolSafetyFilter(guard=guard) |
| 51 | + |
| 52 | + async def handle() -> FilterResult: |
| 53 | + return FilterResult(rsp=await dry_run_tool(script, language=language)) |
| 54 | + |
| 55 | + result = await filter_.run( |
| 56 | + create_agent_context(), |
| 57 | + { |
| 58 | + "script": script, |
| 59 | + "language": language, |
| 60 | + "cwd": str(QUICKSTART_DIR), |
| 61 | + }, |
| 62 | + handle, |
| 63 | + ) |
| 64 | + return { |
| 65 | + "continued": bool(result.is_continue), |
| 66 | + "response": result.rsp, |
| 67 | + } |
| 68 | + |
| 69 | + |
| 70 | +async def _run_executor_case(guard: ToolSafetyGuard, script: str, language: str) -> dict[str, Any]: |
| 71 | + executor = SafetyGuardedCodeExecutor( |
| 72 | + delegate=DryRunScriptExecutor(work_dir=str(QUICKSTART_DIR)), |
| 73 | + guard=guard, |
| 74 | + ) |
| 75 | + result = await executor.execute_code( |
| 76 | + invocation_context=None, # type: ignore[arg-type] |
| 77 | + code_execution_input=CodeExecutionInput(code_blocks=[CodeBlock(language=language, code=script)]), |
| 78 | + ) |
| 79 | + return { |
| 80 | + "outcome": _enum_value(result.outcome), |
| 81 | + "output": result.output, |
| 82 | + } |
| 83 | + |
| 84 | + |
| 85 | +async def run_quickstart( |
| 86 | + *, |
| 87 | + policy_path: Path = DEFAULT_POLICY, |
| 88 | + output_dir: Path = DEFAULT_OUT, |
| 89 | + cases: Iterable[ScriptSafetyCase] = DEFAULT_CASES, |
| 90 | +) -> dict[str, Any]: |
| 91 | + """Run the model-free tool safety quickstart and write a report.""" |
| 92 | + |
| 93 | + policy = ToolSafetyPolicy.load(policy_path) |
| 94 | + audit_path = output_dir / "audit.jsonl" |
| 95 | + report_path = output_dir / "quickstart_report.json" |
| 96 | + guard = ToolSafetyGuard(policy=policy, audit_log_path=audit_path) |
| 97 | + case_results = [] |
| 98 | + |
| 99 | + for case in cases: |
| 100 | + script = read_script(case.script_path) |
| 101 | + report = guard.scan( |
| 102 | + ToolSafetyScanRequest( |
| 103 | + script=script, |
| 104 | + language=case.language, |
| 105 | + cwd=str(QUICKSTART_DIR), |
| 106 | + tool_metadata={ |
| 107 | + "name": case.name, |
| 108 | + "script_path": str(case.script_path), |
| 109 | + }, |
| 110 | + ) |
| 111 | + ) |
| 112 | + filter_result = await _run_filter_case(guard, script, case.language) |
| 113 | + executor_result = await _run_executor_case(guard, script, case.language) |
| 114 | + case_results.append( |
| 115 | + { |
| 116 | + "name": case.name, |
| 117 | + "script": str(case.script_path.relative_to(QUICKSTART_DIR)), |
| 118 | + "language": case.language, |
| 119 | + "decision": _enum_value(report.decision), |
| 120 | + "risk_level": _enum_value(report.risk_level), |
| 121 | + "blocked": report.blocked, |
| 122 | + "rule_ids": [finding.rule_id for finding in report.findings], |
| 123 | + "summary": report.summary, |
| 124 | + "filter": filter_result, |
| 125 | + "code_executor": executor_result, |
| 126 | + } |
| 127 | + ) |
| 128 | + |
| 129 | + summary = { |
| 130 | + "policy": { |
| 131 | + "name": policy.name, |
| 132 | + "version": policy.version, |
| 133 | + "path": str(policy_path), |
| 134 | + }, |
| 135 | + "case_count": len(case_results), |
| 136 | + "decision_counts": { |
| 137 | + decision: sum(1 for case in case_results if case["decision"] == decision) |
| 138 | + for decision in sorted({case["decision"] for case in case_results}) |
| 139 | + }, |
| 140 | + "cases": case_results, |
| 141 | + "report": str(report_path), |
| 142 | + "audit_log": str(audit_path), |
| 143 | + } |
| 144 | + _write_json(report_path, summary) |
| 145 | + return summary |
0 commit comments