{
  "id": "ai-invents-fake-npm-packages",
  "type": "failures",
  "category": "failures",
  "locale": "zh",
  "url": "/zh/failures/ai-invents-fake-npm-packages",
  "title": "如何修复AI编码代理虚构不存在的npm包",
  "description": "AI代理为何会臆想不存在的npm包、如何识别以及如何阻止。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex"
  ],
  "stack": [
    "TypeScript"
  ],
  "tags": [
    "dependencies",
    "hallucination",
    "security"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "一个常见且危险的失败：代理导入了一个不存在的包——\n更糟的是，一个抢注者已注册了与臆想名称匹配的包。\n\n## 症状\n\n代理为一个听起来合理的包编写了导入语句，并将其添加到\n`package.json`，但安装失败或拉取了一个未知包。\n\n```txt\nimport { magicValidate } from \"zod-magic-helpers\"; // does not exist\n```\n\n## 发生原因\n\n模型会对命名约定进行模式匹配（“可能有一个 `-helpers` 包”），并生成听起来*真实*的名称。这是“slopsquatting”供应链攻击的基础。\n\n## 如何识别\n\n- 差异中出现了你不认识的依赖项。\n- 该包的下载量几乎为零，或者最近才发布。\n- 安装解析出的名称与流行包仅差一个字符。\n\n## 如何修复\n\n```txt\n[ ] Verify every new dependency exists and is the one you intend\n[ ] Check weekly downloads + repo link before installing\n[ ] Prefer packages already in the lockfile\n[ ] Pin versions; review the lockfile diff\n```\n\n## 修复提示\n\n```txt title=\"Fix Prompt\"\nYou added a dependency I can't verify. List every new package, its npm URL,\nand weekly download count. Replace any unverified package with a standard,\nwidely-used alternative or inline the logic instead.\n```\n\n## 测试\n\n```bash\nbun pm view <package> 2>/dev/null || echo \"DOES NOT EXIST\"\n```"
}