refactor(contracts,agent): single capability spec and agent run event definitions in contracts

B3: CapabilityDescriptor gains replay; CapabilitySpec + capabilitySpec(id) assemble
CAPABILITY_CATALOG + CAPABILITY_IO; drop CapabilityDefinition/CapabilityRisk. agent
registry registers contracts CapabilitySpec (kind/allowedKinds instead of its own
scope enum; approve also requires authorize). AgentRun port renamed AgentRunHandle.

B9: contracts AgentRunEvent/AgentRunEventBody/AgentRunEventRow/AgentUsageTotals with
row and SSE mapping helpers; agent onEvent receives AgentRunEvent, delivered serially
in seq order, firstSeq continues numbering across processes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-27 19:15:49 +08:00
1 parent 8f59bf3772
commit db5352eecd
18 files changed
+553 -293

No files matched your search

+31 -27
View File
@@ -8,9 +8,9 @@ Pi Agent 接入层:能力注册中心、`AgentRuntimePort` 及其 Pi 实现、
- 模型只能调用本次 `capabilities` 白名单里的能力。白名单有三层保护:
1. 注册层:只把白名单能力注册成 Pi 工具,其它工具名(例如 `bash`)由 harness 合成 unavailable 错误;
2. `before_tool` 钩子再校验一次,白名单外的调用一律 block,并产生 `tool_call_rejected` 事件;
3. 每次执行都走 `CapabilityRegistry.invoke`,依次做作用域、schema、授权、幂等键、输出 schema 和审计。
3. 每次执行都走 `CapabilityRegistry.invoke`,依次做能力类别上限(allowedKinds)、schema、授权、幂等键、输出 schema 和审计。
- **不提供** bash/进程执行、任意 SQL、任意文件读写、任意网络/HTTP 代理、读取 Cookie/Token、安装依赖或修改代码的工具。`NodeExecutionEnv` 只作为会话目录的 FileSystem 使用,它的 exec 不会暴露给模型。
- 授权只在服务端判定:`authorize` 回调查 automation_grant/approval。模型参数里写的"用户已同意"不起作用。没有注入 `authorize` 时,propose/execute 一律拒绝。
- 授权只在服务端判定:`authorize` 回调查 automation_grant/approval。模型参数里写的"用户已同意"不起作用。没有注入 `authorize` 时,propose/approve/execute 一律拒绝。
- 幂等键由服务端按操作语义生成(默认是 `id:v版本:sha256(规范化输入)`,可以注入自定义生成器),通过 `ctx.idempotencyKey` 交给 handler,不采用模型给的值。
- 工具的输入输出在进入模型上下文、事件和审计之前,都要经过 `redactForModel`(cookie/passkey/token/apiKey/authorization/私有下载 URL/URL 内嵌账号密码)处理。`apiKey` 只在请求时经 provider `auth.resolve` 交给 SDK。
- 子代理:`subagentsEnabled` 在 v0.1 中只做记录。SDK 本身不提供子代理,以后由 `agent.delegate` 能力实现,并继承父任务的授权与预算。
@@ -18,30 +18,24 @@ Pi Agent 接入层:能力注册中心、`AgentRuntimePort` 及其 Pi 实现、
## 新增一个能力
能力描述只在 `@umt/contracts` 定义(B3):`CapabilitySpec`(描述符字段 + 真实 zod schema)、`CapabilityKind`(read / preview / propose / approve / execute)、`RiskLevel`(low / medium / high)、`CapabilityReplay`(safe / never)。本包不再有自己的描述类型。
首批 14 个能力一律用 `capabilitySpec(id)` 取规格(元数据来自 `CAPABILITY_CATALOG`,schema 来自 `CAPABILITY_IO`),server 模块只写处理器:
```ts
registry.register(
{
id: "download.submit", // 域.动作;对 Pi 暴露为 download__submit
version: 1,
title: "提交下载",
description: "提交下载计划到下载器。成功只代表已提交,不代表已入库。", // 给模型看的中文说明
inputSchema: z.object({ planId: z.string() }),
outputSchema: z.object({ taskId: z.string(), status: z.literal("submitted") }),
scope: "execute", // read | preview | propose | execute
riskLevel: "medium", // low | medium | high | critical
idempotent: true,
supportsPreview: true,
replay: "never", // 有副作用的能力必须是 never;只读能力用 safe
},
async (input, ctx) => {
// ctx: actorId/taskId/scopeIds/signal + idempotencyKey + authorization
// 失败时抛 CapabilityError("precondition" | "not_found" | "conflict" | "unauthorized" | "budget", message)
return { taskId: await downloads.submit(input.planId, ctx.idempotencyKey!, ctx.signal), status: "submitted" };
},
);
import { capabilitySpec } from "@umt/contracts";
registry.register(capabilitySpec("download.submit"), async (input, ctx) => {
// input 已按 DownloadSubmitInput 校验;ctx: actorId/taskId/scopeIds/signal + idempotencyKey + authorization
// 失败时抛 CapabilityError("precondition" | "not_found" | "conflict" | "unauthorized" | "budget", message)
const task = await downloads.submit(input.planId, ctx.idempotencyKey!, ctx.signal);
return { taskId: task.id, planId: input.planId, downloadTask: null };
});
```
要点:输出只写业务需要的字段,因为 zod 会剥掉多余字段;不要把凭证放进输出;有副作用的 handler 要按 `idempotencyKey` 到操作账本去重。崩溃恢复时,`replay:"never"` 的工具会得到"结果未知",模型需要用查询类能力核对状态。
目录外的新能力:先在 contracts 的 `CAPABILITY_IDS` / `CAPABILITY_CATALOG` / `CAPABILITY_IO` 各加一项,再按上面注册。测试里可以手写 `CapabilitySpec` 对象(`kind` 是能力类别,`scope` 是 HTTP 调用所需的 ApiScope)。
要点:输出只写业务需要的字段,因为 zod 会剥掉多余字段;不要把凭证放进输出;有副作用的 handler 要按 `idempotencyKey` 到操作账本去重。propose / approve / execute 三类都必须经过 `authorize`,并由注册中心生成幂等键。崩溃恢复时,`replay:"never"` 的工具会得到"结果未知",模型需要用查询类能力核对状态。
## 在 server 中装配(W2)
@@ -53,11 +47,16 @@ const registry = new CapabilityRegistry({
audit: (rec) => auditRepo.insert({ type: "capability.invoke", ...rec }), // 写 audit_event
idempotencyKey: (d, input, ctx) => opLedger.keyFor(d.id, input, ctx), // 可选
});
registerAllCapabilities(registry); // catalog.lookup / release.search / … / inventory.query
for (const m of modules) m.registerCapabilities?.(registry, ctx); // 各 server 模块用 capabilitySpec(id) 注册处理器
const runtime = new PiAgentRuntime({
registry,
onEvent: (e) => agentRunEvents.append(e).then(() => sse.publish(`agent_run:${e.runId}`, e)), // 先落库(带 seq)再推 SSE
// e 是 contracts 的 AgentRunEvent;同一 run 内按 seq 串行回调。先落库再推 SSE:
onEvent: async (e) => {
await db.insertInto("agent_run_event").values(toDbRow(agentRunEventToRow(e))).execute(); // (run_id, seq) 唯一
const bus = agentRunEventToBusEvent(e); // agent.run_status / agent.text_delta / agent.tool_call,其余返回 null
if (bus) events.publish(bus.type, bus.payload);
},
});
// 在持久任务 agentRun 的处理器里执行(不要在聊天 HTTP 请求里驱动):
@@ -68,7 +67,8 @@ const run = await runtime.createRun({
capabilities: ["catalog.lookup", "inventory.query", "download.plan", "download.submit"],
settings: { ...settingsRow.agent, apiKey: await secrets.decrypt(settingsRow.agent.apiKeyRef) },
sessionDir: join(dataDir, "agent-sessions"),
actor: { actorId, taskId: task.id, scopeIds, allowedScopes }, // "先给方案"模式传 ['read','preview','propose']
actor: { actorId, taskId: task.id, scopeIds, allowedKinds }, // "先给方案"模式传 ['read','preview','propose']
firstSeq, // 续跑时 = 该 run 在 agent_run_event 中的 max(seq)+1
});
const outcome = run.pendingOperations > 0 ? await run.resume() : await run.prompt();
await run.close();
@@ -79,4 +79,8 @@ await run.close();
## 事件
`AgentEvent` = `{ runId, seq, at } &` 下列之一:`run_started`、`text_delta`、`thinking_delta`、`tool_call_start`/`tool_call_end`(带脱敏截断后的输入/输出摘要和 `recovery` 标记)、`tool_call_rejected`、`compaction`(start/end)、`run_completed`(usage + 最终文本)、`run_failed`(reason: budget | aborted | error)。`run.events(fromSeq)` 回放已有事件后继续跟随新事件,`close()` 后结束。
事件类型只在 contracts 定义(`AgentRunEvent` / `AgentRunEventBody` / `AgentRunEventType`,B9):`{ runId, seq, at } &` 下列之一:`run_started`、`text_delta`、`thinking_delta`、`tool_call_start`/`tool_call_end`(带脱敏截断后的输入/输出摘要和 `recovery` 标记)、`tool_call_rejected`、`compaction`(start/end)、`run_completed`(`AgentUsageTotals` + 最终文本)、`run_failed`(reason: budget | aborted | error)。
- 落库:`agent_run_event(run_id, seq, type, at, payload)`,主键 (run_id, seq);`agentRunEventToRow` / `agentRunEventFromRow` 负责转换。
- 推送:`agentRunEventToBusEvent` 映射到全局 SSE 的 `agent.run_status` / `agent.text_delta` / `agent.tool_call`(phase:start→started,end→succeeded/failed,rejected→denied)。
- `run.events(fromSeq)` 回放本进程已有事件后继续跟随新事件,`close()` 后结束;跨进程回放读 `agent_run_event`。
+41 -28
View File
@@ -1,24 +1,29 @@
import { createHash } from "node:crypto";
import {
ApiScope,
AUTHORIZED_KINDS,
CapabilityKind,
CapabilityReplay,
type CapabilitySpec,
RiskLevel,
} from "@umt/contracts";
import { z } from "zod";
import { summarizeForLog } from "../redact.ts";
import { CapabilityError, isCapabilityError } from "./errors.ts";
import { capabilityIdToToolName, isCapabilityId } from "./tool-name.ts";
import {
type AuditSink,
type AuthorizationChecker,
type AuthorizationDecision,
CAPABILITY_SCOPES,
type CapabilityAuditRecord,
type CapabilityDescriptor,
type CapabilityHandler,
type CapabilityScope,
type HandlerContext,
type IdempotencyKeyGenerator,
type InvokeContext,
import type {
AuditSink,
AuthorizationChecker,
AuthorizationDecision,
CapabilityAuditRecord,
CapabilityHandler,
HandlerContext,
IdempotencyKeyGenerator,
InvokeContext,
} from "./types.ts";
export interface RegisteredCapability {
descriptor: CapabilityDescriptor;
descriptor: CapabilitySpec;
handler: CapabilityHandler;
toolName: string;
}
@@ -26,11 +31,11 @@ export interface RegisteredCapability {
export interface CapabilityRegistryOptions {
/**
* 授权回调(服务端注入):检查 automation_grant / approval。
* 未注入时:read/preview 放行,propose/execute 一律拒绝(安全默认)。
* 未注入时:read/preview 放行,propose/approve/execute 一律拒绝(安全默认)。
*/
authorize?: AuthorizationChecker;
/** 需要走授权回调的作用域,默认 propose + execute */
authorizeScopes?: readonly CapabilityScope[];
/** 需要走授权回调的类别,默认 contracts 的 AUTHORIZED_KINDS(propose/approve/execute) */
authorizeKinds?: readonly CapabilityKind[];
/** 审计回调;每次调用(含拒绝/校验失败)都会触发一次 */
audit?: AuditSink;
/** 幂等键生成(服务端基于操作语义生成,不信任模型);默认对 id+version+规范化输入做 sha256 */
@@ -64,7 +69,7 @@ export class CapabilityRegistry {
}
register<I extends z.ZodType, O extends z.ZodType>(
descriptor: CapabilityDescriptor<I, O>,
descriptor: CapabilitySpec<I, O>,
handler: CapabilityHandler<I, O>,
): this {
if (!isCapabilityId(descriptor.id)) throw new Error(`能力 ID 必须是 域.动作 形式: ${descriptor.id}`);
@@ -72,14 +77,17 @@ export class CapabilityRegistry {
if (!Number.isInteger(descriptor.version) || descriptor.version < 1) {
throw new Error(`能力版本必须是正整数: ${descriptor.id}`);
}
if (!CAPABILITY_SCOPES.includes(descriptor.scope)) throw new Error(`未知作用域: ${descriptor.scope}`);
if (!CapabilityKind.safeParse(descriptor.kind).success) throw new Error(`未知能力类别: ${descriptor.kind}`);
if (!ApiScope.safeParse(descriptor.scope).success) throw new Error(`未知 API scope: ${descriptor.scope}`);
if (!RiskLevel.safeParse(descriptor.riskLevel).success) throw new Error(`未知风险级别: ${descriptor.riskLevel}`);
if (!CapabilityReplay.safeParse(descriptor.replay).success) throw new Error(`未知 replay: ${descriptor.replay}`);
if (!descriptor.description.trim()) throw new Error(`能力缺少给模型看的说明: ${descriptor.id}`);
if (descriptor.scope === "execute" && descriptor.replay === "safe" && !descriptor.idempotent) {
if (sideEffecting(descriptor.kind) && descriptor.replay === "safe" && !descriptor.idempotent) {
throw new Error(`有副作用且非幂等的能力不能声明 replay:'safe': ${descriptor.id}`);
}
const toolName = capabilityIdToToolName(descriptor.id);
this.entries.set(descriptor.id, {
descriptor: descriptor as unknown as CapabilityDescriptor,
descriptor: descriptor as unknown as CapabilitySpec,
handler: handler as unknown as CapabilityHandler,
toolName,
});
@@ -131,7 +139,7 @@ export class CapabilityRegistry {
const record: CapabilityAuditRecord = {
capabilityId: descriptor.id,
version: descriptor.version,
scope: descriptor.scope,
kind: descriptor.kind,
riskLevel: descriptor.riskLevel,
actorId: ctx.actorId,
taskId: ctx.taskId,
@@ -156,10 +164,10 @@ export class CapabilityRegistry {
if (ctx.signal.aborted) throw await fail(new CapabilityError("precondition", "调用已取消"), "denied");
// 1. 作用域:调用方给出的上限
if (ctx.allowedScopes && !ctx.allowedScopes.includes(descriptor.scope)) {
// 1. 类别:调用方给出的上限
if (ctx.allowedKinds && !ctx.allowedKinds.includes(descriptor.kind)) {
throw await fail(
new CapabilityError("unauthorized", `当前任务不允许 ${descriptor.scope} 级能力: ${descriptor.id}`),
new CapabilityError("unauthorized", `当前任务不允许 ${descriptor.kind} 类能力: ${descriptor.id}`),
"denied",
);
}
@@ -177,9 +185,9 @@ export class CapabilityRegistry {
}
// 3. 授权(服务端判定,模型声明无效)
const authorizeScopes = this.options.authorizeScopes ?? ["propose", "execute"];
const authorizeKinds = this.options.authorizeKinds ?? AUTHORIZED_KINDS;
let decision: AuthorizationDecision | undefined;
if (authorizeScopes.includes(descriptor.scope)) {
if (authorizeKinds.includes(descriptor.kind)) {
if (!this.options.authorize) {
throw await fail(new CapabilityError("unauthorized", `未配置授权校验,拒绝 ${descriptor.id}`), "denied");
}
@@ -193,9 +201,9 @@ export class CapabilityRegistry {
}
}
// 4. 幂等键(只对有副作用的作用域生成)
// 4. 幂等键(只对有副作用的类别生成)
let idempotencyKey: string | undefined;
if (descriptor.scope === "propose" || descriptor.scope === "execute") {
if (sideEffecting(descriptor.kind)) {
idempotencyKey = (this.options.idempotencyKey ?? defaultIdempotencyKey)(descriptor, parsed.data, ctx);
}
@@ -233,6 +241,11 @@ export class CapabilityRegistry {
}
}
/** propose/approve/execute 会落变更;read/preview 不会 */
function sideEffecting(kind: CapabilityKind): boolean {
return kind === "propose" || kind === "approve" || kind === "execute";
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+11 -36
View File
@@ -1,43 +1,18 @@
import type { CapabilityContext } from "@umt/contracts";
import type { CapabilityContext, CapabilityKind, CapabilitySpec, RiskLevel } from "@umt/contracts";
import type { z } from "zod";
/**
* 能力作用域(由弱到强):
* - read:只读查询
* - preview:生成预览/方案,不落任何变更
* - propose:生成并保存变更计划(MutationPlan),等待授权
* - execute:产生外部副作用(下载提交、Copy/Move、策略发布…)
* 能力描述统一取自 @umt/contracts(B3):
* - 运行时规格 `CapabilitySpec`(描述符字段 + 真实 zod schema),首批能力用 `capabilitySpec(id)` 组装;
* - 类别 `CapabilityKind`(read/preview/propose/approve/execute),风险 `RiskLevel`,重放 `CapabilityReplay`。
* 本包不再定义自己的一套。
*/
export const CAPABILITY_SCOPES = ["read", "preview", "propose", "execute"] as const;
export type CapabilityScope = (typeof CAPABILITY_SCOPES)[number];
export const CAPABILITY_RISK_LEVELS = ["low", "medium", "high", "critical"] as const;
export type CapabilityRiskLevel = (typeof CAPABILITY_RISK_LEVELS)[number];
/**
* 能力描述。description 会原样给模型看,用中文写清用途、边界与返回含义。
* replay:崩溃恢复时 harness 是否可以用持久化参数重跑;有副作用的一律 'never'。
*/
export interface CapabilityDescriptor<I extends z.ZodType = z.ZodType, O extends z.ZodType = z.ZodType> {
id: string;
version: number;
title: string;
description: string;
inputSchema: I;
outputSchema: O;
scope: CapabilityScope;
riskLevel: CapabilityRiskLevel;
idempotent: boolean;
supportsPreview: boolean;
replay: "safe" | "never";
}
/**
* 调用上下文:contracts 的 CapabilityContext(actorId/taskId/scopeIds/signal)加上本包需要的字段。
* allowedScopes:本次调用方允许触达的最高作用域集合(例如"先给方案"模式只给 read/preview/propose)。
* allowedKinds:本次调用方允许触达的能力类别(例如"先给方案"模式只给 read/preview/propose)。
*/
export interface InvokeContext extends CapabilityContext {
allowedScopes?: readonly CapabilityScope[];
allowedKinds?: readonly CapabilityKind[];
/** 调用来源,仅用于审计 */
source?: "agent" | "web" | "cli" | "mcp" | "task";
/** agent 调用时的 tool call id / invocation id,用于审计对账 */
@@ -57,7 +32,7 @@ export type CapabilityHandler<I extends z.ZodType = z.ZodType, O extends z.ZodTy
) => Promise<z.input<O>> | z.input<O>;
export interface AuthorizationRequest {
descriptor: CapabilityDescriptor;
descriptor: CapabilitySpec;
input: unknown;
ctx: InvokeContext;
}
@@ -74,15 +49,15 @@ export type AuthorizationChecker = (
request: AuthorizationRequest,
) => Promise<AuthorizationDecision> | AuthorizationDecision;
export type IdempotencyKeyGenerator = (descriptor: CapabilityDescriptor, input: unknown, ctx: InvokeContext) => string;
export type IdempotencyKeyGenerator = (descriptor: CapabilitySpec, input: unknown, ctx: InvokeContext) => string;
export type AuditOutcome = "ok" | "denied" | "invalid" | "error";
export interface CapabilityAuditRecord {
capabilityId: string;
version: number;
scope: CapabilityScope;
riskLevel: CapabilityRiskLevel;
kind: CapabilityKind;
riskLevel: RiskLevel;
actorId: string;
taskId: string;
source?: InvokeContext["source"];
+37 -28
View File
@@ -10,6 +10,7 @@ import {
type RunResult,
} from "@earendil-works/pi-agent-core";
import type { Usage } from "@earendil-works/pi-ai";
import type { AgentBudgetKind, AgentRunEvent, AgentRunEventBody, AgentUsageTotals } from "@umt/contracts";
import type { TSchema } from "typebox";
import { isCapabilityError } from "../capability/errors.ts";
import type { CapabilityRegistry, RegisteredCapability } from "../capability/registry.ts";
@@ -17,12 +18,8 @@ import { toolNameToCapabilityId } from "../capability/tool-name.ts";
import { redactForModel, redactString, summarizeForLog } from "../redact.ts";
import { EventChannel } from "../runtime/event-channel.ts";
import {
type AgentEvent,
type AgentEventBody,
type AgentRun,
type AgentRunHandle,
type AgentRuntimePort,
type AgentUsage,
type BudgetKind,
type CreateRunSpec,
emptyUsage,
type RunOutcome,
@@ -35,8 +32,13 @@ export interface PiAgentRuntimeOptions {
registry: CapabilityRegistry;
/** 默认按设置构造真实上游;测试用 FakeModelProvider 覆盖 */
resolveModel?: PiModelResolver;
/** 每个事件产生时回调(server 用它写 agent_run_event 并推 SSE) */
onEvent?: (event: AgentEvent) => void | Promise<void>;
/**
* 每个事件产生时回调(server 用它写 agent_run_event 再推 SSE)。
* 同一 run 内按 seq 顺序串行调用(前一个 Promise 结束才调下一个);回调抛错只记入 onEventError,不影响运行。
* close() 会等待已排队的回调全部完成。
*/
onEvent?: (event: AgentRunEvent) => void | Promise<void>;
onEventError?: (error: unknown, event: AgentRunEvent) => void;
now?: () => Date;
}
@@ -50,7 +52,7 @@ const SUMMARY_LIMIT = 600;
export class PiAgentRuntime implements AgentRuntimePort {
constructor(private readonly options: PiAgentRuntimeOptions) {}
async createRun(spec: CreateRunSpec): Promise<AgentRun> {
async createRun(spec: CreateRunSpec): Promise<AgentRunHandle> {
const ctx = BACKGROUND_CONTEXT;
const settings = resolveAgentSettings(spec.settings);
const capabilities = this.options.registry.resolve(spec.capabilities);
@@ -86,22 +88,24 @@ export class PiAgentRuntime implements AgentRuntimePort {
}
}
type BudgetState = { kind: BudgetKind; message: string };
type BudgetState = { kind: AgentBudgetKind; message: string };
class PiAgentRun implements AgentRun {
class PiAgentRun implements AgentRunHandle {
readonly runId: string;
readonly sessionPath: string;
pendingOperations = 0;
private readonly channel = new EventChannel<AgentEvent>();
private readonly channel = new EventChannel<AgentRunEvent>();
private readonly allowed = new Map<string, string>();
private readonly rejected = new Set<string>();
private readonly abortController = new AbortController();
private harness!: AgentHarnessInstance<object>;
private lane!: AgentLane;
private seq = 0;
private readonly firstSeq: number;
private seq: number;
private delivery: Promise<void> = Promise.resolve();
private toolCalls = 0;
private usage: AgentUsage = emptyUsage();
private usage: AgentUsageTotals = emptyUsage();
private finalText = "";
private budget: BudgetState | undefined;
private userAbort: string | undefined;
@@ -119,6 +123,8 @@ class PiAgentRun implements AgentRun {
) {
this.runId = spec.runId;
this.sessionPath = sessionPath;
this.firstSeq = spec.firstSeq ?? 0;
this.seq = this.firstSeq;
for (const c of capabilities) this.allowed.set(c.toolName, c.descriptor.id);
}
@@ -130,10 +136,10 @@ class PiAgentRun implements AgentRun {
return {
name: entry.toolName,
label: descriptor.title,
description: `${descriptor.description}\n[能力 ${descriptor.id} v${descriptor.version};作用域 ${descriptor.scope};风险 ${descriptor.riskLevel}]`,
description: `${descriptor.description}\n[能力 ${descriptor.id} v${descriptor.version};类别 ${descriptor.kind};风险 ${descriptor.riskLevel}]`,
parameters: registry.inputJsonSchema(descriptor.id) as unknown as TSchema,
replay: descriptor.replay,
...(descriptor.scope === "execute" ? { executionMode: "sequential" as const } : {}),
...(descriptor.kind === "execute" ? { executionMode: "sequential" as const } : {}),
execute: async (toolCallId, params, _onUpdate, _toolCtx, invocation, context) => {
const signal = context.abortSignal ?? this.abortController.signal;
try {
@@ -141,7 +147,7 @@ class PiAgentRun implements AgentRun {
actorId: actor.actorId,
taskId: actor.taskId,
scopeIds: actor.scopeIds,
...(actor.allowedScopes ? { allowedScopes: actor.allowedScopes } : {}),
...(actor.allowedKinds ? { allowedKinds: actor.allowedKinds } : {}),
signal,
source: "agent",
invocationId: invocation.invocationId ?? toolCallId,
@@ -251,11 +257,11 @@ class PiAgentRun implements AgentRun {
);
}
events(fromSeq = 0): AsyncIterable<AgentEvent> {
return this.channel.iterate(fromSeq);
events(fromSeq = this.firstSeq): AsyncIterable<AgentRunEvent> {
return this.channel.iterate(fromSeq - this.firstSeq);
}
history(): AgentEvent[] {
history(): AgentRunEvent[] {
return this.channel.snapshot();
}
@@ -291,6 +297,7 @@ class PiAgentRun implements AgentRun {
await this.harness?.close(ctx).catch(() => undefined);
await this.repo.close(ctx).catch(() => undefined);
this.channel.close();
await this.delivery;
}
// ---- internals ----
@@ -341,7 +348,7 @@ class PiAgentRun implements AgentRun {
return outcome;
}
private failed(reason: RunOutcome["reason"] & string, message: string, budget?: BudgetKind): RunOutcome {
private failed(reason: RunOutcome["reason"] & string, message: string, budget?: AgentBudgetKind): RunOutcome {
return {
status: "failed",
reason,
@@ -359,7 +366,7 @@ class PiAgentRun implements AgentRun {
this.emit({ type: "tool_call_rejected", toolCallId, toolName, ...(capabilityId ? { capabilityId } : {}), reason });
}
private exceed(kind: BudgetKind, message: string): void {
private exceed(kind: AgentBudgetKind, message: string): void {
if (this.budget) return;
this.budget = { kind, message };
this.scheduleAbort();
@@ -392,13 +399,15 @@ class PiAgentRun implements AgentRun {
this.deadlineTimer = undefined;
}
private emit(body: AgentEventBody): void {
const event = { ...body, runId: this.runId, seq: this.seq++, at: new Date().toISOString() } as AgentEvent;
private emit(body: AgentRunEventBody): void {
const event = { ...body, runId: this.runId, seq: this.seq++, at: new Date().toISOString() } as AgentRunEvent;
this.channel.push(event);
if (this.options.onEvent) {
Promise.resolve()
.then(() => this.options.onEvent?.(event))
.catch(() => undefined);
const onEvent = this.options.onEvent;
if (onEvent) {
// 串行投递:落库顺序与 seq 一致
this.delivery = this.delivery
.then(() => onEvent(event))
.catch((error) => this.options.onEventError?.(error, event));
}
}
}
@@ -427,7 +436,7 @@ function assistantText(message: AgentMessage): string | undefined {
.join("");
}
function toAgentUsage(u: Usage): AgentUsage {
function toAgentUsage(u: Usage): AgentUsageTotals {
return {
inputTokens: u.input,
outputTokens: u.output,
+25 -57
View File
@@ -1,52 +1,14 @@
import type { CapabilityScope } from "../capability/types.ts";
import type {
AgentBudgetKind,
AgentFailureReason,
AgentRunEvent,
AgentUsageTotals,
CapabilityKind,
} from "@umt/contracts";
import type { AgentSettings } from "../settings.ts";
/** 本包对外的用量统计(与 SDK 类型解耦) */
export interface AgentUsage {
inputTokens: number;
outputTokens: number;
cacheReadTokens: number;
cacheWriteTokens: number;
totalTokens: number;
costUsd: number;
}
export type AgentFailureReason = "budget" | "aborted" | "error";
export type AgentEventBody =
| { type: "run_started"; goal: string; resumed: boolean }
| { type: "text_delta"; delta: string }
| { type: "thinking_delta"; delta: string }
| {
type: "tool_call_start";
toolCallId: string;
capabilityId: string;
/** 已脱敏、截断的输入摘要 */
inputSummary: string;
recovery: boolean;
}
| {
type: "tool_call_end";
toolCallId: string;
capabilityId: string;
isError: boolean;
/** 已脱敏、截断的输出摘要 */
outputSummary: string;
recovery: boolean;
}
| { type: "tool_call_rejected"; toolCallId: string; toolName: string; capabilityId?: string; reason: string }
| {
type: "compaction";
phase: "start" | "end";
reason: "manual" | "threshold" | "overflow";
status?: "completed" | "declined" | "aborted" | "failed";
}
| { type: "run_completed"; finalText: string; usage: AgentUsage }
| { type: "run_failed"; reason: AgentFailureReason; message: string; usage: AgentUsage; budget?: BudgetKind };
export type BudgetKind = "tool_calls" | "duration" | "tokens" | "cost";
export type AgentEvent = AgentEventBody & { runId: string; seq: number; at: string };
// 事件、用量、失败原因的类型统一取自 @umt/contracts(AgentRunEvent / AgentUsageTotals / AgentFailureReason /
// AgentBudgetKind);本文件只定义运行时端口。
/** 调用能力时使用的业务身份;授权回调据此到 automation_grant / approval 查询 */
export interface AgentActor {
@@ -54,8 +16,8 @@ export interface AgentActor {
/** 持久任务 ID(agent_run 所属任务) */
taskId: string;
scopeIds: string[];
/** 本次运行允许触达的作用域上限;"先给方案"模式传 ['read','preview','propose'] */
allowedScopes?: CapabilityScope[];
/** 本次运行允许触达的能力类别上限;"先给方案"模式传 ['read','preview','propose'] */
allowedKinds?: CapabilityKind[];
}
export interface CreateRunSpec {
@@ -69,26 +31,32 @@ export interface CreateRunSpec {
/** 应用数据目录下的会话目录;会话文件为 sessionDir/<runId>.jsonl */
sessionDir: string;
actor: AgentActor;
/**
* 本进程第一个事件的 seq。续跑(崩溃恢复/多轮对话)时传该 run 已落库事件的 max(seq)+1
* (agent_run_event 中无记录时为 0),保证 (run_id, seq) 不冲突;默认 0。
*/
firstSeq?: number;
}
export interface RunOutcome {
status: "completed" | "failed";
reason?: AgentFailureReason;
budget?: BudgetKind;
budget?: AgentBudgetKind;
message?: string;
finalText: string;
usage: AgentUsage;
usage: AgentUsageTotals;
}
export interface AgentRun {
/** 一次运行的句柄(区别于 contracts 的 AgentRun 行) */
export interface AgentRunHandle {
readonly runId: string;
readonly sessionPath: string;
/** 打开已有会话时发现的未完成操作数;>0 时应调用 resume() */
readonly pendingOperations: number;
/** 从 fromSeq(含)开始回放并持续推送事件;close() 后结束 */
events(fromSeq?: number): AsyncIterable<AgentEvent>;
/** 已产生的全部事件快照 */
history(): AgentEvent[];
events(fromSeq?: number): AsyncIterable<AgentRunEvent>;
/** 本进程已产生的全部事件快照 */
history(): AgentRunEvent[];
/** 发送一条用户消息并驱动到本轮结束;text 省略时使用 goal */
prompt(text?: string): Promise<RunOutcome>;
/** 崩溃/重启后继续未完成的操作 */
@@ -100,9 +68,9 @@ export interface AgentRun {
/** 领域/服务层只依赖这个端口,不直接接触 Pi SDK 类型 */
export interface AgentRuntimePort {
createRun(spec: CreateRunSpec): Promise<AgentRun>;
createRun(spec: CreateRunSpec): Promise<AgentRunHandle>;
}
export function emptyUsage(): AgentUsage {
export function emptyUsage(): AgentUsageTotals {
return { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 0, costUsd: 0 };
}
+6 -3
View File
@@ -1,9 +1,9 @@
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AgentRunEvent } from "@umt/contracts";
import { z } from "zod";
import {
type AgentEvent,
type AgentSettings,
type AuthorizationChecker,
type CapabilityAuditRecord,
@@ -40,6 +40,7 @@ export function makeFixture(opts: { slowMs?: number } = {}): Fixture {
description: "按标题查询本地媒体库是否已有该作品及已有版本。",
inputSchema: z.object({ title: z.string().min(1), year: z.number().int().optional() }),
outputSchema: z.object({ title: z.string(), inLibrary: z.boolean(), versions: z.array(z.string()) }),
kind: "read",
scope: "read",
riskLevel: "low",
idempotent: true,
@@ -56,7 +57,8 @@ export function makeFixture(opts: { slowMs?: number } = {}): Fixture {
description: "提交下载计划到下载器。只代表已提交,不代表已入库。",
inputSchema: z.object({ title: z.string(), quality: z.enum(["720p", "1080p", "2160p"]) }),
outputSchema: z.object({ accepted: z.boolean(), idempotencyKey: z.string(), status: z.literal("submitted") }),
scope: "execute",
kind: "execute",
scope: "organize.execute",
riskLevel: "medium",
idempotent: true,
supportsPreview: true,
@@ -82,6 +84,7 @@ export function makeFixture(opts: { slowMs?: number } = {}): Fixture {
description: "查看站点发布详情(返回原始字段,可能含私有链接)。",
inputSchema: z.object({ releaseId: z.string() }),
outputSchema: z.object({ releaseId: z.string(), torrentUrl: z.string(), cookie: z.string(), note: z.string() }),
kind: "read",
scope: "read",
riskLevel: "low",
idempotent: true,
@@ -127,6 +130,6 @@ export function settings(patch: Partial<AgentSettings> = {}): AgentSettings {
return { ...FAKE_AGENT_SETTINGS, ...patch };
}
export function types(events: AgentEvent[]): string[] {
export function types(events: AgentRunEvent[]): string[] {
return events.filter((e) => e.type !== "text_delta" && e.type !== "thinking_delta").map((e) => e.type);
}
+34 -3
View File
@@ -1,3 +1,4 @@
import { CAPABILITY_IDS, capabilitySpec } from "@umt/contracts";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
@@ -32,6 +33,7 @@ describe("CapabilityRegistry.register", () => {
description: "说明",
inputSchema: z.object({}),
outputSchema: z.object({}),
kind: "read" as const,
scope: "read" as const,
riskLevel: "low" as const,
idempotent: true,
@@ -44,13 +46,41 @@ describe("CapabilityRegistry.register", () => {
expect(() => r.register({ ...base, id: "bad id" }, () => ({}))).toThrow(/域.动作/);
r.register({ ...base, id: "catalog.lookup" }, () => ({}));
expect(() => r.register({ ...base, id: "catalog.lookup" }, () => ({}))).toThrow(/已注册/);
expect(() => r.register({ ...base, id: "cache.cleanup", scope: "execute", idempotent: false }, () => ({}))).toThrow(
expect(() => r.register({ ...base, id: "cache.cleanup", kind: "execute", idempotent: false }, () => ({}))).toThrow(
/replay/,
);
expect(() => r.resolve(["catalog.lookup", "nope.nope"])).toThrow(/未注册/);
expect(r.get("catalog.lookup")?.toolName).toBe("catalog__lookup");
});
it("首批 14 个能力可直接用 contracts 的 capabilitySpec 注册", () => {
const r = new CapabilityRegistry();
for (const id of CAPABILITY_IDS) r.register(capabilitySpec(id), () => ({}) as never);
expect(r.list().map((c) => c.descriptor.id)).toEqual([...CAPABILITY_IDS]);
expect(r.inputJsonSchema("release.search").type).toBe("object");
});
it("approve 类能力同样必须经授权回调,且生成幂等键", async () => {
const seen: string[] = [];
const r = new CapabilityRegistry({
authorize: ({ descriptor }) => {
seen.push(descriptor.id);
return { allowed: true, approvalId: "ap-1" };
},
});
r.register({ ...base, id: "approval.decide", kind: "approve", replay: "never" }, (_i, c) => {
expect(c.idempotencyKey).toMatch(/^approval\.decide:v1:/);
return {};
});
await r.invoke("approval.decide", {}, ctx());
expect(seen).toEqual(["approval.decide"]);
await expect(
new CapabilityRegistry()
.register({ ...base, id: "approval.decide", kind: "approve" }, () => ({}))
.invoke("approval.decide", {}, ctx()),
).rejects.toMatchObject({ code: "unauthorized" });
});
it("输入 JSON Schema 可给模型使用(无 $schema)", () => {
const { registry } = makeFixture();
const schema = registry.inputJsonSchema("download.submit");
@@ -97,7 +127,7 @@ describe("CapabilityRegistry.invoke", () => {
expect(fx.audits.at(-1)).toMatchObject({ outcome: "ok", grantId: "grant:download.submit" });
});
it("未注入授权回调:read 放行、execute 一律拒绝;allowedScopes 限制作用域", async () => {
it("未注入授权回调:read 放行、execute 一律拒绝;allowedKinds 限制能力类别", async () => {
const r = new CapabilityRegistry();
const fx = makeFixture();
const inv = fx.registry.get("inventory.query")!;
@@ -113,7 +143,7 @@ describe("CapabilityRegistry.invoke", () => {
fx.registry.invoke(
"download.submit",
{ title: "x", quality: "720p" },
ctx({ allowedScopes: ["read", "preview"] }),
ctx({ allowedKinds: ["read", "preview"] }),
),
).rejects.toMatchObject({ code: "unauthorized" });
expect(fx.submitted).toHaveLength(0);
@@ -158,6 +188,7 @@ describe("CapabilityRegistry.invoke", () => {
description: "说明",
inputSchema: z.object({}),
outputSchema: z.object({ ok: z.boolean() }),
kind: "read" as const,
scope: "read" as const,
riskLevel: "low" as const,
idempotent: true,
+44 -7
View File
@@ -1,10 +1,10 @@
import { spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { AgentRunEvent } from "@umt/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
type AgentEvent,
type AgentRun,
type AgentRunHandle,
type AgentSettings,
checkToolCall,
createFakeRuntime,
@@ -13,7 +13,7 @@ import {
import { crashScript, RUN_ID } from "./fixtures/crash-script.ts";
import { type Fixture, makeFixture, settings, tempDir, types } from "./helpers.ts";
const opened: AgentRun[] = [];
const opened: AgentRunHandle[] = [];
afterEach(async () => {
await Promise.all(opened.splice(0).map((r) => r.close()));
});
@@ -42,9 +42,20 @@ const dune: FakeScript = {
async function start(
fx: Fixture,
scripts: FakeScript[],
opts: { capabilities?: string[]; settings?: Partial<AgentSettings>; runId?: string; sessionDir?: string } = {},
opts: {
capabilities?: string[];
settings?: Partial<AgentSettings>;
runId?: string;
sessionDir?: string;
firstSeq?: number;
onEvent?: (e: AgentRunEvent) => void | Promise<void>;
} = {},
) {
const { runtime, fake } = createFakeRuntime({ registry: fx.registry, scripts });
const { runtime, fake } = createFakeRuntime({
registry: fx.registry,
scripts,
...(opts.onEvent ? { onEvent: opts.onEvent } : {}),
});
const sessionDir = opts.sessionDir ?? (await tempDir());
const run = await runtime.createRun({
runId: opts.runId ?? "run-1",
@@ -54,6 +65,7 @@ async function start(
settings: settings(opts.settings),
sessionDir,
actor: { actorId: "user:1", taskId: "task:1", scopeIds: ["media:dune"] },
...(opts.firstSeq !== undefined ? { firstSeq: opts.firstSeq } : {}),
});
opened.push(run);
return { run, fake, sessionDir };
@@ -106,12 +118,12 @@ describe("PiAgentRuntime + FakeModelProvider", () => {
it("events() 可按 seq 回放并在 close 后结束", async () => {
const fx = makeFixture();
const { run } = await start(fx, [{ match: "Dune", steps: [], finalText: "库里已有。" }]);
const collected: AgentEvent[] = [];
const collected: AgentRunEvent[] = [];
const consumer = (async () => {
for await (const e of run.events()) collected.push(e);
})();
await run.prompt();
const tail: AgentEvent[] = [];
const tail: AgentRunEvent[] = [];
const replay = (async () => {
for await (const e of run.events(1)) tail.push(e);
})();
@@ -122,6 +134,31 @@ describe("PiAgentRuntime + FakeModelProvider", () => {
expect(collected.at(-1)?.type).toBe("run_completed");
});
it("onEvent 按 seq 串行投递 contracts AgentRunEvent;firstSeq 续接序号,close 等待投递完成", async () => {
const fx = makeFixture();
const delivered: AgentRunEvent[] = [];
const { run } = await start(fx, [{ match: "Dune", steps: [], finalText: "库里已有。" }], {
firstSeq: 10,
// 故意让前面的事件落库更慢,验证不会乱序
onEvent: async (e) => {
await new Promise((r) => setTimeout(r, e.seq === 10 ? 20 : 0));
delivered.push(e);
},
});
await run.prompt();
const tail: AgentRunEvent[] = [];
const replay = (async () => {
for await (const e of run.events(11)) tail.push(e);
})();
await run.close();
await replay;
const seqs = run.history().map((e) => e.seq);
expect(seqs[0]).toBe(10);
expect(delivered.map((e) => e.seq)).toEqual(seqs);
expect(tail[0]?.seq).toBe(11);
for (const e of delivered) expect(AgentRunEvent.safeParse(e).success, e.type).toBe(true);
});
it("白名单:未注册工具(bash)与未列入白名单的已注册能力都被拒绝并产生事件,不执行", async () => {
const fx = makeFixture();
fx.grants.set("user:1", new Set(["download.submit"]));