新闻详情

新闻详情

首页 / 资讯中心 / 详情

Agent-OS 策略 Schema 与 PolicyEngine 权威指南:为自主 AI Agent 构建声明式与编程式治理策略

发布时间:2026/9/17 14:24:31来源:尧图网络
Agent-OS 策略 Schema 与 PolicyEngine 权威指南:为自主 AI Agent 构建声明式与编程式治理策略
Agent-OS 策略 Schema 与 PolicyEngine 权威指南为自主 AI Agent 构建声明式与编程式治理策略【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit本指南以 Agent-OSagent-governance-toolkit 的 Python Agent 运行时内核的策略 Schema 参考文档为骨架完整解析其 JSON Schema 定义、Python API 用法与内置安全防护并对照PolicyEngine 源码展开实现级解读。读完本文你将能够通过 YAML 配置或PolicyEngine编程接口为任意 Agent 角色声明允许清单allow-list、ABAC 条件权限、资源配额与风险策略并理解违规检查、速率限制、风险校验在底层是如何被强制执行的。一、两种策略定义方式YAML 声明式 vs Python 编程式Agent-OS 提供两条平行的策略定义路径二者最终都会汇聚到同一个执行内核YAML 配置.agents/security.md声明式、基于文件。在仓库的.agents/security.md中按规范书写kernel、signals、policies、observability等小节具体字段格式见 Agent OS 安全规范。Python APIPolicyEngine编程式、基于代码。通过agent_control_plane.policy_engine包内的PolicyEngine、Condition、ConditionalPermission、ResourceQuota、RiskPolicy等类在代码中动态构建策略。从源码结构看PolicyEngine位于modules/control-plane/src/agent_control_plane/policy_engine.py约 1000 余行它提供三层校验角色级 → 条件级 → 参数级、配额限流、风险评分校验以及一组始终生效的内置安全检查ActionType等基础类型定义在同目录的 agent_kernel.py 中。两种方式最终都通过PolicyEngine.check_violation()、check_rate_limit()、validate_risk()三个核心入口完成强制。二、策略 JSON Schema 参考对于需要做策略定义校验的工具链Agent-OS 提供了完整的 JSON SchemaDraft-07。它定义了五个可复用类型condition、conditional_permission、resource_quota、risk_policy、policy_rule并在顶层properties中暴露agent_constraints、conditional_permissions、quotas、risk_policies、custom_rules五个维度。完整 Schema 如下可直接用于编辑器提示或 CI 校验{ $schema: http://json-schema.org/draft-07/schema#, $id: https://agent-os.dev/schemas/policy-v1.json, title: Agent-OS Policy Schema, description: Schema for defining governance policies in Agent-OS, type: object, definitions: { condition: { type: object, description: ABAC condition for attribute-based access control, required: [attribute_path, operator, value], properties: { attribute_path: { type: string, description: Dot-notation path to attribute (e.g., args.amount, context.user_role), examples: [user_status, args.amount, context.time_of_day] }, operator: { type: string, enum: [eq, ne, gt, lt, gte, lte, in, not_in, contains, starts_with, not_starts_with, not_contains], description: Comparison operator }, value: { description: Value to compare against (type depends on operator) } } }, conditional_permission: { type: object, description: Permission with ABAC conditions, required: [tool_name], properties: { tool_name: { type: string, description: Name of the tool this permission applies to }, conditions: { type: array, items: { $ref: #/definitions/condition }, description: List of conditions that must be met }, require_all: { type: boolean, default: true, description: If true, ALL conditions must pass (AND). If false, ANY condition passes (OR) } } }, resource_quota: { type: object, description: Rate limits and resource quotas for an agent, properties: { max_requests_per_minute: { type: integer, minimum: 0, default: 60 }, max_requests_per_hour: { type: integer, minimum: 0, default: 1000 }, max_execution_time_seconds: { type: number, minimum: 0, default: 30 }, max_concurrent_executions: { type: integer, minimum: 1, default: 5 }, allowed_action_types: { type: array, items: { type: string, enum: [code_execution, file_read, file_write, api_call, database_query, database_write, workflow_trigger] } } } }, risk_policy: { type: object, description: Risk-based enforcement thresholds, properties: { max_risk_score: { type: number, minimum: 0, maximum: 1, default: 0.8, description: Actions above this score are denied }, require_approval_above: { type: number, minimum: 0, maximum: 1, default: 0.5, description: Actions above this score require human approval }, deny_above: { type: number, minimum: 0, maximum: 1, default: 0.9, description: Actions above this score are automatically denied }, high_risk_patterns: { type: array, items: { type: string }, description: Regex patterns that indicate high-risk actions }, allowed_domains: { type: array, items: { type: string }, description: Domains allowed for API calls }, blocked_domains: { type: array, items: { type: string }, description: Domains blocked for API calls } } }, policy_rule: { type: object, description: Custom policy rule with validator function, required: [rule_id, name, action_types], properties: { rule_id: { type: string, description: Unique identifier for this rule }, name: { type: string, description: Human-readable name }, description: { type: string, description: What this rule enforces }, action_types: { type: array, items: { type: string, enum: [code_execution, file_read, file_write, api_call, database_query, database_write, workflow_trigger] } }, priority: { type: integer, default: 0, description: Higher priority rules are checked first } } } }, properties: { version: { type: string, const: 1.0 }, agent_constraints: { type: object, description: Map of agent_id to allowed tools (allow-list approach), additionalProperties: { type: array, items: { type: string } } }, conditional_permissions: { type: object, description: Map of agent_id to conditional permissions, additionalProperties: { type: array, items: { $ref: #/definitions/conditional_permission } } }, quotas: { type: object, description: Map of agent_id to resource quota, additionalProperties: { $ref: #/definitions/resource_quota } }, risk_policies: { type: object, description: Map of policy_id to risk policy, additionalProperties: { $ref: #/definitions/risk_policy } }, custom_rules: { type: array, items: { $ref: #/definitions/policy_rule } } } }几个值得注意的设计点allowed_action_types与policy_rule.action_types的枚举值与 agent_kernel.py 中ActionType枚举一一对应CODE_EXECUTION、FILE_READ、FILE_WRITE、API_CALL、DATABASE_QUERY、DATABASE_WRITE、WORKFLOW_TRIGGER。require_all默认true多条件时默认取 AND 语义只有显式设为false才转为 OR。agent_constraints/conditional_permissions/quotas都是agent_id → 策略对象的映射即同一份策略库可以按角色、按 Agent 实例分别施加约束。三、Python API 参考PolicyEngine 与核心数据结构PolicyEngine是整个策略强制的核心组件位于 policy_engine.py。初始化与导入方式from agent_control_plane.policy_engine import ( PolicyEngine, Condition, ConditionalPermission, ResourceQuota, RiskPolicy, ) # Initialize engine PolicyEngine()从源码看PolicyEngine.__init__内部维护了以下状态policy_engine.pyquotas: Dict[str, ResourceQuota]—— 按agent_id存储配额risk_policies: Dict[str, RiskPolicy]—— 按policy_id存储风险策略custom_rules: List[PolicyRule]—— 自定义规则按priority降序排序后依次执行state_permissions: Dict[str, set]—— 角色到允许工具集的映射allow-listconditional_permissions: Dict[str, List[ConditionalPermission]]—— 角色到条件权限列表agent_contexts: Dict[str, Dict[str, Any]]—— ABAC 求值所需的上下文属性dangerous_code_patterns/protected_paths—— 内置危险模式与受保护路径详见第六节。四个核心数据类均为dataclass字段与 JSON Schema 对应。Condition类policy_engine.py通过evaluate(context)对上下文求值先用点号路径_get_nested_value()从上下文中逐层取出属性值如args.amount会先取args再取amount属性缺失返回False默认拒绝随后按operator完成比较。ConditionalPermission.is_allowed()policy_engine.py在require_allTrue时用all()聚合ANDrequire_allFalse时用any()聚合OR。四、添加约束Allow-List最安全的默认拒绝模型这是最安全的策略方式——只显式放行被允许的工具其余一切默认拒绝Scale by Subtraction。源码在add_constraint()中将其注释为定义 Agent 的物理法则policy_engine.py# Agent data-analyst can only use these tools engine.add_constraint(data-analyst, [ file_read, database_query, api_call, ]) # Agent admin can use more tools engine.add_constraint(admin, [ file_read, file_write, database_query, database_write, code_execution, ])实现细节state_permissions[role] set(allowed_tools)未在集合中的工具在check_violation()第一层角色检查即被拦截返回Role {agent_role} cannot use tool {tool_name}。值得留意的是源码对权限集采用set存储因此重复添加同一工具是幂等的。五、添加条件权限ABAC上下文感知的细粒度访问控制ABAC基于属性的访问控制让策略从角色能做什么升级为在什么条件下角色能做什么。示例——仅允许对已验证用户、且金额不超过 $1000 的退款操作# Allow refunds only for verified users, up to $1000 refund_permission ConditionalPermission( tool_namerefund_user, conditions[ Condition( attribute_pathuser_status, operatoreq, valueverified ), Condition( attribute_pathargs.amount, operatorlte, value1000 ), ], require_allTrue # Both conditions must pass ) engine.add_conditional_permission(support-agent, refund_permission) # Set context for the agent engine.set_agent_context(support-agent, { user_status: verified, department: customer-service })对应源码行为policy_engine.pyadd_conditional_permission()会把该工具同时加入角色的基础 allow-list保证能通过第一层角色检查条件判定放到第二层做set_agent_context()/update_agent_context()分别用于整体设置或增量更新上下文属性在check_violation()的第二层求值上下文eval_context由三部分合并而成{args: args, context: agent_context}再并入上下文顶层属性。因此条件里的attribute_path可以引用args.amount工具参数、user_status上下文顶层属性或context.time_of_day等任意点号路径。此外源码还提供is_shadow_mode(agent_role)用于判断某 Agent 是否处于影子模式仅记录不执行对应 YAML 中kernel.mode: audit的语义。六、设置资源配额限流与并发控制配额用于限制 Agent 的请求频率、执行时长与并发数quota ResourceQuota( max_requests_per_minute60, max_requests_per_hour1000, max_execution_time_seconds30, max_concurrent_executions5, allowed_action_types[ ActionType.FILE_READ, ActionType.API_CALL, ] ) engine.set_quota(my-agent, quota)ResourceQuota的 dataclass 默认值policy_engine.py与 JSON Schema 中声明的基本一致仅max_execution_time_seconds源码默认是300.0Schema 中为 30二者以实际运行版本为准。配额内部自带用量追踪字段requests_this_minute、requests_this_hour、current_executions以及窗口重置时间戳。check_rate_limit()policy_engine.py的执行逻辑未设置配额的 Agent 默认放行距上次重置超过 60 秒则清零分钟计数、超过 3600 秒则清零小时计数滑动窗口按自然时间重置依次校验分钟上限、小时上限、并发上限以及allowed_action_types非空时才生效全部通过后递增计数返回True。get_quota_status(agent_id)可以随时查询某 Agent 的实时用量与上限用于监控面板或告警。七、设置风险策略基于风险评分的分级强制风险策略依据动作的风险评分做分级处理——低于max_risk_score直接放行、介于require_approval_above与deny_above之间要求人工审批、高于deny_above自动拒绝risk_policy RiskPolicy( max_risk_score0.8, require_approval_above0.5, deny_above0.9, high_risk_patterns[ r\brm\s-rf\b, r\bdrop\stable\b, ], allowed_domains[api.internal.com, api.trusted.com], blocked_domains[*.malware.com] ) engine.set_risk_policy(production, risk_policy)validate_risk()policy_engine.py会遍历所有已注册风险策略并执行三类检查风险分数阈值risk_score deny_above直接拒绝高危模式在请求参数文本中做大小写不敏感的子串匹配命中即拒绝域名约束请求参数中带url或domain时先经_extract_host()用urlparse解析出规范化 hostname自动剔除user、端口、尾点并校验 DNS 合法性再与blocked_domains/allowed_domains匹配。源码对域名匹配有两个值得强调的 fail-closed 设计policy_engine.py其一解析不出合法 hostname 时直接拒绝避免对攻击者可控字符串做脆弱的子串匹配其二_host_matches()只接受精确相等或真子域两种关系——evil.com不会误伤safe-evil.com也无法通过safe.com/path?evil.com之类字符串绕过。blocked_domains支持*.malware.com这类通配写法。八、检查违规check_violation的三层校验check_violation(agent_role, tool_name, args)返回None表示放行否则返回描述性错误字符串# Returns None if allowed, or error message if blocked violation engine.check_violation( agent_roledata-analyst, tool_namefile_write, # Not in allow-list! args{path: /data/output.csv} ) if violation: print(fBlocked: {violation}) # Output: Blocked: Role># Automatically blocked: # - Paths containing .. # - Paths to system directories: /etc/, /sys/, /proc/, /dev/ # - Windows system paths: C:\Windows\System32源码中protected_paths默认列表即[/etc/, /sys/, /proc/, /dev/, C:\\Windows\\System32]配合归一化路径双重校验policy_engine.py。10.2 危险代码模式# Automatically blocked in code_execution: # - rm -rf # - format (disk formatting) # - DROP TABLE / DROP DATABASE # - TRUNCATE TABLE # - DELETE FROM (without WHERE)源码的dangerous_code_patterns用正则实现大小写不敏感\brm\s-rf\b、\bdel\s/f\bWindows、\bformat\s、\bdrop\stable\b、\bdrop\sdatabase\b、\btruncate\stable\b、\bdelete\sfrom\bpolicy_engine.py。10.3 SQL 注入与破坏性 SQL 预防# Automatically sanitized: # - Comments stripped # - Multiple statements detected # - Destructive operations blocked除了check_violation中的正则兜底外控制平面还提供了更强的 AST 级 SQL 校验create_policies_from_config()与_build_policy_rules()会生成三条默认策略规则policy_engine.pyno_system_file_accesspriority10阻断对系统目录的文件读写no_credential_exposurepriority10检测参数中是否泄露password、secret、api_key、token、credential等敏感关键词no_destructive_sqlpriority9优先用sqlglot做 AST 解析识别DROP、TRUNCATE、无WHERE的DELETE/UPDATE、ALTER、GRANT/REVOKE、CREATE USER/ROLE、MERGE、EXEC xp_cmdshell、LOAD_FILE/INTO OUTFILE等危险构造解析失败或sqlglot未安装时fail-closed 直接拒绝。同时SQLPolicyConfig与load_sql_policy_config()支持从 YAML 加载可配置的 SQL 策略blocked_statements、require_where_clause、blocked_create_types、blocked_patterns并将注释剥离后做正则兜底防止/* DROP */这类绕过尝试。十一、完整策略配置示例从约束到内核接线下面是一份端到端的完整配置涵盖允许清单、ABAC 条件、配额、风险策略以及如何将PolicyEngine接入KernelSpace与FlightRecorder使所有 syscall 都经过策略强制from agent_control_plane.policy_engine import ( PolicyEngine, Condition, ConditionalPermission, ResourceQuota, RiskPolicy ) from agent_control_plane.agent_kernel import ActionType # Initialize engine PolicyEngine() # 1. Define allow-lists for each agent role engine.add_constraint(reader, [file_read, database_query]) engine.add_constraint(writer, [file_read, file_write, database_query, database_write]) engine.add_constraint(admin, [*]) # All tools # 2. Add ABAC conditions for sensitive operations engine.add_conditional_permission(writer, ConditionalPermission( tool_namedatabase_write, conditions[ Condition(args.table, not_in, [users, credentials, audit_log]), ] )) # 3. Set quotas engine.set_quota(reader, ResourceQuota( max_requests_per_minute100, max_requests_per_hour2000, )) engine.set_quota(writer, ResourceQuota( max_requests_per_minute30, max_requests_per_hour500, max_concurrent_executions2, )) # 4. Set risk policies engine.set_risk_policy(default, RiskPolicy( max_risk_score0.7, require_approval_above0.5, blocked_domains[*.evil.com], )) # 5. Wire to KernelSpace from agent_control_plane.kernel_space import KernelSpace from agent_control_plane.flight_recorder import FlightRecorder kernel KernelSpace( policy_engineengine, flight_recorderFlightRecorder(audit.db), ) # 6. Register tools kernel.register_tool(file_read, my_file_read_function) kernel.register_tool(database_query, my_db_query_function) # 7. Create agent and execute ctx kernel.create_agent_context(reader) # Now all syscalls go through policy enforcement对照 kernel_space.py 源码KernelSpace.__init__接受policy_engine与flight_recorder第 235-246 行附近create_agent_context()创建会话在系统调用分发处如第 515、694 行调用self._policy_engine.check_violation(...)做授权未传入policy_engine时对应 syscall 会被显式拦截体现 fail-closed 原则。自定义规则方面add_custom_rule(PolicyRule)会将规则按priority降序插入validate_request()会依次执行限流检查与自定义规则校验规则未通过返回policy_violation: name。十二、从 YAML 迁移到 Python API若你已有.agents/security.md其 YAML 字段格式见 Agent OS 安全规范可通过如下工具函数将其转换为PolicyEngine调用import yaml def load_yaml_policies(path: str, engine: PolicyEngine): Convert YAML security config to PolicyEngine calls. with open(path) as f: config yaml.safe_load(f) for policy in config.get(policies, []): action policy[action] effect policy.get(effect, allow) if effect deny: # Dont add to allow-list (implicit deny) continue # Add to default allow-list engine.add_constraint(default, [action]) # Add rate limits if specified if rate_limit in policy: count, period policy[rate_limit].split(/) if period hour: quota ResourceQuota(max_requests_per_hourint(count)) elif period minute: quota ResourceQuota(max_requests_per_minuteint(count)) engine.set_quota(default, quota)迁移要点YAML 中effect: deny的策略不需要写入 allow-list——因为默认拒绝模型下未声明即拒绝rate_limit: 100/hour这类字段会转化为ResourceQuota对应上限。此外安全规范还提供了agentos init --template strict|permissive、agentos secure --verify、agentos audit --format json等 CLI 命令用于初始化、校验与审计配置。十三、冻结引擎抵御运行期自修改攻击这是原文档之外、源码中一个值得单独强调的安全特性PolicyEngine.freeze()policy_engine.py在完成初始配置后调用可不可逆地锁定策略布尔开关_frozen置位后add_constraint()、set_agent_context()、update_agent_context()、add_conditional_permission()等变更方法都会抛出RuntimeError底层可变字典会被替换为MappingProxyType内部set→frozenset、list→tuple即使绕过方法直接操作属性也会抛TypeError所有被拦截的变更尝试会记录进mutation_log含操作名、时间戳、blocked: True可通过mutation_log属性读取形成攻击取证线索。这正对应Agent 试图在运行期削弱自身策略的自修改攻击向量是零信任治理闭环的关键一环。十四、测试佐证策略行为的可验证性仓库中已有覆盖策略行为的测试用例可作为配置正确性的参照test_constraint_graph.py验证默认拒绝test_deny_by_default、精确匹配放行、通配 agent 模式、优先级排序、条件必须匹配test_conditions_must_match等约束图语义test_control_plane_fail_closed.py验证未配置策略引擎时 syscall 被 fail-closed 拦截test_kernel_interception.py 与 test_kernel_space_integration.py覆盖工具调用拦截与KernelSpace集成路径。相关文档Agent OS 安全规范.agents/security.mdYAML 格式内核内部机制策略如何被强制Agent-OS 快速上手Agent-OS 文档索引PolicyEngine 源码实现【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

dlt 自学课程指南:从零基础到高级数据工程师的两阶段实战路线 2026/9/17 15:18:44

dlt 自学课程指南:从零基础到高级数据工程师的两阶段实战路线

dlt 自学课程指南:从零基础到高级数据工程师的两阶段实战路线 【免费下载链接】dlt data load tool (dlt) is an open source Python library that makes data loading easy 🛠️ 项目地址: https://gitcode.com/GitHub_Trending/dl/dlt dlt&…

阅读更多 →
GEO实操指南:如何让豆包在AI回答中优先引用你的内容 2026/9/17 15:18:44

GEO实操指南:如何让豆包在AI回答中优先引用你的内容

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
数据驱动的初三化学总复习教案:从JSON配置到Word自动生成 2026/9/17 15:18:44

数据驱动的初三化学总复习教案:从JSON配置到Word自动生成

简介:在教学资源数字化背景下,数据驱动的复习备课成为提升效率与精准度的重要方法。将复习内容按知识模块结构化,利用JSON配置文件管理模块权重、考点与薄弱点,再通过Python脚本与python-docx自动生成Word教案,形成“诊…

阅读更多 →
GPU加速数字信道化:实时频谱监测的CUDA工程实践 2026/9/17 15:18:44

GPU加速数字信道化:实时频谱监测的CUDA工程实践

简介:本资源是一份面向通信工程、信号处理领域高校师生及工程师的专业技术文档,聚焦GPU加速的数字信道化设计这一前沿课题,解决传统硬件在多信道并发处理与高吞吐量场景下的性能瓶颈问题。文档系统阐述多相滤波器组原理、50%重叠子信道设计、…

阅读更多 →
K8S核心三件套:Pod、Deployment、Service与Spring AI部署实战 2026/9/17 15:18:44

K8S核心三件套:Pod、Deployment、Service与Spring AI部署实战

1. 先别急着敲命令,搞懂 K8S 到底在解决什么聊 K8S 之前,我想先吐槽一个特别常见的现象:网上铺天盖地的部署教程,一上来就让你kubectl create deployment,结果你照抄跑通了,但 Pod 换个 IP 服务就断&#x…

阅读更多 →
LDO设计原理与关键技术:从线性稳压到系统级电源治理 2026/9/17 15:15:44

LDO设计原理与关键技术:从线性稳压到系统级电源治理

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞