physical_byte_agent/src/core/tool-pipeline.ts
d-robotics d671f174fe feat(v3): P0 全落地 — T01-T05b 安全骨架 + 命门根治
P0 六项任务全部完成,1044 单测全绿,tsc 0 错。

- T01 真 createAgentSession boot 离线验证(e2e-runtime + e2e-smoke 71 测试)
- T02 safety-gate 正则与 hex 归一联动,堵 devmem 十进制砖板漏洞;devmem-via-bash 硬门
- T03 reg-tool.ts:datasheet 地址校验寄存器工具,prepareArguments 接 hex 归一;barrel 22 工厂
- T04 src/core/tool-pipeline.ts:五段流水线 + 单调 guard 不变量;safety-gate 委托 decide();flash finalizeFlashContent
- T05a sandbox-policy.ts:fail-closed unusable→exitCode126 不 spawn;board-link 包 argv
- T05b native/landlock-run/landlock-run.c:C11 raw-landlock self-restrict-then-exec + Makefile + README;probeViaBinary 接线

测试方法:等价类/边界值/决策表/状态转换/变异/对抗/元蜕变(TDD test-first)。
文档:架构设计文档_v3.md 进度表 + Docs/postmortem/0001-e2e-smoke.md。

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-14 12:12:24 +08:00

317 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @module tool-pipeline
*
* 五段工具执行流水线(T04)—— 嫁接 dsh `ToolRuntimeScheduler`(dsh
* `packages/core/tools/src/index.ts:451`)到 pba 扩展层。
*
* 五段,正交、可组合、单一职责:
* ① pre-execute waterfall —— allow / deny / ask,listener 调 next() 委托
* ② monotonic guards —— 身份保护,任一 deny 不可被 force-allow(单调不变式)
* ③ ctx.approval —— ask 的一次性裁决(fail-closed:无 resolver 则 deny)
* ④ execute around-waterfall—— timeout / retry / metrics 包裹 tool body
* ⑤ post-execute waterfall + finalizeContent —— accept / block / replace / add-context
*
* 与 dsh 的差异:不引 Cordis,自包含中间件链;guard 单调性靠"任一 deny ⟹ 终局 deny"
* 构造保证(非靠身份锁)。见架构设计文档_v3.md §5.3。
*
* 纯逻辑 + 异步,零 pi 运行时依赖,可离线单测。
*/
// ============================================================================
// 上下文 + 基础类型
// ============================================================================
/** 一次工具调用的不可变上下文。 */
export interface ToolCallContext {
readonly toolName: string;
readonly input: unknown;
readonly toolCallId: string;
/** 取消信号(around 的 timeout 容器消费)。 */
readonly signal?: AbortSignal;
/** finalizeContent(工具定义可选注入)。 */
readonly finalizeContent?: FinalizeContent;
/** ask 裁决器(缺省 fail-closed:ask → deny)。 */
readonly approvalResolver?: ApprovalResolver;
/** 透传字段。 */
readonly [key: string]: unknown;
}
/** 工具产出(content-only 是 finalizeContent 的硬不变式)。 */
export interface ToolResult {
readonly content: unknown;
readonly isError?: boolean;
readonly details?: unknown;
}
// ============================================================================
// ① pre-execute + ② guard 裁决
// ============================================================================
export type GuardVerdict =
| { readonly decision: "allow" }
| { readonly decision: "deny"; readonly reason: string }
| { readonly decision: "ask"; readonly reason: string };
/**
* 单调 guard —— 身份保护(带不可变 id)。任一 guard deny 即终局 deny,
* 不可被 pre-execute listener 或其他 guard 的 allow 覆盖(单调不变式)。
*/
export interface MonotonicGuard {
readonly id: string;
evaluate(ctx: ToolCallContext): GuardVerdict | Promise<GuardVerdict>;
}
/** pre-execute listener 裁决:allow/deny/ask 或 abstain(调 next() 委托)。 */
export type PreExecuteVerdict = GuardVerdict | "abstain";
export type PreExecuteListener = (
ctx: ToolCallContext,
next: () => Promise<PreExecuteVerdict>,
) => Promise<PreExecuteVerdict>;
// ============================================================================
// ④ execute around
// ============================================================================
export type ToolBody = (ctx: ToolCallContext) => Promise<ToolResult>;
/** around listener:包裹 tool body(timeout/retry/metrics)。调 next() 执行内层。 */
export type AroundListener = (ctx: ToolCallContext, next: ToolBody) => Promise<ToolResult>;
// ============================================================================
// ⑤ post-execute + finalizeContent
// ============================================================================
export type PostExecuteAction =
| { readonly action: "accept" }
| { readonly action: "block"; readonly reason: string }
| { readonly action: "replace"; readonly result: ToolResult }
| { readonly action: "addContext"; readonly context: unknown };
export type PostExecuteListener = (
ctx: ToolCallContext,
result: ToolResult,
next: () => Promise<PostExecuteAction>,
) => Promise<PostExecuteAction>;
/**
* finalizeContent —— 工具定义注入,materialize 前同步执行。
* content-only 不变量:输出必须是"纯 content"(无嵌套 tool-call)。
* 实现者负责把 details 等剥成 content;抛错 → snapshot 转 isError。
*/
export type FinalizeContent = (result: ToolResult) => ToolResult;
// ============================================================================
// ③ approval
// ============================================================================
/** ask 裁决器。返回 true=allow-once,false=deny。无 resolver 时 ask→deny(fail-closed)。 */
export type ApprovalResolver = (ctx: ToolCallContext, reason: string) => Promise<boolean>;
// ============================================================================
// 终局裁决
// ============================================================================
export type PipelineOutcome =
| { readonly outcome: "executed"; readonly result: ToolResult }
| { readonly outcome: "denied"; readonly reason: string }
| { readonly outcome: "blocked"; readonly reason: string; readonly result?: ToolResult }
| { readonly outcome: "replaced"; readonly result: ToolResult };
export type PreExecuteDecision =
| { readonly decision: "allow" }
| { readonly decision: "deny"; readonly reason: string };
// ============================================================================
// ToolPipeline
// ============================================================================
/**
* 五段流水线调度器。模块级单例 {@link pipeline} 供 safety-gate 等扩展共用。
*
* 单调性靠构造保证:guard verdicts 收集后 `find(deny)`,任一 deny 即终局 deny,
* pre-execute 的 allow 不参与 guard 聚合,故无法 force-allow。
*/
export class ToolPipeline {
private readonly guards = new Map<string, MonotonicGuard>();
private readonly preListeners: PreExecuteListener[] = [];
private readonly aroundListeners: AroundListener[] = [];
private readonly postListeners: PostExecuteListener[] = [];
/**
* 注册单调 guard。id 唯一:重复 id 视为更新(替换 evaluate),不抛错——
* 保证 barrel 重装配(测试多次装配 / session resume)幂等安全。返回 disposer。
*/
registerGuard(guard: MonotonicGuard): () => void {
this.guards.set(guard.id, guard);
return () => this.guards.delete(guard.id);
}
/** 注册 pre-execute listener。返回 disposer。 */
onPreExecute(listener: PreExecuteListener): () => void {
this.preListeners.push(listener);
return () => {
const i = this.preListeners.indexOf(listener);
if (i >= 0) this.preListeners.splice(i, 1);
};
}
/** 注册 around listener(先注册=外层)。返回 disposer。 */
onAround(listener: AroundListener): () => void {
this.aroundListeners.push(listener);
return () => {
const i = this.aroundListeners.indexOf(listener);
if (i >= 0) this.aroundListeners.splice(i, 1);
};
}
/** 注册 post-execute listener。返回 disposer。 */
onPostExecute(listener: PostExecuteListener): () => void {
this.postListeners.push(listener);
return () => {
const i = this.postListeners.indexOf(listener);
if (i >= 0) this.postListeners.splice(i, 1);
};
}
/** 跑完整五段。 */
async run(ctx: ToolCallContext, body: ToolBody): Promise<PipelineOutcome> {
// ①②③ pre-execute + guards + approval
const pre = await this.decide(ctx);
if (pre.decision === "deny") {
return { outcome: "denied", reason: pre.reason };
}
// ④ execute around-waterfall
const raw = await this.runAround(ctx, body);
// ⑤ post-execute waterfall
const post = await this.runPostExecute(ctx, raw);
if (post.action === "block") {
return { outcome: "blocked", reason: post.reason, result: raw };
}
const afterPost = post.action === "replace" ? post.result : raw;
// finalizeContent(content-only 不变量)
const finalized = ctx.finalizeContent ? ctx.finalizeContent(afterPost) : afterPost;
return { outcome: post.action === "replace" ? "replaced" : "executed", result: finalized };
}
/**
* 只跑 ①②③(pre-execute + monotonic guards + approval),返回 allow/deny。
*
* 供 safety-gate 的 tool_call 钩子用:钩子只能在执行前 block,不能跑 body,
* 故只取裁决阶段。单调性同 {@link run}:任一 guard deny ⟹ deny。
*/
async decide(ctx: ToolCallContext): Promise<PreExecuteDecision> {
const soft = await this.runPreExecute(ctx);
const guardVerdicts = await this.collectGuardVerdicts(ctx);
const deniedBy = guardVerdicts.find((v) => v.decision === "deny");
if (deniedBy && deniedBy.decision === "deny") {
return { decision: "deny", reason: `[guard] ${deniedBy.reason}` };
}
const denyFromSoft = soft?.decision === "deny" ? soft : undefined;
if (denyFromSoft && denyFromSoft.decision === "deny") {
return { decision: "deny", reason: `[pre-execute] ${denyFromSoft.reason}` };
}
const guardAsk = guardVerdicts.find((v) => v.decision === "ask");
const askVerdict = guardAsk?.decision === "ask" ? guardAsk : soft?.decision === "ask" ? soft : undefined;
if (askVerdict && askVerdict.decision === "ask") {
const resolver = ctx.approvalResolver;
if (!resolver) {
return { decision: "deny", reason: `[approval] ${askVerdict.reason} (no resolver, fail-closed)` };
}
const allowed = await resolver(ctx, askVerdict.reason);
if (!allowed) {
return { decision: "deny", reason: `[approval] ${askVerdict.reason} (denied by user)` };
}
}
return { decision: "allow" };
}
// ---- 内部:pre-execute waterfall(next() 委托) ----
private async runPreExecute(ctx: ToolCallContext): Promise<GuardVerdict | undefined> {
if (this.preListeners.length === 0) return undefined;
// 构造 next 链:listeners[i] 调 next() → 跑 listeners[i+1]…;末尾 abstain
let i = 0;
const next = async (): Promise<PreExecuteVerdict> => {
if (i >= this.preListeners.length) return "abstain";
const listener = this.preListeners[i];
i++;
return listener(ctx, next);
};
const verdict = await next();
return verdict === "abstain" ? undefined : verdict;
}
// ---- 内部:guards 收集(全部评估,单调性靠聚合) ----
private async collectGuardVerdicts(ctx: ToolCallContext): Promise<GuardVerdict[]> {
const out: GuardVerdict[] = [];
for (const guard of this.guards.values()) {
out.push(await guard.evaluate(ctx));
}
return out;
}
// ---- 内部:around waterfall(先注册=外层) ----
private async runAround(ctx: ToolCallContext, body: ToolBody): Promise<ToolResult> {
let chain: ToolBody = body;
// 反向迭代:listeners[0] 成为最外层
for (let i = this.aroundListeners.length - 1; i >= 0; i--) {
const listener = this.aroundListeners[i];
const inner = chain;
chain = (c) => listener(c, inner);
}
return chain(ctx);
}
// ---- 内部:post-execute waterfall(首个非 accept 生效;addContext 透传) ----
private async runPostExecute(ctx: ToolCallContext, result: ToolResult): Promise<PostExecuteAction> {
if (this.postListeners.length === 0) return { action: "accept" };
let i = 0;
const next = async (): Promise<PostExecuteAction> => {
if (i >= this.postListeners.length) return { action: "accept" };
const listener = this.postListeners[i];
i++;
return listener(ctx, result, next);
};
return next();
}
}
/** 模块级单例:safety-gate 等扩展共用。 */
export const pipeline = new ToolPipeline();
// ============================================================================
// 通用 around 容器:timeout(fail-closed 超时即 isError)
// ============================================================================
/**
* timeout around 容器:body 超时 → 返回 isError 结果(不抛,转成 content)。
*
* @param ms 超时毫秒。
*/
export function withTimeout(ms: number): AroundListener {
return async (ctx, next) => {
const timeoutController = new AbortController();
const timer = setTimeout(() => timeoutController.abort(), ms);
try {
// 竞速:body 完成 vs 超时
const settled = await Promise.race([
next(ctx).then((r) => ({ kind: "ok" as const, r })),
new Promise<{ kind: "timeout" }>((resolve) =>
timeoutController.signal.addEventListener("abort", () => resolve({ kind: "timeout" }), { once: true }),
),
]);
if (settled.kind === "ok") return settled.r;
return {
content: [{ type: "text", text: `TIMEOUT: ${ctx.toolName} exceeded ${ms}ms` }],
isError: true,
details: { timeout: ms },
};
} finally {
clearTimeout(timer);
}
};
}