十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Agent Governance Toolkit Framework Adapter Contract 1.0:HostSession 生命周期治理与框架适配器集成规范

Agent Governance Toolkit Framework Adapter Contract 1.0:HostSession 生命周期治理与框架适配器集成规范 Agent Governance Toolkit Framework Adapter Contract 1.0HostSession 生命周期治理与框架适配器集成规范【免费下载链接】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 Agent Governance Toolkit下文简称 AGT中的 Framework Adapter Contract 1.0 规范。该规范定义了框架适配器如何将 LangChain、OpenAI Agents、AutoGen 等原生 Agent 运行时的生命周期事件接入统一的治理管线适配器通过HostSession承载会话级状态、在副作用或信息披露之前应用策略变换、向宿主透出原生PolicyEvaluation错误同时把会话计数器留在无状态运行时之外。读完本文你将掌握适配器的干预点声明、动作解析、身份绑定、审计追踪与失败关闭fail-closed的完整实现路径并能基于 agent-governance-typescript 的GenericFrameworkAdapter源码落地一个可运行的治理适配器。一、契约核心适配器、运行时与 HostSession 的边界Framework Adapter Contract 1.0docs/specs/FRAMEWORK-ADAPTER-CONTRACT-1.0.md用一段精炼的语义定义了三方职责边界框架适配器Framework Adapter接受一个原生运行时native runtime把框架自身的生命周期事件翻译成治理调用HostSession承载单个会话的SnapshotBuilder、计数器与原生干预点调用是所有会话级状态的家治理运行时AgentControl无会话状态、可共享拥有审批解析器approval resolver与超时行为。契约原文强调五个强制点适配器必须声明所需的干预点required intervention points并在执行前完成契约校验适配器在副作用或信息披露之前应用变换transform适配器向宿主透出原生PolicyEvaluation错误而非私有的 v4 结果类型会话计数器存放在无状态的运行时之外即HostSession内审批解析approval resolution属于运行时的职责适配器不得携带竞争性的解析器配置。这五条与 v4 策略语言移除计划docs/v4-removal.md中的 Phase 2 提取边界一一对应HostSession现在独占一个会话的SnapshotBuilder、计数器与原生干预点调用它会在执行前预留工具调用预算因此被拒绝和失败的尝试同样消耗预算并在post_model_call之后记录模型 token只对计数器变更做串行化AgentControl保持无会话且可在回调线程安全的前提下被多个宿主共享。二、为什么需要适配器契约从 v4 桥到原生 HostSession理解这份契约的背景是 v4 策略语言的移除。AGT 正在移除旧的 v4 意图式策略语言使 ACSAgent Control Specificationv5策略层成为工具箱中唯一的策略契约。在移除计划docs/v4-removal.md的符号清单中v4 的PolicyInterceptor、ExecutionContext与AdapterRuntimeBridge全部由HostSessionoverAgentControl取代v4 符号原位置替代品GovernancePolicy、PatternTypeagent_os/integrations/base.pyACS manifest 加AgentControlPolicyInterceptor、ExecutionContextagent_os/integrations/base.pyHostSessionoverAgentControlget_runtime_bridge、AdapterRuntimeBridgeagent_os/integrations/_v5_runtime_bridge.pyHostSessionPolicyDocument、CedarBackendagent_os/policies/ACSpolicies.type: cedar与原生 manifest移除了桥接层之后框架适配器只依赖两个原生契约原生 manifest以AgentControl.from_path(str(...))为规范运行时构造函数携带父目录作为 provenance相对 bundle、data、prompt、Cedar 与extends引用都相对 manifest 解析而不是相对当前工作目录原生干预点结果AgentControl.evaluate_intervention_point(...)返回不可变的InterventionPointResult其verdict携带decision、reason、message、transform、evidence与result_labels审计信封使用agt.policy_evaluation.v1schema。ACSpolicy-engine/spec/README.md定义了八个干预点agent_startup、input、pre_model_call、post_model_call、pre_tool_call、post_tool_call、output、agent_shutdown。每个干预点条目通过policy_target选择值、可请求annotations并通过policy.id引用顶层policies条目。适配器契约正是在这八个点上挂接治理逻辑其中pre_tool_call是工具调用类动作的默认治理关口。适配器强制契约速览移除计划中以表格形式给出了适配器强制契约Adapter enforcement contract这是 Framework Adapter Contract 的运行时化表述关注点原生契约必需干预点每个适配器声明它们执行前校验运行时契约缺失必需干预点是构造错误绝不是运行时允许的回退工具目录manifest要求静态toolshost_dynamic由宿主同步optional不施加目录要求变换每个适配器声明可应用变换的干预点共享的适配器会话在转发载荷前应用变换审批AgentControl拥有解析器与超时行为拿到运行时的适配器不得再接受竞争性的解析器配置预算尝试的调用消耗工具调用预算包括被拒绝与失败的尝试会话计数器位于适配器会话而非AgentControl运行时共享当宿主分发器与审批回调线程安全时一个运行时可被共享会话快照与计数器绝不存放在运行时上失败方向非法 manifest、缺失必需绑定、分发器错误与审批错误一律失败关闭原生路径不会把未知干预点或工具重写为允许三、源码级落地TypeScript 版 GenericFrameworkAdapter框架适配器契约在 agent-governance-typescript 中由 src/framework-adapter.ts 完整实现并从 src/index.ts 导出GenericFrameworkAdapter与FrameworkInvocationHandle同时导出FrameworkInvocation、FrameworkInvocationOutcome、GenericFrameworkAdapterOptions等类型。这一实现与契约五条强制点一一对应。3.1 核心类型定义调用方与适配器交互的数据结构如下src/framework-adapter.tsexport interface FrameworkInvocation { name: string; kind?: TraceSpanKind; // 如 tool_call | llm_inference | internal action?: string; // 显式动作名优先于自动解析 /** 可选诊断身份提示若提供则必须匹配绑定的客户端身份。 */ agentId?: string; input?: Recordstring, unknown; attributes?: Recordstring, unknown; trustedSkillMetadata?: TrustedSkillMetadataSource; } export interface FrameworkInvocationOutcomeTOutput unknown { output?: TOutput; error?: string; status?: TraceSpanStatus; costUsd?: number; } export interface FrameworkAdapterResultTOutput unknown { allowed: boolean; reason: string; action: string; invocation: FrameworkInvocation; governanceResult: GovernanceResult; output?: TOutput; error?: string; trace: ExecutionTrace; } export interface GenericFrameworkAdapterOptions { metrics?: GovernanceMetrics; actionPrefix?: string; // 默认 framework actionResolver?: (invocation: FrameworkInvocation) string; }其中FrameworkAdapterResult是适配器运行的最终产物allowed与reason构成决策可解释性governanceResult内含decision、trustScore、auditEntry、executionTime与lifecycleStatetrace是完整的执行追踪ExecutionTrace。3.2 动作解析显式优先前缀兜底GenericFrameworkAdapter构造时接受actionPrefix默认framework与可选的actionResolver。动作解析逻辑src/framework-adapter.ts遵循三级优先级invocation.action显式指定直接使用否则调用actionResolver(invocation)用于框架定制命名如 LangChain 的langchain.invoke.${name}兜底拼接${actionPrefix}.${invocation.kind ?? internal}.${invocation.name}即framework.tool_call.search这类默认动作名。测试 tests/framework-adapter.test.ts 验证了自定义解析路径策略规则langchain.invoke.chat_model配effect: allowactionResolver返回langchain.invoke.${invocation.name}最终result.action为langchain.invoke.chat_model。这意味着未来任何框架适配器LangChain、LlamaIndex、Semantic Kernel 等都可以通过actionResolver建立自己的命名空间而不必改动治理管线。3.3 beginInvocation治理前置与身份绑定beginInvocationsrc/framework-adapter.ts是治理决策发生的地方它完成以下步骤解析动作按 3.2 的三级优先级得到治理动作名身份规范化以绑定客户端的 DIDthis.client.identity.did作为规范身份覆盖调用方的agentId空字符串视为未断言身份一致性校验若调用方断言的agentId与绑定身份不一致直接生成拒绝结果记录Caller-asserted agentId ... does not match bound client identity ...的审计条目并降低信任分rejectIdentityMismatchsrc/framework-adapter.ts开启追踪 span以TraceCapture记录动作名、类型、输入与属性执行治理this.client.executeWithGovernance(action, input, skillAuditMetadata)走完整的治理管线——环强制ring enforcement、策略求值、信任分读取、审计日志src/client.ts记录指标策略决策、信任分、审计条目长度决策分支allowed为false时立即终结 span状态error、完成追踪并finalizeDenied处理器永远不会执行。executeWithGovernance的底层管线src/client.ts体现了完整的治理语义// 简化自 AgentMeshClient.executeWithGovernance this.ringEnforcer.enforce(action); // 1. 执行环校验Ring2/Ring3 越权即 deny const decision this.policy.evaluate(action, params); // 2. 策略求值 const trustScore this.trust.getTrustScore(this.identity.did); const auditEntry this.audit.log({ agentId, action, decision, skillAuditMetadata }); if (decision allow) this.trust.recordSuccess(agentId); else if (decision deny) this.trust.recordFailure(agentId);环违反RingBreachError会触发隔离quarantine甚至 kill-switch同时记录 deny 审计并降低信任分最后以ringViolation字段携带违规详情返回。3.4 FrameworkInvocationHandle预检与完成的两阶段生命周期beginInvocation返回FrameworkInvocationHandleTOutputsrc/framework-adapter.ts这是一个两阶段句柄专门为框架特定的包装器设计预检阶段句柄携带allowed、reason、governanceResult与traceId框架可以据此决定是否继续完成阶段complete(outcome)终结 span依据error或status判定ok | error对tool_call类型的调用记录耗时metrics.recordToolCall归一化输出对象原样保留标量包装为{ value }完成追踪并返回FrameworkAdapterResult保护机制未完成即调用toResult()抛错Invocation has not been completed重复complete抛错Invocation already completed预检即被拒绝的调用无 capture/span抛错Invocation was already finalized during preflight。3.5 run一站式治理执行入口runsrc/framework-adapter.ts把两阶段封装成一步式 API是最常用的入口async runTOutput( invocation: FrameworkInvocation, handler: () PromiseTOutput | TOutput, ): PromiseFrameworkAdapterResultTOutput { const handle await this.beginInvocationTOutput(invocation); if (!handle.allowed) { return handle.toResult(); // 拒绝时处理器绝不执行 } try { const output await handler(); // 允许时执行真实副作用 return handle.complete({ output }); } catch (error) { return handle.complete({ error: error instanceof Error ? error.message : Unknown framework handler error, status: error, }); } }注意handle.allowed false时handler完全不执行——这正是契约中在副作用或信息披露之前应用变换/决策的体现也是测试 tests/framework-adapter.test.ts 用jest.fn验证的失败关闭行为策略规则{ action: *, effect: deny }下处理器从未被调用result.trace.success为false。四、配置与使用如何实例化一个受治理的适配器4.1 最小可用示例参考测试 tests/framework-adapter.test.ts一个最小可用的治理适配器如下import { AgentMeshClient } from ./client; import { GenericFrameworkAdapter } from ./framework-adapter; import { GovernanceMetrics } from ./metrics; // 1. 创建带策略的治理客户端 const client AgentMeshClient.create(adapter-agent, { policyRules: [ { action: framework.tool_call.search, effect: allow }, ], }); // 2. 可选开启指标采集 const metrics new GovernanceMetrics({ enabled: true }); // 3. 构造适配器 const adapter new GenericFrameworkAdapter(client, { metrics }); // 4. 治理式执行 const result await adapter.run( { name: search, kind: tool_call, input: { query: status }, }, async () ({ items: 3 }), ); console.log(result.allowed); // true console.log(result.output); // { items: 3 } console.log(result.trace.spans.length); // 1 console.log(metrics.getSnapshot().counters[trace.captures]); // 14.2 策略规则形态AgentMeshClient.create的policyRules是动作到效应的映射常用的三种形态规则示例语义{ action: framework.tool_call.search, effect: allow }精确放行单个动作{ action: *, effect: deny }默认拒绝一切失败关闭的基线{ action: langchain.invoke.chat_model, effect: allow }配合actionResolver的框架命名空间结合执行环配置还可以为动作指定所需特权环见测试 tests/framework-adapter.test.tsconst client AgentMeshClient.create(adapter-agent, { policyRules: [{ action: framework.tool_call.lookup, effect: allow }], execution: { agentRing: ExecutionRing.Ring2, actionRings: { framework.tool_call.lookup: ExecutionRing.Ring2, }, }, });4.3 技能审计元数据与上下文哈希契约要求适配器在披露前做变换而审计层面则要求可追溯。FrameworkInvocation.trustedSkillMetadata携带可信的技能来源skillName、skillOriginbuildSkillAuditMetadatasrc/framework-adapter.ts会对调用输入做稳定序列化后 SHA-256 哈希contextHashBefore有可信元数据或上下文哈希时才构造SkillAuditMetadata并标记provenanceSourceTrust: trusted哈希使用键排序的稳定序列化sortKeysJSON.stringify因此对象键顺序不影响哈希值——测试 tests/framework-adapter.test.ts 用{a:1,b:2}与{b:2,a:1}两种输入验证了哈希一致。这些元数据最终随审计条目写入governanceResult.auditEntry.skillAuditMetadata为事后取证提供调用前上下文指纹。4.4 身份绑定的失败关闭语义身份是零信任治理的第一道关。契约与实现共同确立以下规则agentId省略或为空字符串绑定到客户端 DID正常执行agentId与客户端 DID 一致正常执行测试 tests/framework-adapter.test.tsagentId与客户端 DID 不一致失败关闭——即使策略允许该动作也会生成deny决策、写入审计、降低信任分处理器绝不执行测试 tests/framework-adapter.test.ts 中did:agentmesh:spoofed:1234被拒绝。实现上beginInvocation在规范化时用canonicalAgentId覆盖invocation.agentId保证审计与追踪中的身份永远是绑定身份防止伪造身份混入证据链。五、失败方向与错误透出原生 PolicyEvaluation契约与移除计划共同强调非法 manifest、缺失必需绑定、分发器错误与审批错误一律失败关闭原生路径不会把未知干预点或工具重写为允许。对应的工程语义缺失必需干预点 构造错误适配器声明的必需干预点在运行时契约校验中缺失时直接构造失败而不是在运行时静默放行原生错误透出原生拒绝通过PolicyViolationError附带evaluation_result与agt.policy_evaluation.v1审计记录PolicyViolationError.from_evaluation_result(...)会生成稳定、脱敏的公开消息不把策略或用户内容复制进异常文本审批归属运行时AgentControl独占审批解析器与超时行为适配器可以省略approval_resolver或重复相同回调过渡期但传入不同回调会在构造时被拒绝预算失败也计费HostSession在执行前预留工具调用预算因此被拒绝与失败的尝试同样消耗预算防止通过反复试错绕过治理。TypeScript 侧对应的失败关闭体现在两处run在allowed false时跳过handlerbeginInvocation在身份不匹配或治理 deny 时通过finalizeDenied生成allowed: false的结果且拒绝路径的追踪success恒为false。六、生态中的适配器范围与演进路线Framework Adapter Contract 是跨语言、跨框架的。移除计划docs/v4-removal.md列出了 17 个桥接框架适配器在 Phase 3 全部切换到原生runtime参数与NativeAdapterRuntime/HostSessionA2A、Agent Shield、Anthropic、AutoGen、Bedrock、CrewAI、Gemini、Google ADK、Guardrails、LangChain、LlamaIndex、MAF、Mistral、OpenAI、PydanticAI、Semantic Kernel、Smolagents。它们不再通过AdapterRuntimeBridge或BridgeResult导入与求值唯一保留的桥接依赖只是过渡期的构造选择器。演进分六个阶段strangler 模式加一次原子性公开破坏性发布阶段内容0语义清点与 Python/Rust/TypeScript 的 CI 棘轮ratchet1定义原生 v5 结果、错误、审计、类型化 manifest 与适配器强制契约2从 v4 运行时桥中抽取 ACS 原生HostSession隔离并加固迁移翻译器317 个框架适配器按绿色纵向切片迁移并配套测试与示例4迁移非适配器消费方并删除运行时governance.yaml解析5重写 Rust 与 TypeScript 的 v4 表面并修复包构建6原子性移除全部桥接、v4 结果转换与再导出棘轮收紧为零贯穿全程的是scripts/check_v4_ratchet.py棘轮docs/v4-removal.md 中的命令python scripts/check_v4_ratchet.py # 对照基线做门禁 python scripts/check_v4_ratchet.py --report # 查看清单 python scripts/check_v4_ratchet.py --update-baseline # 真实削减后更新基线对于存量 v4 项目官方迁移路径是一次性执行agt migrate v4-to-v5见 docs/specs/AGENT-OS-POLICY-ENGINE-1.0.md运行时模块不再加载旧治理文件。七、结语契约的工程价值Framework Adapter Contract 1.0 的工程价值可以浓缩为三句话干预点声明前置适配器把我需要在哪里被治理变成显式的构造期契约杜绝静默放行状态与运行时分离计数器、快照、预算全在HostSessionAgentControl保持无状态可共享天然支持多宿主并发失败关闭是默认值身份不匹配、环越权、策略 deny、审批缺失、manifest 非法任何一环失败都阻止副作用发生且拒绝路径同样留下审计与追踪证据。对于要在 AGT 上接入新框架的开发者参考实现就是 agent-governance-typescript/src/framework-adapter.ts 与其配套测试 tests/framework-adapter.test.ts声明干预点、绑定身份、解析动作、调用run或两阶段的beginInvocation/complete即可把任意 Agent 框架纳入 AGT 的策略、信任、审计与追踪体系。【免费下载链接】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),仅供参考
返回列表