安全策略

本页目录

SDK 提供了一个声明性策略引擎,用于控制工具执行和请求人工批准。

默认情况下,允许自定义Python函数和标准只读工具,而高风险系统操作(例如使用run_command执行shell命令)需要显式权限或策略规则。

声明式策略引擎

定义明确的规则以允许、拒绝或请求工具调用的人工批准。

例如,您可以将 SDK 配置为在 Agent 尝试执行 shell 命令时需要批准:

from google.antigravity import LocalAgentConfig
from google.antigravity.hooks.policy import deny, allow, ask_user

async def my_handler(tool_call):
    print(f"Tool approval requested for: {tool_call.name}")
    return True

policies = [
    deny("*"),                                     # Deny all tools by default
    allow("view_file"),                            # Allow file viewing
    ask_user("run_command", handler=my_handler),   # Ask approval for shell
]

config = LocalAgentConfig(policies=policies)

包含人工审批的交互式循环

在 CLI 应用程序中,您可以在执行高风险工具之前以交互方式提示用户。

例如,使用 run_interactive_loop 与 policy.safe_defaults 组合来启动控制台会话,每当请求任何写入工具(文件创建、编辑或 shell 执行)时,该会话都会提示用户批准:

import asyncio
from google.antigravity import LocalAgentConfig
from google.antigravity.hooks import policy
from google.antigravity.utils import interactive
from google.antigravity.utils.interactive import run_interactive_loop

# safe_defaults allows read-only tools and asks user for write operations
policies = policy.safe_defaults(handler=interactive.ask_user_handler)
config = LocalAgentConfig(policies=policies)

if __name__ == "__main__":
    asyncio.run(run_interactive_loop(config))

执行过程中,控制台会出现交互式审批提示:

Starting interactive loop. Type 'exit' or 'quit' to end.
User: Run the 'ls' command to see what is in this directory.

Policy check: Tool execution requested: run_command
Arguments: {'CommandLine': 'ls -la'}
Allow execution? (y/n) [n]:

示例代码

有关完整的工作代码示例,请查看 GitHub 存储库: