示例工程 60-tool-registry-approval

60-tool-registry-approval/app/shared/tools.ts

typescript · 7.8 KB

export type Risk = "read" | "write" | "exec" | "network";

export type ApprovalDecision =
  "auto" | "deny" | "allow-once" | "allow-session" | "use-grant";

export type ToolField = {
  name: string;
  type: "string" | "number";
  required: boolean;
};

export type ToolDef = {
  id: string;
  name: string;
  risk: Risk;
  description: string;
  timeoutMs: number;
  maxOutput: number;
  fields: ToolField[];
};

export type ToolCall = {
  scenarioId: string;
  toolId: string;
  args: Record<string, string>;
};

export type Scenario = {
  id: string;
  label: string;
  toolId: string;
  args: Record<string, string>;
  note: string;
  costMs: number;
};

export type ToolStatus =
  "ok" | "denied" | "approval-required" | "timeout" | "invalid";

export type ToolResult = {
  scenarioId: string;
  toolId: string;
  risk: Risk;
  status: ToolStatus;
  decision: ApprovalDecision | "grant" | "policy";
  durationMs: number;
  summary: string;
  output: string;
};

export type AuditEntry = ToolResult & {
  seq: number;
  at: number;
  approvedBy: "auto" | "user" | "policy" | "none";
};

export const TOOLS: ToolDef[] = [
  {
    id: "read_file",
    name: "read_file",
    risk: "read",
    description: "读取工作区内单个文件",
    timeoutMs: 500,
    maxOutput: 4096,
    fields: [{ name: "path", type: "string", required: true }],
  },
  {
    id: "list_dir",
    name: "list_dir",
    risk: "read",
    description: "列出工作区目录",
    timeoutMs: 500,
    maxOutput: 2048,
    fields: [{ name: "path", type: "string", required: true }],
  },
  {
    id: "write_file",
    name: "write_file",
    risk: "write",
    description: "写入工作区文件",
    timeoutMs: 800,
    maxOutput: 1024,
    fields: [
      { name: "path", type: "string", required: true },
      { name: "content", type: "string", required: true },
    ],
  },
  {
    id: "run_shell",
    name: "run_shell",
    risk: "exec",
    description: "执行白名单命令",
    timeoutMs: 200,
    maxOutput: 2048,
    fields: [{ name: "command", type: "string", required: true }],
  },
  {
    id: "fetch_url",
    name: "fetch_url",
    risk: "network",
    description: "请求允许的 HTTPS 地址",
    timeoutMs: 1200,
    maxOutput: 4096,
    fields: [{ name: "url", type: "string", required: true }],
  },
];

export const SCENARIOS: Scenario[] = [
  {
    id: "read-config",
    label: "读取配置(只读)",
    toolId: "read_file",
    args: { path: "src/config.ts" },
    note: "受信工作区内的只读操作,自动允许。",
    costMs: 6,
  },
  {
    id: "write-notes",
    label: "写入笔记(需审批)",
    toolId: "write_file",
    args: { path: "notes/today.md", content: "今天的调试记录" },
    note: "写入需要明确审批;session 授权在本次会话内复用。",
    costMs: 8,
  },
  {
    id: "run-tests",
    label: "运行测试(exec)",
    toolId: "run_shell",
    args: { command: "pnpm test" },
    note: "exec 永远需要审批,即使已有 session 授权。",
    costMs: 24,
  },
  {
    id: "slow-tool",
    label: "超时命令(timeout)",
    toolId: "run_shell",
    args: { command: "sleep 5" },
    note: "命令运行时间超过工具超时,标记 timeout 而不是取消。",
    costMs: 320,
  },
  {
    id: "bad-args",
    label: "参数缺失(invalid)",
    toolId: "write_file",
    args: { path: "notes/x.md" },
    note: "缺少必填 content;校验在审批之前,不执行也不弹审批。",
    costMs: 4,
  },
  {
    id: "outside",
    label: "越界路径(policy)",
    toolId: "read_file",
    args: { path: "../secrets.env" },
    note: "工作区外路径由策略直接拒绝,不进入审批。",
    costMs: 4,
  },
];

export function toolById(id: string): ToolDef | undefined {
  return TOOLS.find((tool) => tool.id === id);
}

export function scenarioById(id: string): Scenario | undefined {
  return SCENARIOS.find((scenario) => scenario.id === id);
}

export function validateArgs(
  tool: ToolDef,
  args: Record<string, string>,
): string | null {
  for (const field of tool.fields) {
    if (!field.required) continue;
    const value = args[field.name];
    if (typeof value !== "string" || value.trim().length === 0) {
      return `MISSING_${field.name.toUpperCase()}`;
    }
  }
  return null;
}

export function isOutsideWorkspace(path: string): boolean {
  if (path.startsWith("/") || path.startsWith("~")) return true;
  return path.split("/").includes("..");
}

export function needsApproval(tool: ToolDef): boolean {
  return tool.risk !== "read";
}

export type RunInput = {
  scenarioId: string;
  decision: ApprovalDecision;
};

export type RunContext = {
  grants: Set<string>;
  sleep: (ms: number) => Promise<void>;
};

export async function runScenario(
  input: RunInput,
  context: RunContext,
): Promise<ToolResult> {
  const started = Date.now();
  const scenario = scenarioById(input.scenarioId);
  if (!scenario) {
    return {
      scenarioId: input.scenarioId,
      toolId: "unknown",
      risk: "read",
      status: "invalid",
      decision: "policy",
      durationMs: Date.now() - started,
      summary: "UNKNOWN_SCENARIO",
      output: "",
    };
  }
  const tool = toolById(scenario.toolId);
  if (!tool) {
    return {
      scenarioId: scenario.id,
      toolId: scenario.toolId,
      risk: "read",
      status: "invalid",
      decision: "policy",
      durationMs: Date.now() - started,
      summary: "UNKNOWN_TOOL",
      output: "",
    };
  }

  const base = {
    scenarioId: scenario.id,
    toolId: tool.id,
    risk: tool.risk,
    durationMs: 0,
  };

  const invalid = validateArgs(tool, scenario.args);
  if (invalid) {
    return {
      ...base,
      status: "invalid",
      decision: "policy",
      durationMs: Date.now() - started,
      summary: invalid,
      output: "",
    };
  }

  if (isOutsideWorkspace(scenario.args.path ?? "")) {
    return {
      ...base,
      status: "denied",
      decision: "policy",
      durationMs: Date.now() - started,
      summary: "PATH_OUTSIDE_WORKSPACE",
      output: "",
    };
  }

  let decision: ToolResult["decision"] = "auto";
  if (needsApproval(tool)) {
    if (input.decision === "deny") {
      return {
        ...base,
        status: "denied",
        decision: "deny",
        durationMs: Date.now() - started,
        summary: "USER_DENIED",
        output: "",
      };
    }
    if (input.decision === "use-grant") {
      if (tool.risk === "exec" || !context.grants.has(tool.id)) {
        return {
          ...base,
          status: "approval-required",
          decision: "use-grant",
          durationMs: Date.now() - started,
          summary: "APPROVAL_REQUIRED",
          output: "",
        };
      }
      decision = "grant";
    } else if (input.decision === "allow-once") {
      decision = "allow-once";
    } else if (input.decision === "allow-session") {
      decision = "allow-session";
      context.grants.add(tool.id);
    } else {
      return {
        ...base,
        status: "approval-required",
        decision: "auto",
        durationMs: Date.now() - started,
        summary: "APPROVAL_REQUIRED",
        output: "",
      };
    }
  }

  if (scenario.costMs > tool.timeoutMs) {
    await context.sleep(Math.min(scenario.costMs, tool.timeoutMs));
    return {
      ...base,
      status: "timeout",
      decision,
      durationMs: Date.now() - started,
      summary: `TIMEOUT_${tool.timeoutMs}MS`,
      output: "",
    };
  }

  await context.sleep(scenario.costMs);
  const output =
    scenario.id === "read-config"
      ? "export const mode = 'dev';"
      : scenario.id === "run-tests"
        ? "12 tests passed"
        : scenario.id === "write-notes"
          ? "wrote notes/today.md"
          : "ok";

  return {
    ...base,
    status: "ok",
    decision,
    durationMs: Date.now() - started,
    summary: `${tool.name} ok`,
    output: output.slice(0, tool.maxOutput),
  };
}