使用说明
DelegateOS
代理网络的授权和责任范围。
DelegateOS是一种中间件,它为多代理系统提供了它们所缺少的东西:具有单调衰减的加密委托令牌、基于合约的任务验证和可传递的责任链。当代理A委托给代理B,代理B委托给代理C时,DelegateOS确保该链中的每个链接都具有范围权限、可验证的完成和可撤销的信任边界。
为什么
今天的每个代理框架——CrewAI、AutoGen、LangGraph、OpenClaw——都假设所有代理都是可信的,并且位于同一位置。没有办法说“这个代理可以搜索网络,但不能读取我的文件”或“这个委托链最多只能花费2美元” 谷歌DeepMind代表团文件 (2026年2月)明确指出了这一差距:MCP处理工具访问,A2A处理代理通信,但 没有人处理他们之间的信任和责任层.
DelegateOS填补了这一空白。
关键概念
- 委托能力令牌(DCT) --Ed25519签名JSON令牌编码作用域权限。能力、预算、到期时间、链深度——所有这些都是加密执行的。
- 单调衰减 --当你委托下游时,你只能缩小范围,永远不能扩大。子代理得到的≤你的能力,≤你的预算,≤你时间。
- 合同首次验证 --每个任务都有一个合约,指定“完成”的含义:JSON模式验证、确定性检查、复合验证。没有歧义。
- 认证链 --工作已完成并验证的加密证明,形成从叶子代理到根委托者的可审计链。
- 撤销 --在飞行途中撤销任何代表团。单块或级联——由您决定。
快速开始
npm install delegate-os
import { generateKeypair } from 'delegate-os/core/crypto';
import { createDCT, attenuateDCT, verifyDCT } from 'delegate-os/core/dct';
// 1. Create identities
const alice = generateKeypair();
const bob = generateKeypair();
// 2. Alice creates a root DCT for Bob
const dct = createDCT({
issuer: alice,
delegatee: bob.principal,
capabilities: [
{ namespace: 'web', action: 'search', resource: '*' },
{ namespace: 'docs', action: 'read', resource: '/project/**' },
],
contractId: 'ct_review_001',
delegationId: 'del_001',
parentDelegationId: 'del_000000000000',
chainDepth: 0,
maxChainDepth: 3,
maxBudgetMicrocents: 500_000, // $5.00
expiresAt: new Date(Date.now() + 3600_000).toISOString(), // 1 hour
});
// 3. Bob attenuates for a sub-agent (narrower scope)
const carol = generateKeypair();
const narrowDCT = attenuateDCT({
token: dct,
attenuator: bob,
delegatee: carol.principal,
delegationId: 'del_002',
contractId: 'ct_review_001',
allowedCapabilities: [
{ namespace: 'web', action: 'search', resource: 'arxiv.org/**' },
],
maxBudgetMicrocents: 100_000, // $1.00
maxChainDepth: 1,
});
// 4. Verify the token
const result = verifyDCT(narrowDCT, {
resource: 'arxiv.org/abs/2602.11865',
namespace: 'web',
operation: 'search',
now: new Date().toISOString(),
spentMicrocents: 0,
rootPublicKey: alice.principal.id,
revocationIds: [],
});
if (result.ok) {
console.log('Authorized:', result.value.capabilities);
console.log('Budget remaining:', result.value.remainingBudgetMicrocents);
} else {
console.log('Denied:', result.error.type);
}
看 入门指南 查看完整教程。看 API 参考 对于所有功能。
MCP集成
DelegateOS附带了一个MCP中间件插件,用于拦截 tools/call 透明地请求和执行DCT权限:
import { createMCPPlugin } from 'delegate-os/mcp/plugin';
import { InMemoryRevocationList } from 'delegate-os/core/revocation';
const plugin = createMCPPlugin({
toolCapabilities: {
web_search: { namespace: 'web', action: 'search' },
read_file: { namespace: 'docs', action: 'read',
resourceExtractor: (args) => args.path as string },
},
trustedRoots: [orchestratorPublicKey],
revocations: new InMemoryRevocationList(),
budgetTracker: { getSpent: () => 0, recordSpend: () => {} },
});
// Intercept incoming MCP request
const result = await plugin.handleRequest(mcpRequest);
插件过滤器 tools/list 仅显示DCT授予访问权限的工具,条带 _delegateos 并跟踪每个委托的花费。
看 API参考资料-MCP插件 了解全部细节。
演示
运行PR审查委托演示——编排器将代码审查委托给3名专家(安全、ExpressRoute、数据库),每位专家都有衰减令牌:
npx tsx src/demo/scenario.ts
演示:委托链、证明签名、令牌衰减强制、流中撤销和过期令牌拒绝。
用例
用例1:带工具护栏的个人AI助手
脚本: 你正在构建一个个人人工智能助理,可以搜索网络、阅读文档和发送电子邮件。您希望它将研究任务委托给更便宜、更快的模型,但该子代理永远无法发送电子邮件或读取您的私人文件。
演员: 您(用户)、您的主要助理(GPT-4级)、研究子代理(较小型号)
import {
generateKeypair, createDCT, attenuateDCT, verifyDCT,
createMCPPlugin, InMemoryRevocationList
} from 'delegate-os';
// Your assistant and its sub-agent each get an identity
const assistant = generateKeypair();
const researcher = generateKeypair();
// You (the root authority) grant your assistant broad capabilities
const you = generateKeypair();
const assistantToken = createDCT({
issuer: you,
delegatee: assistant.principal,
capabilities: [
{ namespace: 'web', action: 'search', resource: '*' },
{ namespace: 'docs', action: 'read', resource: '/home/me/**' },
{ namespace: 'email', action: 'send', resource: '*' },
],
contractId: 'ct_daily_tasks',
delegationId: 'del_001',
parentDelegationId: 'root',
chainDepth: 0,
maxChainDepth: 2,
maxBudgetMicrocents: 1_000_000, // $10
expiresAt: new Date(Date.now() + 86400_000).toISOString(), // 24 hours
});
// Your assistant delegates research to a sub-agent — but ONLY web search
// The sub-agent physically cannot access docs or email, even if it tries
const researchToken = attenuateDCT({
token: assistantToken,
attenuator: assistant,
delegatee: researcher.principal,
delegationId: 'del_002',
contractId: 'ct_daily_tasks',
allowedCapabilities: [
{ namespace: 'web', action: 'search', resource: '*.edu/**' }, // only .edu sites
],
maxBudgetMicrocents: 50_000, // $0.50 — tight budget
expiresAt: new Date(Date.now() + 600_000).toISOString(), // 10 minutes
});
// When the research agent tries to call a tool, DelegateOS checks the token
const check = verifyDCT(researchToken, {
resource: 'arxiv.org/search',
namespace: 'web',
operation: 'search',
now: new Date().toISOString(),
spentMicrocents: 0,
rootPublicKey: you.principal.id,
});
// ✅ Allowed — arxiv.org matches *.edu/** pattern
const emailCheck = verifyDCT(researchToken, {
resource: 'boss@company.com',
namespace: 'email',
operation: 'send',
now: new Date().toISOString(),
spentMicrocents: 0,
rootPublicKey: you.principal.id,
});
// ❌ Denied — email capability was never delegated
您将获得: 您的子代理可以在其范围内搜索网络。它无法读取您的文件、发送电子邮件、超支预算或超过10分钟的窗口。不需要信任——它是加密执行的。
用例2:开发团队代码审查管道
脚本: 你是一名技术主管,正在构建一个自动化的公关审查系统。您希望编排代理将评论外包给专业代理(安全、性能、风格),每个代理只能访问他们需要的存储库和工具。当专家完成时,你需要他们审查内容的加密证明。
演员: CI/CD系统(根)、编排代理、3个专业代理
import {
generateKeypair, createDCT, attenuateDCT,
createContract, signContract, createAttestation, signAttestation,
DelegationChainStore, TrustEngine,
} from 'delegate-os';
// Identities
const ciSystem = generateKeypair();
const orchestrator = generateKeypair();
const securityAgent = generateKeypair();
const perfAgent = generateKeypair();
const styleAgent = generateKeypair();
// CI system creates a root token for the orchestrator
const rootToken = createDCT({
issuer: ciSystem,
delegatee: orchestrator.principal,
capabilities: [
{ namespace: 'git', action: 'read', resource: 'myorg/myrepo/**' },
{ namespace: 'git', action: 'comment', resource: 'myorg/myrepo/pulls/*' },
{ namespace: 'analysis', action: 'run', resource: '*' },
],
contractId: 'ct_pr_review_789',
delegationId: 'del_root',
parentDelegationId: 'root',
chainDepth: 0,
maxChainDepth: 2,
maxBudgetMicrocents: 2_000_000, // $20 total for all reviews
expiresAt: new Date(Date.now() + 1800_000).toISOString(), // 30 minutes
});
// Orchestrator creates a contract for the security review
const securityContract = createContract({
issuer: orchestrator.principal.id,
task: {
title: 'Security Review — PR #789',
description: 'Review for SQL injection, XSS, auth bypass, secrets in code',
inputs: { prNumber: 789, repo: 'myorg/myrepo', diffUrl: '...' },
outputSchema: {
type: 'object',
required: ['vulnerabilities', 'severity', 'recommendation'],
properties: {
vulnerabilities: { type: 'array' },
severity: { enum: ['none', 'low', 'medium', 'high', 'critical'] },
recommendation: { enum: ['approve', 'request_changes', 'block'] },
},
},
},
verification: { method: 'schema_match' },
constraints: {
maxBudgetMicrocents: 500_000,
deadline: new Date(Date.now() + 600_000).toISOString(),
maxChainDepth: 1,
requiredCapabilities: ['git:read'],
},
}, orchestrator);
// Attenuated token for the security agent — read-only, no commenting
const securityToken = attenuateDCT({
token: rootToken,
attenuator: orchestrator,
delegatee: securityAgent.principal,
delegationId: 'del_security',
contractId: securityContract.id,
allowedCapabilities: [
{ namespace: 'git', action: 'read', resource: 'myorg/myrepo/**' },
{ namespace: 'analysis', action: 'run', resource: 'security/*' },
],
maxBudgetMicrocents: 500_000,
});
// ... (similar for perfAgent, styleAgent with their own scoped tokens)
// When security agent finishes, it creates a signed attestation
const attestation = createAttestation({
contractId: securityContract.id,
delegationId: 'del_security',
principal: securityAgent.principal.id,
type: 'completion',
result: {
success: true,
output: {
vulnerabilities: [{ type: 'XSS', file: 'src/input.ts', line: 42 }],
severity: 'medium',
recommendation: 'request_changes',
},
costMicrocents: 150_000,
durationMs: 45_000,
verificationOutcome: { method: 'schema_match', passed: true },
},
}, securityAgent);
// Orchestrator can verify: the attestation is signed, output matches schema,
// and the agent had a valid token when it produced the result.
// The trust engine records the outcome for future delegation decisions.
const trust = new TrustEngine();
trust.recordOutcome(securityAgent.principal.id, attestation);
console.log(trust.getScore(securityAgent.principal.id));
// → { composite: 0.85, reliability: 1.0, quality: 0.7, speed: 0.9 }
您将获得: 每位专家只能获得所需的信息。编排器不能超过CI系统的预算。每次审查都会产生一份签名的、可验证的证明。信任评分会随着时间的推移而提高,因此可靠的代理会首先获得委托。
用例3:多租户代理市场
脚本: 您正在构建一个平台,企业可以在其中发布人工智能代理作为服务(数据分析、法律研究、翻译)。当客户提交作业时,您的平台需要:发现有能力的代理,协商委托条款,将复杂的作业拆分为子任务,将其发送给专家,跟踪支出,并提供可验证的完成证明——同时确保没有代理可以访问另一个客户的数据。
演员: 平台(根权限)、客户、协调器、来自不同供应商的3个以上市场代理
import {
generateKeypair, createDCT, attenuateDCT,
createContract, signContract,
AgentRegistry, DelegationBroker, TrustEngine,
DelegationChainStore, DecompositionEngine, SequentialStrategy,
VerificationEngine, MockLLMJudge,
MemoryStorageAdapter,
} from 'delegate-os';
// === Setup: Platform registers available agents ===
const platform = generateKeypair();
const registry = new AgentRegistry();
const trust = new TrustEngine();
const storage = new MemoryStorageAdapter();
// Vendor agents register their Agent Cards
const dataAnalyst = generateKeypair();
registry.register({
id: 'agent_data_analyst',
name: 'DataCrunch Pro',
description: 'Statistical analysis, visualization, ML model evaluation',
principal: dataAnalyst.principal.id,
capabilities: [
{ namespace: 'data', action: 'analyze', resource: '*' },
{ namespace: 'data', action: 'visualize', resource: '*' },
],
delegationPolicy: {
acceptsDelegation: true,
maxChainDepth: 2,
requiredTrustScore: 0.3,
allowedNamespaces: ['data'],
costPerTaskMicrocents: 200_000, // $2.00 per task
},
signature: '...', // self-signed with dataAnalyst's key
metadata: { vendor: 'DataCrunch Inc', sla: '99.9%' },
});
// ... register translator, legal researcher, etc.
// === Customer submits a complex job ===
const customer = generateKeypair();
// Platform creates the master contract
const masterContract = createContract({
issuer: platform.principal.id,
task: {
title: 'Q4 Market Analysis Report',
description: 'Analyze Q4 sales data, translate executive summary to 3 languages, check for regulatory compliance',
inputs: {
dataset: 'customer_12345/q4_sales.csv', // customer-scoped!
languages: ['es', 'de', 'ja'],
regulations: ['GDPR', 'CCPA'],
},
outputSchema: {
type: 'object',
required: ['analysis', 'translations', 'compliance'],
},
},
verification: {
method: 'composite',
steps: [
{ method: 'schema_match' },
{ method: 'llm_judge', prompt: 'Rate the analysis quality', criteria: ['accuracy', 'depth', 'actionability'], passingScore: 0.7 },
],
mode: 'all_pass',
},
constraints: {
maxBudgetMicrocents: 5_000_000, // $50 total
deadline: new Date(Date.now() + 7200_000).toISOString(), // 2 hours
maxChainDepth: 3,
requiredCapabilities: ['data:analyze', 'translate:text', 'legal:review'],
},
}, platform);
// === Decompose into sub-tasks ===
const decomposition = new DecompositionEngine();
const plan = decomposition.decompose(masterContract, new SequentialStrategy());
// → Sub-task 1: Data analysis ($20 budget, 45min)
// → Sub-task 2: Translation ($15 budget, 30min, depends on #1)
// → Sub-task 3: Compliance review ($15 budget, 30min, depends on #1)
// === Broker discovers and delegates to best agents ===
const broker = new DelegationBroker(registry, trust);
const chain = new DelegationChainStore();
for (const subtask of plan.subtasks) {
// Find the best agent — considers capabilities, trust score, cost
const agent = broker.findAgent(subtask.contract, chain);
if (agent.ok) {
// Create a scoped DCT — this agent can ONLY access this customer's data
const delegation = broker.proposeDelegation(
platform,
agent.value,
subtask.contract,
);
// The DCT ensures:
// - Data analyst can read customer_12345/* but NOT customer_67890/*
// - Translator gets the analysis output but NOT the raw dataset
// - No agent can exceed its budget fraction
// - Everything expires when the master deadline hits
// - Any delegation can be revoked mid-flight if something goes wrong
await storage.saveDelegation(delegation.value.delegation);
}
}
// === Verify results with composite verification ===
const verifier = new VerificationEngine();
verifier.registerLLMJudge(new MockLLMJudge({ defaultScore: 0.85 }));
const analysisOutput = { /* ... agent's output ... */ };
const verification = await verifier.verify(analysisOutput, masterContract.verification);
// → { passed: true, score: 0.85, details: 'Schema valid. LLM judge: 0.85 (accuracy: 0.9, depth: 0.8, actionability: 0.85)' }
// Trust scores update based on outcomes — reliable agents rise to the top
trust.recordOutcome(dataAnalyst.principal.id, attestation);
您将获得: 完全的租户隔离以加密方式强制执行,而不仅仅是通过访问控制列表。自动代理发现和委派。复杂的工作被分解并交给专家。整个链条的预算跟踪。复合验证(模式+LLM判断)。信任评分会随着时间的推移而提高,因此最好的代理可以获得更多的工作。每一步都会产生一个签名的审计证明。
为您的架构选择DelegateOS
| 你需要。.. | 没有DelegateOS | 有DelegateOS |
|---|---|---|
| 子代理只能使用某些工具 | 荣誉系统/提示工程 | 加密强制功能 |
| 整个委托链的支出上限 | 手动跟踪,易于超过 | 每次验证都强制执行预算 |
| 证明工作已正确完成 | 相信代理的话 | 带模式验证的签名证明 |
| 在任务中期撤销行为不端的代理 | 终止进程并希望 | 撤销DCT——所有下游立即无效 |
| 为作业找到最佳代理 | 硬编码路由 | 代理注册表+信任评分+能力匹配 |
| 将复杂的工作分散给专家 | 手动编排 | 通过预算/截止日期传播进行合同分解 |
| 谁做了什么的审计跟踪 | 分散的日志 | 从根到叶子的加密认证链 |
建筑
看 docs/architecture.md 对于完整的架构文档,包括令牌格式、验证算法、安全模型和包结构。
看 docs/protocol-spec.md 用于有线协议规范。
特性
核心(v0.1)
- DCT发动机 --创建、衰减、验证Ed25519签名JSON令牌
- 合同制度 --具有模式、确定性和复合验证的任务契约
- 认证发动机 --已签署的完成和授权验证证明
- 撤销 --具有级联支持的内存吊销列表
- 代表团连锁店 --具有完整性验证的内存链跟踪
- MCP中间件 —
tools/call拦截、DCT执行、审计日志记录 - 演示 --完整的PR审查委托场景
v0.2阶段A
- 信任/声誉引擎 --指数衰减、冷启动处理、可靠性/质量/速度分解的综合信任评分
- 合同分解 --具有顺序和并行策略的递归任务拆分、依赖性跟踪、预算/截止日期/能力验证
- 饼干代币后端 --纯TypeScript数据日志引擎,具有前向链评估功能,兼容Biscuit令牌格式,可从SJT选择升级
- 持久化存储 --摘要
StorageAdapter与内存和SQLite接口(better-sqlite3)实施方案
v0.2阶段B
- 验证引擎 --统一
VerificationEngine所有5种验证方法的类调度:schema_match,deterministic_check,composite,llm_judge,human_review.可插拔LLMJudgeAdapter和HumanReviewAdapter与模拟实现接口进行测试 - A2A协议 --带有Ed25519签名卡的代理卡自我描述身份,
AgentRegistry为了发现/解析,DelegationBroker用于基于能力、信任分数和成本的自动代理选择和委托建议 - 分布式撤销 --异步
RevocationStore与...对接LocalRevocationStore(现有包装)和DistributedRevocationStore具有八卦风格的同步、反熵、重复数据删除和签名验证。v0.2的过程模拟
v0.2阶段C
- HTTP+SSE传输 —
MCPHttpServer通过HTTP暴露具有SSE流的MCP中间件,MCPHttpClient通过重试/回退,SSEWriter/SSEReader公用事业。路线:/mcp/message,/mcp/stream,/mcp/events/:sessionId,/health,/agents - 集成测试 --48个端到端测试,涵盖了整个委托生命周期(3级链、预算级联、能力衰减、中链撤销)、HTTP传输、信任+验证以及跨两个适配器的存储往返
v0.2完成 --257个测试,0个TypeScript错误。
v0.3——生产准备就绪
- 结构化日志记录 —
Logger与...对接ConsoleLogger输出JSON结构化日志(时间戳、级别、模块、消息、上下文)。createLogger(module)工厂,LogLevel枚举(调试/信息/警告/错误/静音),运行时setGlobalLogLevel(),每个记录器级别超控 - 速率限制 --代币桶
RateLimiter通过按密钥跟踪,RateLimitMiddleware具有基于路由的配置、通配符模式匹配、可配置的密钥提取(IP/主体/组合)、自动清理过时桶、429和重试后 - 度量与可观察性 —
MetricsCollector使用计数器/量规/直方图基元、基于标签的维度、基于标签和基于标签的度量,MetricsAdapter外部系统接口(Prometheus、StatsD)、快照导出、,globalMetrics单例 - 令牌版本控制和迁移 —
TokenVersion类型、向后兼容版本字段(缺失=v1.0),isCompatible()检查,migrateToken()具有已注册的迁移功能,迁移注册表具有registerMigration() - 断路器 —
CircuitBreaker具有CLOSED/OPEN/HALF_OPEN状态、可配置的故障阈值和重置超时、状态更改回调、,CircuitOpenError,forceReset()用于手动恢复 - 费率限制基础设施 --路由级速率限制,精确匹配和前缀匹配,每个键单独设置存储桶,定期清理过时条目
v0.3完成 --在27个文件中进行374次测试,0个TypeScript错误。
许可证
麻省理工学院