[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-mengjian-github--copilot-analysis":3,"tool-mengjian-github--copilot-analysis":64},[4,17,27,35,44,52],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",152630,2,"2026-04-12T23:33:54",[13,14,15],"开发框架","Agent","语言模型","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":10,"last_commit_at":23,"category_tags":24,"status":16},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[25,14,26,13],"插件","图像",{"id":28,"name":29,"github_repo":30,"description_zh":31,"stars":32,"difficulty_score":10,"last_commit_at":33,"category_tags":34,"status":16},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[25,13],{"id":36,"name":37,"github_repo":38,"description_zh":39,"stars":40,"difficulty_score":41,"last_commit_at":42,"category_tags":43,"status":16},4487,"LLMs-from-scratch","rasbt\u002FLLMs-from-scratch","LLMs-from-scratch 是一个基于 PyTorch 的开源教育项目，旨在引导用户从零开始一步步构建一个类似 ChatGPT 的大型语言模型（LLM）。它不仅是同名技术著作的官方代码库，更提供了一套完整的实践方案，涵盖模型开发、预训练及微调的全过程。\n\n该项目主要解决了大模型领域“黑盒化”的学习痛点。许多开发者虽能调用现成模型，却难以深入理解其内部架构与训练机制。通过亲手编写每一行核心代码，用户能够透彻掌握 Transformer 架构、注意力机制等关键原理，从而真正理解大模型是如何“思考”的。此外，项目还包含了加载大型预训练权重进行微调的代码，帮助用户将理论知识延伸至实际应用。\n\nLLMs-from-scratch 特别适合希望深入底层原理的 AI 开发者、研究人员以及计算机专业的学生。对于不满足于仅使用 API，而是渴望探究模型构建细节的技术人员而言，这是极佳的学习资源。其独特的技术亮点在于“循序渐进”的教学设计：将复杂的系统工程拆解为清晰的步骤，配合详细的图表与示例，让构建一个虽小但功能完备的大模型变得触手可及。无论你是想夯实理论基础，还是为未来研发更大规模的模型做准备",90106,3,"2026-04-06T11:19:32",[15,26,14,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":10,"last_commit_at":50,"category_tags":51,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,15],{"id":53,"name":54,"github_repo":55,"description_zh":56,"stars":57,"difficulty_score":10,"last_commit_at":58,"category_tags":59,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",85092,"2026-04-10T11:13:16",[26,60,61,25,14,62,15,13,63],"数据工具","视频","其他","音频",{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":70,"readme_en":71,"readme_zh":72,"quickstart_zh":73,"use_case_zh":74,"hero_image_url":75,"owner_login":76,"owner_name":77,"owner_avatar_url":78,"owner_bio":79,"owner_company":80,"owner_location":81,"owner_email":82,"owner_twitter":83,"owner_website":84,"owner_url":85,"languages":86,"stars":91,"forks":92,"last_commit_at":93,"license":83,"difficulty_score":94,"env_os":95,"env_gpu":96,"env_ram":96,"env_deps":97,"category_tags":106,"github_topics":83,"view_count":10,"oss_zip_url":83,"oss_zip_packed_at":83,"status":16,"created_at":107,"updated_at":108,"faqs":109,"releases":110},7035,"mengjian-github\u002Fcopilot-analysis","copilot-analysis","本文详细分析了 Github Copilot 这个基于机器学习的代码自动补全工具的实现原理。作者通过逆向工程的方式,深入探索了 Copilot 的核心逻辑,包括代码提示的入口、获取提示的核心方法、以及相关的缓存策略、实验特性等。","copilot-analysis 是一个深入剖析 GitHub Copilot 内部实现原理的开源项目。由于 Copilot 本身并未开源，其代码经过复杂的 Webpack 打包与混淆处理，普通开发者难以窥探其运作机制。该项目通过逆向工程手段，成功还原了 Copilot VSCode 插件的核心逻辑，解决了“黑盒”工具内部流程不透明的问题。\n\n作者利用 AST（抽象语法树）技术，将压缩混淆后的单一文件智能分割为 700 多个独立模块，并自动识别和重命名关键的依赖参数（如 module、exports、require），同时优化了逗号运算符、短路写法等难以阅读的压缩语法。这使得原本晦涩难懂的源码变得清晰可读，揭示了代码提示的触发入口、核心生成方法、缓存策略及实验特性等关键细节。\n\n该工具非常适合对 AI 编程助手原理感兴趣的后端开发者、逆向工程研究人员以及希望深入理解大模型在 IDE 中落地机制的技术爱好者。通过 copilot-analysis，用户不仅能学习到高级的 JS 逆向分析技巧，还能更透彻地理解机器学习模型如何结合上下文精准推断用户意图，从而在日常开发中更高效地利用 Copi","copilot-analysis 是一个深入剖析 GitHub Copilot 内部实现原理的开源项目。由于 Copilot 本身并未开源，其代码经过复杂的 Webpack 打包与混淆处理，普通开发者难以窥探其运作机制。该项目通过逆向工程手段，成功还原了 Copilot VSCode 插件的核心逻辑，解决了“黑盒”工具内部流程不透明的问题。\n\n作者利用 AST（抽象语法树）技术，将压缩混淆后的单一文件智能分割为 700 多个独立模块，并自动识别和重命名关键的依赖参数（如 module、exports、require），同时优化了逗号运算符、短路写法等难以阅读的压缩语法。这使得原本晦涩难懂的源码变得清晰可读，揭示了代码提示的触发入口、核心生成方法、缓存策略及实验特性等关键细节。\n\n该工具非常适合对 AI 编程助手原理感兴趣的后端开发者、逆向工程研究人员以及希望深入理解大模型在 IDE 中落地机制的技术爱好者。通过 copilot-analysis，用户不仅能学习到高级的 JS 逆向分析技巧，还能更透彻地理解机器学习模型如何结合上下文精准推断用户意图，从而在日常开发中更高效地利用 Copilot，或为相关领域的研究提供宝贵的参考实例。","# 花了大半个月，我终于逆向分析了Github Copilot\n\n## 背景\n\n众所周知，Github Copilot是一种基于机器学习的代码自动补全工具。它使用了来自GitHub的大量代码作为训练数据，并使用OpenAI的语言模型来生成代码。Copilot还可以学习用户的编码习惯，并根据上下文推断出正确的代码片段。\n\n在实际使用中发现大部份提示还是非常好用的，能够较为准确的推测出用户意图，甚至是基于项目其他文件的上下文进行推理。比较好奇这里是怎么做到的，于是探索了这个VSCode插件的详细实现。\n\n## 准备工作\n\n由于Copilot并没有开源，因此我们需要做一些逆向的准备。\n\n首先，找到VSCode插件的安装目录，拿到`extension.js`：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_58bb1238a2c1.png)\n\n在mac下插件目录在`~\u002F.vscode`下，我们可以拿到一个经过压缩混淆的文件：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_fe2d4b693e3d.png)\n\n### 1. 分割`webpack_modules`\n\n针对整个webpack压缩混淆的js，我们首先要将不同的bundle识别出来，分割成单个文件，以便于后续的分析。\n\n由于压缩后的代码存在很多不确定性，一开始打算尝试通过正则提取，但无论如何都有各种边界情况导致提取不正确，最简单的方法还是通过AST来提取。\n\n首先，通过babel-parser将源码解析为AST：\n\n```jsx\nconst ast = parser.parse(source);\n```\n\n然后，通过babel-traverse遍历整个AST，找到modules的变量，取出里面的值：\n\n```jsx\nfunction parseModules() {\n  traverse(ast, {\n    enter(path) {\n      if (\n        path.node.type === \"VariableDeclarator\" &&\n        path.node.id.name === \"__webpack_modules__\"\n      ) {\n        const modules = path.node.init.properties;\n        for (const module of modules) {\n          const moduleId = module.key.value;\n          const moduleAst = module.value;\n          const moduleSource = generate(moduleAst).code;\n\n          try {\n            const ast = transformRequire(prettier(clearfyParams(moduleId, moduleSource)));\n\n            const mainBody = ast.program.body[0].expression.body.body;\n            const moduleCode = generate(types.Program(mainBody)).code;\n            fs.writeFileSync(\n              \".\u002Fprettier\u002Fmodules\u002F\" + moduleId + \".js\",\n              moduleCode,\n              \"utf8\"\n            );\n          } catch (e) {\n            console.log(e);\n          }\n        }\n      }\n    },\n  });\n}\n\n```\n\n最后，将处理过后的ast通过babel-generator和babel-types重新生成新的ast写入文件。\n\n这样，我们就得到了以模块id命名的独立bundle，在我的这一版中，解析出来的copilot的bundle已经非常多了，达到752个。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_7835920fc46f.png)\n\n### 2. 识别模块依赖\n\n我们解析出来的bundle，第一层函数大概是这样：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_ca13397a27b0.png)\n\n对于webpack来说，这几个参数是固定的，分别是`module`、`exports`、`require`，所以我们优先把这几个参数识别出来，进行作用域的替换，这样才可以看出模块间的依赖关系：\n\n```jsx\nfunction clearfyParams(moduleId, moduleSource) {\n  if (moduleSource.trim().startsWith(\"function\")) {\n    \u002F\u002F change `function(e, t, n) {` to `(e, t, n) => {`\n    moduleSource = moduleSource.replace(\"function\", \"\");\n    moduleSource = moduleSource.replace(\")\", \") =>\");\n  }\n\n  const moduleAst = parser.parse(moduleSource);\n  let flag = false;\n\n  traverse(moduleAst, {\n    ArrowFunctionExpression(path) {\n      if (flag) return;\n      const params = path.node.params;\n      params.forEach((param) => {\n        if (param.name === \"e\" || param.name === \"t\" || param.name === \"n\") {\n          path.scope.rename(\n            param.name,\n            {\n              e: \"module\",\n              t: \"exports\",\n              n: \"require\",\n            }[param.name]\n          );\n        }\n      });\n      flag = true;\n    },\n  });\n  return moduleAst;\n}\n```\n\n这样，我们就得到了类似这样的有require和exports的代码：\n\n```jsx\nvar r = require(12781).Stream;\nvar i = require(73837);\nfunction o() {\n  this.source = null;\n  this.dataSize = 0;\n  this.maxDataSize = 1048576;\n  this.pauseStream = !0;\n  this._maxDataSizeExceeded = !1;\n  this._released = !1;\n  this._bufferedEvents = [];\n}\nmodule.exports = o;\n```\n\n### 3. 优化压缩后的语法\n\nJS代码经过压缩后，会产生大量的逗号运算符、短路写法、三元表达式、括号闭包等等，非常阻碍阅读，这里参考了https:\u002F\u002Fgithub.com\u002Fthakkarparth007\u002Fcopilot-explorer 这个项目所做的一些逆向工作，对语法进行了一系列处理：\n\n```jsx\nfunction prettier(ast) {\n  const moduleTransformer = {\n    \u002F\u002F e.g., `(0, r.getConfig)(e, r.ConfigKey.DebugOverrideProxyUrl);`\n    \u002F\u002F gets transformed to r.getConfig(e, r.ConfigKey.DebugOverrideProxyUrl);\n    CallExpression(path) {\n      if (path.node.callee.type != \"SequenceExpression\") {\n        return;\n      }\n      if (\n        path.node.callee.expressions.length == 2 &&\n        path.node.callee.expressions[0].type == \"NumericLiteral\"\n      ) {\n        path.node.callee = path.node.callee.expressions[1];\n      }\n    },\n    ExpressionStatement(path) {\n      if (path.node.expression.type == \"SequenceExpression\") {\n        const exprs = path.node.expression.expressions;\n        let exprStmts = exprs.map((e) => {\n          return types.expressionStatement(e);\n        });\n        path.replaceWithMultiple(exprStmts);\n        return;\n      }\n      if (path.node.expression.type == \"AssignmentExpression\") {\n        \u002F\u002F handle cases like: `a = (expr1, expr2, expr3)`\n        \u002F\u002F convert to: `expr1; expr2; a = expr3;`\n        if (path.node.expression.right.type == \"SequenceExpression\") {\n          const exprs = path.node.expression.right.expressions;\n          let exprStmts = exprs.map((e) => {\n            return types.expressionStatement(e);\n          });\n          let lastExpr = exprStmts.pop();\n          path.node.expression.right = lastExpr.expression;\n          exprStmts.push(path.node);\n          path.replaceWithMultiple(exprStmts);\n          return;\n        }\n\n        \u002F\u002F handle cases like: `exports.GoodExplainableName = a;` where `a` is a function or a class\n        \u002F\u002F rename `a` to `GoodExplainableName` everywhere in the module\n        if (\n          path.node.expression.left.type == \"MemberExpression\" &&\n          path.node.expression.left.object.type == \"Identifier\" &&\n          path.node.expression.left.object.name == \"exports\" &&\n          path.node.expression.left.property.type == \"Identifier\" &&\n          path.node.expression.left.property.name != \"default\" &&\n          path.node.expression.right.type == \"Identifier\" &&\n          path.node.expression.right.name.length == 1\n        ) {\n          path.scope.rename(\n            path.node.expression.right.name,\n            path.node.expression.left.property.name\n          );\n          return;\n        }\n      }\n      if (path.node.expression.type == \"ConditionalExpression\") {\n        \u002F\u002F handle cases like: `\u003Ctest> ? c : d;`\n        \u002F\u002F convert to: `if (\u003Ctest>) { c; } else { d; }`\n        const test = path.node.expression.test;\n        const consequent = path.node.expression.consequent;\n        const alternate = path.node.expression.alternate;\n\n        const ifStmt = types.ifStatement(\n          test,\n          types.blockStatement([types.expressionStatement(consequent)]),\n          types.blockStatement([types.expressionStatement(alternate)])\n        );\n        path.replaceWith(ifStmt);\n        return;\n      }\n      if (path.node.expression.type == \"LogicalExpression\") {\n        \u002F\u002F handle cases like: `a && b;`\n        \u002F\u002F convert to: `if (a) { b; }`\n        const test = path.node.expression.left;\n        const consequent = path.node.expression.right;\n\n        const ifStmt = types.ifStatement(\n          test,\n          types.blockStatement([types.expressionStatement(consequent)]),\n          null\n        );\n        path.replaceWith(ifStmt);\n        return;\n      }\n    },\n    IfStatement(path) {\n      if (!path.node.test || path.node.test.type != \"SequenceExpression\") {\n        return;\n      }\n      const exprs = path.node.test.expressions;\n      let exprStmts = exprs.map((e) => {\n        return types.expressionStatement(e);\n      });\n      let lastExpr = exprStmts.pop();\n      path.node.test = lastExpr.expression;\n      exprStmts.push(path.node);\n      path.replaceWithMultiple(exprStmts);\n    },\n    ReturnStatement(path) {\n      if (\n        !path.node.argument ||\n        path.node.argument.type != \"SequenceExpression\"\n      ) {\n        return;\n      }\n      const exprs = path.node.argument.expressions;\n      let exprStmts = exprs.map((e) => {\n        return types.expressionStatement(e);\n      });\n      let lastExpr = exprStmts.pop();\n      let returnStmt = types.returnStatement(lastExpr.expression);\n      exprStmts.push(returnStmt);\n      path.replaceWithMultiple(exprStmts);\n    },\n    VariableDeclaration(path) {\n      \u002F\u002F change `const a = 1, b = 2;` to `const a = 1; const b = 2;`\n      if (path.node.declarations.length > 1) {\n        let newDecls = path.node.declarations.map((d) => {\n          return types.variableDeclaration(path.node.kind, [d]);\n        });\n        path.replaceWithMultiple(newDecls);\n      }\n    },\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n### 4. require的模块id取名\n\n由于压缩之后的代码，require依赖只有moduleid，已经失去了原来的文件名称，所以这里我们需要手动映射（当然也可以借助GPT）推断一下不同文件的名称，维护一个map文件，然后在ast里将模块id替换为有语义的模块名：\n\n```jsx\nfunction transformRequire(ast) {\n  const moduleTransformer = {\n    VariableDeclaration(path) {\n        if (path.node.declarations[0].init && path.node.declarations[0].init.type === \"CallExpression\") {\n            if (path.node.declarations[0].init.callee.name === \"require\") {\n                const moduleId = path.node.declarations[0].init.arguments[0].value;\n                if (NameMap[moduleId]) {\n                    const { name, path: modulePath} = NameMap[moduleId];\n\n                    path.node.declarations[0].init.arguments[0].value = '\"'+modulePath+'\"';\n                    path.scope.rename(path.node.declarations[0].id.name, name);\n                }\n              }\n        }\n      \n    },\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n至此，我们逆向相关的准备工作就完成了。\n\n## 入口分析\n\n虽然前面我们已经为逆向做了大量的工作，但实际上，逆向JS代码还是一个体力活，在有限的精力下，我们也只能手动将一些上下文压缩变量进行推断替换，尽可能还原一些核心文件的代码。\n\n入口可以很轻易找到它的模块id是91238：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_832bc9869c6c.png)\n\n经过一系列的手动优化操作，我们可以大致还原这个入口文件的原始样貌：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_ea5396e97d3c.png)\n\n在VSCode的active函数中，copilot做了大量初始化相关的工作，以及将各个模块的示例注册到context中，后续取实例就从context上下文来取。\n\n我们的核心还是想探索copilot的代码补全能力，入口文件的细节在这里就不展开了。\n\n## 代码提示入口逻辑\n\n代码提示逻辑是在`registerGhostText`中注册的：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_d3cf8de50f6f.png)\n\n在vscode中，主要通过`InlineCompletionItemProvider`来实现编辑器中的代码补全能力。\n\n整个实现的入口逻辑经过还原后大致如下：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_212d21aacba7.png)\n\n整体还是比较清晰的，它大致做了以下几件事情：\n\n- 如果用户关闭了`InlineSuggestEnable`、或者document不在处理白名单内，或者用户取消了输入，都会提前return，不进行代码提示。\n- 调用`getGhostText`方法拿到texts，这个大概就是最终会返回给用户的代码提示文本。\n- 调用`completionsFromGhostTextResults`，拿到最终的completions。这个函数比较简单，主要对文本进行了一些格式化的处理，比如处理Tab空格的问题，以及根据光标当前的位置计算出代码提示应当显示在编辑器中的坐标范围。\n\n## getGhostText核心逻辑\n\ngetGhostText是获取提示代码的核心方法，整体代码较多，我们将其拆分一下：\n\n### 1. 提取Prompt\n\n```jsx\nconst prompt = await extractprompt.extractPrompt(ctx, document, position);\n```\n\n提取prompt是一个比较复杂的操作，接下来我们单独拆一小节详细分析。\n\n### 2. 边界判断\n\n```jsx\nif (\"copilotNotAvailable\" === prompt.type) {\n    exports.ghostTextLogger.debug(\n      ctx,\n      \"Copilot not available, due to the .copilotignore settings\"\n    );\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Copilot not available due to the .copilotignore settings\",\n    };\n  }\n  if (\"contextTooShort\" === prompt.type) {\n    exports.ghostTextLogger.debug(ctx, \"Breaking, not enough context\");\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Not enough context\",\n    };\n  }\n  if (token?.isCancellationRequested) {\n    exports.ghostTextLogger.info(ctx, \"Cancelled after extractPrompt\");\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Cancelled after extractPrompt\",\n    };\n  }\n```\n\n这里的边界范围主要是三种情况：\n\n- 包含在.copilotignore里的文件\n- 上下文太少了\n- 用户已经取消了\n\n### 3. 二级缓存\n\n在copilot内部做了两层缓存处理，第一层缓存是保存了上一次的`prefix`和`suffix`：\n\n```jsx\nfunction updateGlobalCacheKey(prefix, suffix, promptKey) {\n  prefixCache = prefix;\n  suffixCache = suffix;\n  promptKeyCache = promptKey;\n}\n```\n\n这里的`promptKey`是根据`prefix`和`suffix`的内容计算得到。在copilot向后台发起请求前，如果判断这次请求的prefix和suffix还是和之前的一样，则会读取缓存的内容：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_8e27b07d0e75.png)\n\n紧接着，如果上一层的缓存没有命中，copilot还会计算二级缓存，会计算当前的prompt在不在缓存范围内：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_dfc61c68e578.png)\n\n在这里，copilot采取的缓存是LRU缓存策略，prompt默认会缓存100条：\n\n```jsx\nexports.completionCache = new s.LRUCacheMap(100);\n```\n\n而keyForPrompt函数就是一个对prefix和suffix的hash：\n\n```jsx\nexports.keyForPrompt = function (e) {\n  return r.SHA256(e.prefix + e.suffix).toString();\n};\n```\n\n### 4. 真正发起请求\n\n到了真正到向后台发送prompt请求的时候，copilot还是做了两件比较细致的事情：\n\n1. 设置`Debounce`时延\n2. 判断`contexualFilterScore`是否达到阈值\n\n首先，为了避免频繁向后台发送请求，copilot做了debounce，要知道模型计算是十分消耗算力的，因此在这个场景下，必须要做debounce。copilot的这个debounce也不是一般的，让我们看看它的实现细节：\n\n```jsx\nexports.getDebounceLimit = async function (e, t) {\n  let n;\n  if ((await e.get(r.Features).debouncePredict()) && t.measurements.contextualFilterScore) {\n    const e = t.measurements.contextualFilterScore;\n    const r = .3475;\n    const i = 7;\n    n = 25 + 250 \u002F (1 + Math.pow(e \u002F r, i));\n  } else n = await e.get(r.Features).debounceMs();\n  return n > 0 ? n : 75;\n};\n```\n\ncopilot有一个预测开关，如果这个预测开关打开，会根据当前的内容相关性评分预测当前的debounce时延，这个处理就比较高级了。当然在开关没打开的情况下默认值为75ms。\n\n其次就是`contexualFilterScore` 了，这个值代表的是上下文的评分，copilot会记录之前几次上下文有没有采纳的结果，貌似是通过一个简单的线性回归来预测当前的上下文被采纳的可能性，如果小于一定的阈值，则不会再给用户进行提示，优化用户体验。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_252041897696.png)\n\n当前版本的阈值应该是35%。这个`contextualFilterEnable`开关默认是打开的。\n\n最后，就是向后台真正发起请求了：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_a01ff042eeb0.png)\n\n### 5. 流程总结\n\n画个图总结一下copilot向后台发起请求之前做的事情：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_b2106fc8fa0f.png)\n\n## Extract核心逻辑\n\nExtract首层逻辑其实并不复杂，最终返回了prompt对象：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_10354104e41c.png)\n\n上图中用红框标出的字段来源于配置，其他的字段来自于`getPrompt`方法的返回，getPrompt是获取prompt的核心逻辑，这块我们接下来单独展开讨论，先来看看配置的问题。\n\n在copilot（VSCode）体系中，有很多配置是对接了微软的AB实验平台的，可以在文件中找到这样的模块：\n\n```jsx\nasync fetchExperiments(e, t) {\n      const n = e.get(r.Fetcher);\n      let o;\n      try {\n        o = await n.fetch(\"https:\u002F\u002Fdefault.exp-tas.com\u002Fvscode\u002Fab\", {\n          method: \"GET\",\n          headers: t\n        });\n      } catch (t) {\n        return i.ExpConfig.createFallbackConfig(e, `Error fetching ExP config: ${t}`);\n      }\n      if (!o.ok) return i.ExpConfig.createFallbackConfig(e, `ExP responded with ${o.status}`);\n      const s = await o.json(),\n        a = s.Configs.find(e => \"vscode\" === e.Id) ?? {\n          Id: \"vscode\",\n          Parameters: {}\n        },\n        c = Object.entries(a.Parameters).map(([e, t]) => e + (t ? \"\" : \"cf\"));\n      return new i.ExpConfig(a.Parameters, s.AssignmentContext, c.join(\";\"));\n    }\n```\n\n这个就是拉取了ab实验的平台，很多特性开关都是通过配置下发，copilot的相关配置也不例外。\n\n这些配置在平台没有指定的时候，都是以它的默认值。\n\n经过我实际抓包，发现我的Copilot插件配置好像没有经过配置平台单独指定，因此整个字段应该取的默认值：\n\n- `suffixPercent`，默认值为15.\n- `fimSuffixLengthThreshold`，默认值为0\n- `maxPromptCompletionTokens`，默认值为2048\n- `neighboringTabsOption`，默认值为eager\n- `neighboringSnippetTypes`，默认值为NeighboringSnippets\n- `numberOfSnippets`，默认值为4\n- `snippetPercent`，默认值为0\n- `suffixStartMode`，默认值为CursorTrimStart\n- `tokenizerName，` 默认值为cushman002\n- `indentationMinLength`，默认值为undefined\n- `indentationMaxLength`，默认值为undefined\n- `cursorContextFix`，默认值为false\n\n这些会作为Prompt的基础配置字段传给getPrompt方法。\n\n## getPrompt核心逻辑\n\n### 一些额外的配置字段\n\n在getPrompt逻辑里，首先扩充了一系列配置字段：\n\n- `languageMarker`，默认值为Top\n- `pathMarker`，默认值为Top\n- `localImportContext`，默认值为Declarations\n- `snippetPosition`，默认值为TopOfText\n- `lineEnding`，默认值为ConvertToUnix\n- `suffixMatchThreshold`，默认值为0\n- `suffixMatchCriteria`，默认值为`Levenshtein`\n- `cursorSnippetsPickingStrategy`，默认值为`CursorJaccard`\n\n### prompt的组成\n\n在Copilot中，prompt是由多种类型组合而成，可以在PromptElementKind中找到：\n\n- `BeforeCursor`，是光标前的内容\n- `AfterCursor`，是光标后的内容\n- `SimilarFile`，与当前文件相似度较高的内容\n- `ImportedFile`：import依赖\n- `LanguageMarkder`，文件开头的标记语法\n- `PathMarker`，文件的路径信息\n\n### PromptElement的优先级\n\nCopilot实现了一个优先级的辅助类，用来设置不同类型的Element优先级：\n\n```jsx\nclass Priorities {\n  constructor() {\n    this.registeredPriorities = [0, 1];\n  }\n  register(e) {\n    if (e > Priorities.TOP || e \u003C Priorities.BOTTOM) throw new Error(\"Priority must be between 0 and 1\");\n    this.registeredPriorities.push(e);\n    return e;\n  }\n  justAbove(...e) {\n    const t = Math.max(...e);\n    const n = Math.min(...this.registeredPriorities.filter(e => e > t));\n    return this.register((n + t) \u002F 2);\n  }\n  justBelow(...e) {\n    const t = Math.min(...e);\n    const n = Math.max(...this.registeredPriorities.filter(e => e \u003C t));\n    return this.register((n + t) \u002F 2);\n  }\n  between(e, t) {\n    if (this.registeredPriorities.some(n => n > e && n \u003C t) || !this.registeredPriorities.includes(e) || !this.registeredPriorities.includes(t)) throw new Error(\"Priorities must be adjacent in the list of priorities\");\n    return this.register((e + t) \u002F 2);\n  }\n}\n```\n\n可以看到justAbove和justBelow，就是生成一个比传入优先级略高或略低的优先级，保证这个优先级在目前的情况下只比传入的优先级高或低一点。\n\n在Copilot中，不同类型的优先级是这样产生的：\n\n```jsx\nconst beforeCursorPriority = priorities.justBelow(p.Priorities.TOP);\n  const languageMarkerPriority =\n    promptOpts.languageMarker === h.Always\n      ? priorities.justBelow(p.Priorities.TOP)\n      : priorities.justBelow(beforeCursorPriority);\n  const pathMarkerPriority =\n    promptOpts.pathMarker === f.Always ? priorities.justBelow(p.Priorities.TOP) : priorities.justBelow(beforeCursorPriority);\n  const importedFilePriority = priorities.justBelow(beforeCursorPriority);\n  const lowSnippetPriority = priorities.justBelow(importedFilePriority);\n  const highSnippetPriority = priorities.justAbove(beforeCursorPriority);\n```\n\n这里可以简单推断一下：\n\n- `beforeCursorPriority`，为0.5\n- `languageMarkerPriority`，为0.25\n- `pathMarkderPriority`，为0.375\n- `importedFilePriority`，为0.4375\n- `lowSnippetPriority`，为0.40625\n- `highSnippetPriority`，为0.75\n\n所以在默认的场景下，这几种类型的优先级排序为：`highSnippetPriority` > `beforeCursorPriority` > `importedFilePriority` > `lowSnippetPriority` > `pathMarkderPriority` > `languageMarkerPriority`\n\n### PromptElement主要内容\n\n1. **languageMarker和pathMarker**\n    \n    languageMarker和pathMarker是最先被放进promptWishList中的，经过前面的分析，我们知道在配置中，languageMarker和pathMarker都是有默认值的，因此下面的判断分支一定会走到：\n    \n  ```jsx\n    if (promptOpts.languageMarker !== h.NoMarker) {\n        const e = newLineEnded(r.getLanguageMarker(resourceInfo));\n        languageMarkerId = promptWishlist.append(e, p.PromptElementKind.LanguageMarker, languageMarkerPriority);\n      }\n      if (promptOpts.pathMarker !== f.NoMarker) {\n        const e = newLineEnded(r.getPathMarker(resourceInfo));\n        if (e.length > 0) {\n          pathMarkerId = promptWishlist.append(e, p.PromptElementKind.PathMarker, pathMarkerPriority);\n        }\n      }\n  ```\n    \n    这两个函数实现也比较简单，我们先来看一下getLanguageMarker：\n    \n    ```jsx\n    exports.getLanguageMarker = function (e) {\n      const {\n        languageId: t\n      } = e;\n      return -1 !== n.indexOf(t) || hasLanguageMarker(e) ? \"\" : t in r ? r[t] : comment(`Language: ${t}`, t);\n    };\n    ```\n    \n    这里首先确认了languageId，不在ignoreList当中，在copilot中，有两种语言是被排除在外的：\n    \n    ```jsx\n    const n = [\"php\", \"plaintext\"];\n    ```\n    \n    其次再看一下语言本身是否有标记语法，在这个Map中（HTML、Python、Ruby、Shell、YAML）：\n    \n    ```jsx\n    const r = {\n      html: \"\u003C!DOCTYPE html>\",\n      python: \"#!\u002Fusr\u002Fbin\u002Fenv python3\",\n      ruby: \"#!\u002Fusr\u002Fbin\u002Fenv ruby\",\n      shellscript: \"#!\u002Fbin\u002Fsh\",\n      yaml: \"# YAML data\"\n    };\n    ```\n    \n    其余的情况就返回一行注释，类似这样：\n    \n    ```jsx\n    \u002F\u002F Language: ${languageId}\n    ```\n    \n    getPathMarker逻辑更简单些，只是一行注释，标明文件路径（暂时搞不清楚这个信息给模型有什么用，可能路径里面包含了目录结构信息和文件名帮助模型更好进行推断？）：\n    \n    ```jsx\n    exports.getPathMarker = function (e) {\n      return e.relativePath ? comment(`Path: ${e.relativePath}`, e.languageId) : \"\";\n    };\n    ```\n    \n2. **localImportContext**\n    \n    localImportContext的实现要复杂一点，通过上面的配置我们可以看到这个也是默认有值的，会进到下面这个分支当中：\n    \n    ```jsx\n    if (promptOpts.localImportContext !== y.NoContext)\n        for (const e of await i.extractLocalImportContext(resourceInfo, promptOpts.fs))\n          promptWishlist.append(newLineEnded(e), p.PromptElementKind.ImportedFile, importedFilePriority);\n    ```\n    \n    extractLocalImportContext是一个异步函数，让我们看一下这里面的实现：\n    \n    ```jsx\n    const reg = \u002F^\\s*import\\s*(type|)\\s*\\{[^}]*\\}\\s*from\\s*['\"]\\.\u002Fgm;\n      exports.extractLocalImportContext = async function (resourceInfo, fs) {\n        let {\n          source: source,\n          uri: uri,\n          languageId: languageId\n        } = resourceInfo;\n        return fs && \"typescript\" === languageId ? async function (source, uri, fs) {\n          let language = \"typescript\";\n          let result = [];\n          const importEndIndex = function (source) {\n            let match;\n            let lastIndex = -1;\n            reg.lastIndex = -1;\n            do {\n                match = reg.exec(source);\n              if (match) {\n                lastIndex = reg.lastIndex + match.length;\n              }\n            } while (match);\n            if (-1 === lastIndex) return -1;\n            const nextNewLine = source.indexOf(\"\\n\", lastIndex);\n            return -1 !== nextNewLine ? nextNewLine : source.length;\n          }(source);\n          if (-1 === importEndIndex) return result;\n          source = source.substring(0, importEndIndex);\n          let ast = await i.parseTreeSitter(language, source);\n          try {\n            for (let node of function (node) {\n              let t = [];\n              for (let childNode of node.namedChildren) if (\"import_statement\" === childNode.type) {\n                t.push(childNode);\n              }\n              return t;\n            }(ast.rootNode)) {\n              let filePath = getTSFilePath(uri, node);\n              if (!filePath) continue;\n              let namedImports = parseNamedImport(node);\n              if (0 === namedImports.length) continue;\n              let exports = await getExports(filePath, language, fs);\n              for (let e of namedImports) if (exports.has(e.name)) {\n                result.push(...exports.get(e.name));\n              }\n            }\n          } finally {\n            ast.delete();\n          }\n          return result;\n        }(source, uri, fs) : [];\n      }\n    ```\n    \n    首先我们可以关注到的是，这个函数先判断了Typescript的语言，也就意味着当前版本的Copilot，只对ts文件的import依赖做了处理。\n    \n    这个函数之所以是异步的，就是这里要拿到import语句的语法树，这个过程比较复杂，copilot是使用了wasm的方式，通过tree-sitter来解析语法树的，这个过程是异步的。\n    \n    最后，copilot提取出所有的import，并且返回了所有named import对应的export代码，也就是最终索引到了依赖文件，将用到的export都作为上下文extract出来。\n    \n3. **snippets**\n    \n    snippets的处理是比较复杂的，在Copilot中，首先拿到了一个snippets：\n    \n    ```jsx\n    const snippets = [\n        ...retrievalSnippets,\n        ...(promptOpts.neighboringTabs === a.NeighboringTabsOption.None || 0 === neighborDocs.length\n          ? []\n          : await a.getNeighborSnippets(\n              resourceInfo,\n              neighborDocs,\n              promptOpts.neighboringSnippetTypes,\n              promptOpts.neighboringTabs,\n              promptOpts.cursorContextFix,\n              promptOpts.indentationMinLength,\n              promptOpts.indentationMaxLength,\n              promptOpts.snippetSelection,\n              promptOpts.snippetSelectionK,\n              lineCursorHistory,\n              promptOpts.cursorSnippetsPickingStrategy\n            )),\n      ];\n    ```\n    \n    在默认的场景下，`retrievalSnippets`是空的，而`neighboringTabs`在我们前面的分析中是`eager`，所以会通过`getNeighborSnippets`去拿到这个数组。\n    \n    注意这里传入了`neighborDocs`，这个是在extract的入口就传过来的，对应的代码是：\n    \n    ```jsx\n    let neighborDocs = [];\n          let neighborSource = new Map();\n          try {\n            const t = await u.NeighborSource.getNeighborFiles(ctx, uri, repoUserData);\n            neighborDocs = t.docs;\n            neighborSource = t.neighborSource;\n          } catch (t) {\n            telemetry.telemetryException(ctx, t, \"prompt.getPromptForSource.exception\");\n          }\n    ```\n    \n    在默认的情况下，这里拿到的fileType是`OpenTabs`，所以会默认通过VSCode拿到目前打开的tab中，包含同类型语言文件的所有内容(按访问时间排序)，对应的代码如下：\n    \n    ```jsx\n    exports.OpenTabFiles = class {\n      constructor(e, t) {\n        this.docManager = e;\n        this.neighboringLanguageType = t;\n      }\n      async truncateDocs(e, t, n, r) {\n        const o = [];\n        let s = 0;\n        for (const a of e) if (!(s + a.getText().length > i.NeighborSource.MAX_NEIGHBOR_AGGREGATE_LENGTH) && (\"file\" == a.uri.scheme && a.fileName !== t && i.considerNeighborFile(n, a.languageId, this.neighboringLanguageType) && (o.push({\n          uri: a.uri.toString(),\n          relativePath: await this.docManager.getRelativePath(a),\n          languageId: a.languageId,\n          source: a.getText()\n        }), s += a.getText().length), o.length >= r)) break;\n        return o;\n      }\n      async getNeighborFiles(e, t, n, o) {\n        let s = [];\n        const a = new Map();\n        s = await this.truncateDocs(utils2.sortByAccessTimes(this.docManager.textDocuments), e.fsPath, n, o);\n        a.set(i.NeighboringFileType.OpenTabs, s.map(e => e.uri));\n        return {\n          docs: s,\n          neighborSource: a\n        };\n      }\n    };\n    ```\n    \n    接着我们来看一下`getNeighborSnippets`的实现：\n    \n    ```jsx\n    exports.getNeighborSnippets = async function (\n      resourceInfo,\n      neighborDocs,\n      neighboringSnippetTypes,\n      neighboringTabs,\n      cursorContextFix,\n      indentationMinLength,\n      indentationMaxLength,\n      snippetSelection,\n      snippetSelectionK,\n      lineCursorHistory,\n      cursorSnippetsPickingStrategy\n    ) {\n      const options = {\n        ...exports.neighborOptionToSelection[neighboringTabs],\n      };\n      const y = (function (\n        resourceInfo,\n        neighboringSnippetTypes,\n        options,\n        cursorContextFix,\n        indentationMinLength,\n        indentationMaxLength,\n        lineCursorHistory,\n        cursorSnippetsPickingStrategy = i.CursorSnippetsPickingStrategy\n          .CursorJaccard\n      ) {\n        let d;\n        if (neighboringSnippetTypes === s.NeighboringSnippets) {\n          d =\n            void 0 !== indentationMinLength && void 0 !== indentationMaxLength\n              ? o.IndentationBasedJaccardMatcher.FACTORY(\n                  indentationMinLength,\n                  indentationMaxLength,\n                  cursorContextFix\n                )\n              : o.FixedWindowSizeJaccardMatcher.FACTORY(\n                  options.snippetLength,\n                  cursorContextFix\n                );\n        } else {\n          if (neighboringSnippetTypes === s.NeighboringFunctions) {\n            d = o.FunctionJaccardMatcher.FACTORY(\n              options.snippetLength,\n              cursorContextFix,\n              indentationMinLength,\n              indentationMaxLength\n            );\n          } else {\n            r.ok(\n              void 0 !== lineCursorHistory,\n              \"lineCursorHistory should not be undefined\"\n            );\n            d = i.CursorHistoryMatcher.FACTORY(\n              options.snippetLength,\n              lineCursorHistory,\n              cursorSnippetsPickingStrategy,\n              cursorContextFix\n            );\n          }\n        }\n        return d.to(resourceInfo);\n      })(\n        resourceInfo,\n        neighboringSnippetTypes,\n        options,\n        cursorContextFix,\n        indentationMinLength,\n        indentationMaxLength,\n        lineCursorHistory,\n        cursorSnippetsPickingStrategy\n      );\n      return 0 === options.numberOfSnippets\n        ? []\n        : (\n            await neighborDocs\n              .filter((e) => e.source.length \u003C 1e4 && e.source.length > 0)\n              .slice(0, 20)\n              .reduce(\n                async (e, t) =>\n                  (\n                    await e\n                  ).concat(\n                    (\n                      await y.findMatches(t, snippetSelection, snippetSelectionK)\n                    ).map((e) => ({\n                      relativePath: t.relativePath,\n                      ...e,\n                    }))\n                  ),\n                Promise.resolve([])\n              )\n          )\n            .filter((e) => e.score && e.snippet && e.score > options.threshold)\n            .sort((e, t) => e.score - t.score)\n            .slice(-options.numberOfSnippets);\n    };\n    ```\n    \n    在这个实现中，我们可以得到以下关键信息：\n    \n    - neighboringSnippetTypes默认为NeighboringSnippets，所以会走到`FixedWindowSizeJaccardMatcher`的逻辑里\n    - 返回值是根据neighborDocs的内容，过滤掉过小和过大文件，经过findMatchers拿到的结果\n    - 最后过滤掉score较低的，不过threshold默认为0，所以这里应该保留了所有的内容\n    - 根据score进行排序，选取较大的4条（numberOfSnippets默认为4）\n    \n    紧接着我们就来看看`FixedWindowSizeJaccardMatcher`的逻辑：\n    \n    ```jsx\n    class FixedWindowSizeJaccardMatcher extends i.WindowedMatcher {\n        constructor(resourceInfo, snippetLength, cursorContextFix) {\n          super(resourceInfo, cursorContextFix);\n          this.windowLength = snippetLength;\n          this.cursorContextFix = cursorContextFix;\n        }\n        id() {\n          return \"fixed:\" + this.windowLength;\n        }\n        getWindowsDelineations(e) {\n          return o.getBasicWindowDelineations(this.windowLength, e);\n        }\n        trimDocument(e) {\n          return e.source.slice(0, e.offset).split(\"\\n\").slice(-this.windowLength).join(\"\\n\");\n        }\n        _getCursorContextInfo(e) {\n          return r.getCursorContext(e, {\n            maxLineCount: this.windowLength,\n            cursorContextFix: this.cursorContextFix\n          });\n        }\n        similarityScore(e, t) {\n          return computeScore(e, t);\n        }\n      }\n    ```\n    \n    这里的`snippetLength` 在eager的情况下默认为60，也就意味着snippet最多不超过60行。\n    \n    这个类继承了`WindowedMatcher`，findMatches就在WindowedMatcher里：\n    \n    ```jsx\n    async findMatches(e, t = i.SnippetSelectionOption.BestMatch, n) {\n          if (t == i.SnippetSelectionOption.BestMatch) {\n            const t = await this.findBestMatch(e);\n            return t ? [t] : [];\n          }\n          return t == i.SnippetSelectionOption.TopK && (await this.findTopKMatches(e, n)) || [];\n        }\n    ```\n    \n    在这里第二个参数其实默认是undefined，所以默认走到BestMatch的分支：\n    \n    ```jsx\n    async findBestMatch(e) {\n          if (0 === e.source.length || 0 === this.referenceTokens.size) return;\n          const t = e.source.split(\"\\n\");\n          const n = this.retrieveAllSnippets(e, s.Descending);\n          return 0 !== n.length && 0 !== n[0].score ? {\n            snippet: t.slice(n[0].startLine, n[0].endLine).join(\"\\n\"),\n            semantics: o.SnippetSemantics.Snippet,\n            provider: o.SnippetProvider.NeighboringTabs,\n            ...n[0]\n          } : void 0;\n        }\n    ```\n    \n    可以看到所谓BestMatch，就是取出`retrieveAllSnippets` 的第0条结果作为snippet返回。\n    \n    ```jsx\n    retrieveAllSnippets(e, t = s.Descending) {\n          const n = [];\n          if (0 === e.source.length || 0 === this.referenceTokens.size) return n;\n          const sourceArr = e.source.split(\"\\n\");\n          const key = this.id() + \":\" + e.source;\n          const result = c.get(key) ?? [];\n          const noCache = 0 == result.length;\n          const tokens = noCache ? sourceArr.map(this.tokenizer.tokenize, this.tokenizer) : [];\n          for (const [index, [startLine, endLine]] of this.getWindowsDelineations(sourceArr).entries()) {\n            if (noCache) {\n              const e = new Set();\n              tokens.slice(startLine, endLine).forEach(t => t.forEach(e.add, e));\n              result.push(e);\n            }\n            const r = result[index];\n            const s = this.similarityScore(r, this.referenceTokens);\n            n.push({\n              score: s,\n              startLine: startLine,\n              endLine: endLine\n            });\n          }\n          if (noCache) {\n            c.put(key, result);\n          }\n          return this.sortScoredSnippets(n, t);\n        }\n    ```\n    \n    这段代码的核心是根据窗口计算出不同的代码片段与当前文件的相似度，并返回排序后的片段列表。\n    \n    首先这里做了个缓存处理，用来缓存已经计算过相似度的代码；\n    \n    然后我们重点关注下这里的几个逻辑：\n    \n    - 经过tokenize获取到当前代码片段每一行的token\n    - 通过getWindowsDelineations将代码分割成不同的小窗口（步长为1）\n    - 每个窗口的token和当前文件（referenceDoc）的token做一次相似度计算（`Jaccard`相似度）\n    \n    这三个点都非常关键，我们展开来分析下：\n    \n    1. **tokenize计算每一行的token**\n        \n        ```jsx\n        const p = new Set([\"we\", \"our\", \"you\", \"it\", \"its\", \"they\", \"them\", \"their\", \"this\", \"that\", \"these\", \"those\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"have\", \"has\", \"had\", \"having\", \"do\", \"does\", \"did\", \"doing\", \"can\", \"don\", \"t\", \"s\", \"will\", \"would\", \"should\", \"what\", \"which\", \"who\", \"when\", \"where\", \"why\", \"how\", \"a\", \"an\", \"the\", \"and\", \"or\", \"not\", \"no\", \"but\", \"because\", \"as\", \"until\", \"again\", \"further\", \"then\", \"once\", \"here\", \"there\", \"all\", \"any\", \"both\", \"each\", \"few\", \"more\", \"most\", \"other\", \"some\", \"such\", \"above\", \"below\", \"to\", \"during\", \"before\", \"after\", \"of\", \"at\", \"by\", \"about\", \"between\", \"into\", \"through\", \"from\", \"up\", \"down\", \"in\", \"out\", \"on\", \"off\", \"over\", \"under\", \"only\", \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"just\", \"now\"]);\n        const d = new Set([\"if\", \"then\", \"else\", \"for\", \"while\", \"with\", \"def\", \"function\", \"return\", \"TODO\", \"import\", \"try\", \"catch\", \"raise\", \"finally\", \"repeat\", \"switch\", \"case\", \"match\", \"assert\", \"continue\", \"break\", \"const\", \"class\", \"enum\", \"struct\", \"static\", \"new\", \"super\", \"this\", \"var\", ...p]);\n        \n        tokenize(e) {\n          return new Set(splitIntoWords(e).filter(e => !this.stopsForLanguage.has(e)));\n        }\n        \n        function splitIntoWords(e) {\n          return e.split(\u002F[^a-zA-Z0-9]\u002F).filter(e => e.length > 0);\n        }\n        ```\n        \n        可以看到处理tokens其实就是分词的过程，比普通单词分割多了一步，就是过滤常见的关键词，这些关键词不影响相似度的计算（比如if、for这种）。\n        \n    2. **getWindowsDelineations分割窗口**\n        \n        ```jsx\n        exports.getBasicWindowDelineations = function (e, t) {\n          const n = [];\n          const r = t.length;\n          if (0 == r) return [];\n          if (r \u003C e) return [[0, r]];\n          for (let t = 0; t \u003C r - e + 1; t++) n.push([t, t + e]);\n          return n;\n        };\n        ```\n        \n        `getWindowsDelineations` 本身逻辑并不复杂，就是根据传入的windowSize返回一个二维数组，这个二维数组的每一项都是一个起始行数和终止行数，它返回的是步长为1，在文件里面windowSize长度内的所有可能区间。\n        \n        得到这些区间后，会跟当前的内容（同样windowSize）进行相似度计算，选择出相似度最高的区间内容返回，这个内容就是最终的snippet。\n        \n        其中，获取当前内容的方法如下：\n        \n        ```jsx\n        get referenceTokens() {\n          if (void 0 === this._referenceTokens) {\n            this._referenceTokens = this.tokenizer.tokenize(this._getCursorContextInfo(this.referenceDoc).context);\n          }\n          return this._referenceTokens;\n        }\n        \n        exports.getCursorContext = function e(doc, opts = {}) {\n            const opts = function (e) {\n              return {\n                ...i,\n                ...e\n              };\n            }(opts);\n            const s = r.getTokenizer(opts.tokenizerName);\n            \n            if (void 0 === opts.maxTokenLength && void 0 !== opts.maxLineCount) {\n              const e = doc.source.slice(0, doc.offset).split(\"\\n\").slice(-opts.maxLineCount);\n              const n = e.join(\"\\n\");\n              return {\n                context: n,\n                lineCount: e.length,\n                tokenLength: s.tokenLength(n),\n                tokenizerName: opts.tokenizerName\n              };\n            }\n        \t\t\u002F\u002F ...\n          };\n        ```\n        \n        可以看到，这里取的是当前光标前所有内容在窗口大小的截断，这个会token分词之后与对应的相关文件token进行相似度计算。\n        \n    3. **相似度计算（`Jaccard`）**\n        \n        Copilot通过一个非常简单的**`Jaccard`** 相似度计算方法：\n        \n        ```jsx\n        function computeScore(e, t) {\n            const n = new Set();\n            e.forEach(e => {\n              if (t.has(e)) {\n                n.add(e);\n              }\n            });\n            return n.size \u002F (e.size + t.size - n.size);\n          }\n        ```\n        \n        实际上，Jaccard相似度计算公式为：\n        \n        ![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_35dc1b672d53.png)  \n      \n        这是一个非常简单的集合运算，利用交集占比来求相似度，Copilot利用两个分词集合来快速计算文本相似度。\n        \n    \n    最后，copilot调用了processSnippetsForWishlist，将snippet加入到wishList当中：\n    \n    ```jsx\n    function $() {\n        const maxSnippetLength = Math.round((promptOpts.snippetPercent \u002F 100) * promptOpts.maxPromptLength);\n        c.processSnippetsForWishlist(\n          snippets,\n          resourceInfo.languageId,\n          tokenizer,\n          promptOpts.snippetProviderOptions,\n          {\n            priorities: priorities,\n            low: lowSnippetPriority,\n            high: highSnippetPriority,\n          },\n          promptOpts.numberOfSnippets,\n          maxSnippetLength\n        ).forEach((e) => {\n          let t = p.PromptElementKind.SimilarFile;\n          if (e.provider === c.SnippetProvider.Retrieval) {\n            t = p.PromptElementKind.RetrievalSnippet;\n          } else {\n            if (e.provider == c.SnippetProvider.SymbolDef) {\n              t = p.PromptElementKind.SymbolDefinition;\n            }\n          }\n          promptWishlist.append(e.announcedSnippet, t, e.priority, e.tokens, e.normalizedScore);\n        });\n      }\n    ```\n    \n    从前面我们可以得知snippetPercent默认为0，所以这里maxSnippetLength也为0.\n    \n    我们深入看一下processSnippetsForWishList的实现：\n    \n    ```jsx\n    exports.processSnippetsForWishlist = function (snippets, languageId, tokenizer, snippetProviderOptions, priorities, numberOfSnippets, maxSnippetLength) {\n        const {\n          reserved: reserved,\n          candidates: candidates\n        } = selectSnippets(snippets, numberOfSnippets, snippetProviderOptions);\n        let d = 0;\n        let h = [];\n        let highPriorities = priorities.high;\n        let lowPriorities = priorities.low;\n        function g(snippet, r) {\n          const o = announceSnippet(snippet, languageId);\n          const c = tokenizer.tokenLength(o);\n          let l;\n          if (r + c \u003C= maxSnippetLength) {\n            l = highPriorities;\n            highPriorities = priorities.priorities.justBelow(l);\n          } else {\n            l = lowPriorities;\n            lowPriorities = priorities.priorities.justBelow(l);\n          }\n          h.push({\n            announcedSnippet: o,\n            provider: snippet.provider,\n            providerScore: snippet.providerScore,\n            normalizedScore: snippet.normalizedScore,\n            priority: l,\n            tokens: c,\n            relativePath: snippet.relativePath\n          });\n          return r + c;\n        }\n        for (const snippet of [...reserved, ...candidates]) {\n          if (h.length >= numberOfSnippets) break;\n          d = g(snippete, d);\n        }\n        l(h);\n        h.reverse();\n        return h;\n      };\n    ```\n    \n    可以看到这里maxSnippetLength影响的是Priority，在这里默认情况下就是lowPriority了。\n    \n    这里的处理其实本质上是对score进行正则化，重排序，然后返回announcedSnippet，这个announceSnippet就是最后被加入到Prompt文本里的内容：\n    \n    ```jsx\n    function announceSnippet(e, t) {\n        const n = s[e.semantics];\n        let i = (e.relativePath ? `Compare this ${n} from ${e.relativePath}:` : `Compare this ${n}:`) + \"\\n\" + e.snippet;\n        if (i.endsWith(\"\\n\")) {\n          i += \"\\n\";\n        }\n        return r.commentBlockAsSingles(i, t);\n      }\n    ```\n    \n    可以看到这里，相关文件的snippet会包裹在注释里，并在头部加上一行`Compare this …`的文案，提供给模型。\n    \n4. **beforeCursor**\n    \n    beforeCursor的代码比较简单：\n    \n    ```jsx\n    promptWishlist.appendLineForLine(source.substring(0, offset), p.PromptElementKind.BeforeCursor, beforeCursorPriority).forEach((e) =>\n          V.push(e)\n        );\n    ```\n    \n    注意这里用了appendLineForLine，而不是append，让我们看一下appendLineForLine的实现：\n    \n    ```jsx\n    appendLineForLine(text, kind, priority) {\n        const lineArr = (lines = this.convertLineEndings(text)).split(\"\\n\");\n        for (let i = 0; i \u003C lineArr.length - 1; i++) lineArr[i] += \"\\n\";\n        const lines = [];\n        lineArr.forEach((line) => {\n          if (\"\\n\" === line && lines.length > 0 && !lines[lines.length - 1].endsWith(\"\\n\\n\")) {\n            lines[lines.length - 1] += \"\\n\";\n          } else {\n            lines.push(line);\n          }\n        });\n        const result = [];\n        lines.forEach((text, index) => {\n          if (\"\" !== text) {\n            result.push(this.append(text, kind, priority));\n            if (index > 0) {\n              this.content[this.content.length - 2].requires = [\n                this.content[this.content.length - 1],\n              ];\n            }\n          }\n        });\n        return result;\n      }\n    ```\n    \n    实际上这段代码的作用就是将光标前的内容按行append，这样在token有限的情况下，能够按行保留最大的上下文。\n    \n\n### wishList的fullfill整合处理\n\n在接下来就是一系列依赖关系的处理：\n\n```jsx\nif (h.Top === promptOpts.languageMarker && V.length > 0 && void 0 !== languageMarkerId) {\n    promptWishlist.require(languageMarkerId, V[0]);\n  }\n  if (f.Top === promptOpts.pathMarker && V.length > 0 && void 0 !== pathMarkerId) {\n    if (languageMarkerId) {\n      promptWishlist.require(pathMarkerId, languageMarkerId);\n    } else {\n      promptWishlist.require(pathMarkerId, V[0]);\n    }\n  }\n  if (void 0 !== languageMarkerId && void 0 !== pathMarkerId) {\n    promptWishlist.exclude(pathMarkerId, languageMarkerId);\n  }\n```\n\n这里其实我不太理解的一点是，pathMarker和languageMarker在这个逻辑里互斥了，在我们上面分析可以看到pathMarker的优先级比languageMarker优先级高，这里加了一个exclude，也就意味着languageMarker永远不可能出现了。\n\n最后，如果是suffixPercent为0的情况下，代码到这里就直接结束了，调用fullfill方法返回最终的结果：\n\n```jsx\nif (0 === promptOpts.suffixPercent || q.length \u003C= promptOpts.fimSuffixLengthThreshold)\n    return promptWishlist.fulfill(promptOpts.maxPromptLength);\n```\n\n当然，经过我们上面的分析suffixPercent在当前版本的默认值是15，不为0，会走到suffix的逻辑。\n\n不过我们可以先看一下fullfill的处理，suffix逻辑我们就不分析了:\n\n```jsx\nfulfill(maxPromptLength) {\n    const promptChoices = new PromptChoices();\n    const promptBackground = new PromptBackground();\n    const elements = this.content.map((e, t) => ({\n      element: e,\n      index: t,\n    }));\n    elements.sort((e, t) =>\n      e.element.priority === t.element.priority\n        ? t.index - e.index\n        : t.element.priority - e.element.priority\n    );\n    const requires = new Set();\n    const excludes = new Set();\n    let lastElement;\n    const results = [];\n    let promptLength = maxPromptLength;\n    elements.forEach((e) => {\n      const element = e.element;\n      const index = e.index;\n      if (\n        promptLength >= 0 &&\n        (promptLength > 0 || void 0 === lastElement) &&\n        element.requires.every((e) => requires.has(e.id)) &&\n        !excludes.has(r.id)\n      ) {\n        let tokens = element.tokens;\n        const nextElement = (function (e, t) {\n          let n;\n          let r = 1 \u002F 0;\n          for (const i of e)\n            if (i.index > t && i.index \u003C r) {\n              n = i;\n              r = i.index;\n            }\n          return n;\n        })(results, index)?.element;\n        if (element.text.endsWith(\"\\n\\n\") && nextElement && !nextElement.text.match(\u002F^\\s\u002F)) {\n          tokens++;\n        }\n        if (promptLength >= tokens) {\n            promptLength -= tokens;\n            requires.add(r.id);\n          element.excludes.forEach((e) => excludes.add(e.id));\n          promptChoices.markUsed(element);\n          promptBackground.markUsed(element);\n          results.push(e);\n        } else {\n          if (void 0 === lastElement) {\n            lastElement = e;\n          } else {\n            promptChoices.markUnused(e.element);\n            promptBackground.markUnused(e.element);\n          }\n        }\n      } else {\n        promptChoices.markUnused(element);\n        promptBackground.markUnused(element);\n      }\n    });\n    results.sort((e, t) => e.index - t.index);\n    let prefix = results.reduce((e, t) => e + t.element.text, \"\");\n    let prefixLength = this.tokenizer.tokenLength(prefix);\n    for (; prefixLength > maxPromptLength; ) {\n      u.sort((e, t) =>\n        t.element.priority === e.element.priority\n          ? t.index - e.index\n          : t.element.priority - e.element.priority\n      );\n      const e = u.pop();\n      if (e) {\n        promptChoices.undoMarkUsed(e.element);\n        promptChoices.markUnused(e.element);\n        promptBackground.undoMarkUsed(e.element);\n        promptBackground.markUnused(e.element);\n        if (void 0 !== lastElement) {\n          promptChoices.markUnused(lastElement.element);\n          promptBackground.markUnused(lastElement.element);\n        }\n        lastElement = void 0;\n      }\n      u.sort((e, t) => e.index - t.index);\n      prefix = u.reduce((e, t) => e + t.element.text, \"\");\n      prefixLength = this.tokenizer.tokenLength(prefix);\n    }\n    const f = [...u];\n    if (void 0 !== lastElement) {\n      f.push(lastElement);\n      f.sort((e, t) => e.index - t.index);\n      const prefix = f.reduce((e, t) => e + t.element.text, \"\");\n      const prefixLength = this.tokenizer.tokenLength(prefix);\n      if (prefixLength \u003C= maxPromptLength) {\n        promptChoices.markUsed(l.element);\n        promptBackground.markUsed(l.element);\n        const promptElementRanges = new PromptElementRanges(f);\n        return {\n          prefix: prefix,\n          suffix: \"\",\n          prefixLength: prefixLength,\n          suffixLength: 0,\n          promptChoices: promptChoices,\n          promptBackground: promptBackground,\n          promptElementRanges: promptElementRanges,\n        };\n      }\n      promptChoices.markUnused(l.element);\n      promptBackground.markUnused(l.element);\n    }\n    const m = new PromptElementRanges(u);\n    return {\n      prefix: prefix,\n      suffix: \"\",\n      prefixLength: prefixLength,\n      suffixLength: 0,\n      promptChoices: promptChoices,\n      promptBackground: promptBackground,\n      promptElementRanges: m,\n    };\n  }\n```\n\n这个fullfill逻辑核心有两点：\n\n- 首先按照Priority排序（Priority相同按index），处理文本内容，这就意味着，在有限的Token下，Priority越高的文本越能被保障。\n- 输出的时候，是按照index排序的，也就是说Priority只用作处理文本的优先级，最终组合的prefix文本的顺序是按照插入wishList的先后顺序的。\n\n所以我们根据前面的分析，可以看到文本优先级是这样的：\n\n- `languageMarker`\n- `pathMarkder`\n- `importedFile`\n- `Snippet`\n- `beforeCursor`\n\n而处理优先级是这样的（优先保证的内容）：\n\n- `beforeCursor`\n- `importedFile`\n- `Snippet`\n- `pathMarkder`\n- `languageMarker`\n\n### Prompt组成的图示\n\nprompt从代码上看比较复杂，我们整体把prefix的组成画一下做个总结：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_cd0a89ed511b.png)\n\n## 抓包实验一下\n\n我们找个TS文件来试试：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_56e5471cac3f.png)\n\n可以看到，在Copilot发起的请求中，prompt包含了Path Marker和BeforeCursor两个部分，这也是我们在使用过程中绝大多数的面临场景。\n\n如果代码相关性够高，可以看到snippet的部分，比如我们拷贝了一个简单的文件：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_d02d9bb6def0.png)\n\n这个时候就会生成对应的snippet：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_a7604b1d0158.png)\n\n## 小结\n\n从Copilot中，我们可以了解到值得学习的几个核心思想：\n\n- 对于编辑器输入的边界判断，包括太少、太多、取消等等很多场景齐全的考虑\n- 缓存思想，利用多级缓存策略保护后台，模型运算本身就是一件昂贵的事情\n- prompt的设计，不仅仅包含了上下文代码，在文件解析、编辑器打开的相关代码上还做了很多\n- 利用简单的Jaccard算法计算分词后的文本相似度，能够快速决策出当前上下文相关的snippet\n- 实验特性，在Copilot中，大量的参数、优先级、设置字段都是通过实验来控制的，有一套完整的监控上报体系，帮助Copilot去调整这些参数，以达到更好的效果\n\nCopilot的逻辑比我想象中要复杂许多，逆向分析难度就更高了。耗费了很多时间在解析工作上，本文相关的工具链和代码都已上传Github，希望能够给一些有需要的同学提供帮助：\n\n[https:\u002F\u002Fgithub.com\u002Fmengjian-github\u002Fcopilot-analysis](https:\u002F\u002Fgithub.com\u002Fmengjian-github\u002Fcopilot-analysis)\n","# 花了大半个月，我终于逆向分析了Github Copilot\n\n## 背景\n\n众所周知，Github Copilot是一种基于机器学习的代码自动补全工具。它使用了来自GitHub的大量代码作为训练数据，并使用OpenAI的语言模型来生成代码。Copilot还可以学习用户的编码习惯，并根据上下文推断出正确的代码片段。\n\n在实际使用中发现大部份提示还是非常好用的，能够较为准确的推测出用户意图，甚至是基于项目其他文件的上下文进行推理。比较好奇这里是怎么做到的，于是探索了这个VSCode插件的详细实现。\n\n## 准备工作\n\n由于Copilot并没有开源，因此我们需要做一些逆向的准备。\n\n首先，找到VSCode插件的安装目录，拿到`extension.js`：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_58bb1238a2c1.png)\n\n在mac下插件目录在`~\u002F.vscode`下，我们可以拿到一个经过压缩混淆的文件：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_fe2d4b693e3d.png)\n\n### 1. 分割`webpack_modules`\n\n针对整个webpack压缩混淆的js，我们首先要将不同的bundle识别出来，分割成单个文件，以便于后续的分析。\n\n由于压缩后的代码存在很多不确定性，一开始打算尝试通过正则提取，但无论如何都有各种边界情况导致提取不正确，最简单的方法还是通过AST来提取。\n\n首先，通过babel-parser将源码解析为AST：\n\n```jsx\nconst ast = parser.parse(source);\n```\n\n然后，通过babel-traverse遍历整个AST，找到modules的变量，取出里面的值：\n\n```jsx\nfunction parseModules() {\n  traverse(ast, {\n    enter(path) {\n      if (\n        path.node.type === \"VariableDeclarator\" &&\n        path.node.id.name === \"__webpack_modules__\"\n      ) {\n        const modules = path.node.init.properties;\n        for (const module of modules) {\n          const moduleId = module.key.value;\n          const moduleAst = module.value;\n          const moduleSource = generate(moduleAst).code;\n\n          try {\n            const ast = transformRequire(prettier(clearfyParams(moduleId, moduleSource)));\n\n            const mainBody = ast.program.body[0].expression.body.body;\n            const moduleCode = generate(types.Program(mainBody)).code;\n            fs.writeFileSync(\n              \".\u002Fprettier\u002Fmodules\u002F\" + moduleId + \".js\",\n              moduleCode,\n              \"utf8\"\n            );\n          } catch (e) {\n            console.log(e);\n          }\n        }\n      },\n    },\n  });\n}\n\n```\n\n最后，将处理过后的ast通过babel-generator和babel-types重新生成新的ast写入文件。\n\n这样，我们就得到了以模块id命名的独立bundle，在我的这一版中，解析出来的copilot的bundle已经非常多了，达到752个。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_7835920fc46f.png)\n\n### 2. 识别模块依赖\n\n我们解析出来的bundle，第一层函数大概是这样：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_ca13397a27b0.png)\n\n对于webpack来说，这几个参数是固定的，分别是`module`、`exports`、`require`，所以我们优先把这几个参数识别出来，进行作用域的替换，这样才可以看出模块间的依赖关系：\n\n```jsx\nfunction clearfyParams(moduleId, moduleSource) {\n  if (moduleSource.trim().startsWith(\"function\")) {\n    \u002F\u002F change `function(e, t, n) {` to `(e, t, n) => {`\n    moduleSource = moduleSource.replace(\"function\", \"\");\n    moduleSource = moduleSource.replace(\")\", \") =>\");\n  }\n\n  const moduleAst = parser.parse(moduleSource);\n  let flag = false;\n\n  traverse(moduleAst, {\n    ArrowFunctionExpression(path) {\n      if (flag) return;\n      const params = path.node.params;\n      params.forEach((param) => {\n        if (param.name === \"e\" || param.name === \"t\" || param.name === \"n\") {\n          path.scope.rename(\n            param.name,\n            {\n              e: \"module\",\n              t: \"exports\",\n              n: \"require\",\n            }[param.name]\n          );\n        }\n      });\n      flag = true;\n    },\n  });\n  return moduleAst;\n}\n```\n\n这样，我们就得到了类似这样的有require和exports的代码：\n\n```jsx\nvar r = require(12781).Stream;\nvar i = require(73837);\nfunction o() {\n  this.source = null;\n  this.dataSize = 0;\n  this.maxDataSize = 1048576;\n  this.pauseStream = !0;\n  this._maxDataSizeExceeded = !1;\n  this._released = !1;\n  this._bufferedEvents = [];\n}\nmodule.exports = o;\n```\n\n### 3. 优化压缩后的语法\n\nJS代码经过压缩后，会产生大量的逗号运算符、短路写法、三元表达式、括号闭包等等，非常阻碍阅读，这里参考了https:\u002F\u002Fgithub.com\u002Fthakkarparth007\u002Fcopilot-explorer 这个项目所做的一些逆向工作，对语法进行了一系列处理：\n\n```jsx\nfunction prettier(ast) {\n  const moduleTransformer = {\n    \u002F\u002F e.g., `(0, r.getConfig)(e, r.ConfigKey.DebugOverrideProxyUrl);`\n    \u002F\u002F gets transformed to r.getConfig(e, r.ConfigKey.DebugOverrideProxyUrl);\n    CallExpression(path) {\n      if (path.node.callee.type != \"SequenceExpression\") {\n        return;\n      }\n      if (\n        path.node.callee.expressions.length == 2 &&\n        path.node.callee.expressions[0].type == \"NumericLiteral\"\n      ) {\n        path.node.callee = path.node.callee.expressions[1];\n      }\n    },\n    ExpressionStatement(path) {\n      if (path.node.expression.type == \"SequenceExpression\") {\n        const exprs = path.node.expression.expressions;\n        let exprStmts = exprs.map((e) => {\n          return types.expressionStatement(e);\n        });\n        path.replaceWithMultiple(exprStmts);\n        return;\n      }\n      if (path.node.expression.type == \"AssignmentExpression\") {\n        \u002F\u002F handle cases like: `a = (expr1, expr2, expr3)`\n        \u002F\u002F convert to: `expr1; expr2; a = expr3;`\n        if (path.node.expression.right.type == \"SequenceExpression\") {\n          const exprs = path.node.expression.right.expressions;\n          let exprStmts = exprs.map((e) => {\n            return types.expressionStatement(e);\n          });\n          let lastExpr = exprStmts.pop();\n          path.node.expression.right = lastExpr.expression;\n          exprStmts.push(path.node);\n          path.replaceWithMultiple(exprStmts);\n          return;\n        }\n\n        \u002F\u002F handle cases like: `exports.GoodExplainableName = a;` where `a` is a function or a class\n        \u002F\u002F rename `a` to `GoodExplainableName` everywhere in the module\n        if (\n          path.node.expression.left.type == \"MemberExpression\" &&\n          path.node.expression.left.object.type == \"Identifier\" &&\n          path.node.expression.left.object.name == \"exports\" &&\n          path.node.expression.left.property.type == \"Identifier\" &&\n          path.node.expression.left.property.name != \"default\" &&\n          path.node.expression.right.type == \"Identifier\" &&\n          path.node.expression.right.name.length == 1\n        ) {\n          path.scope.rename(\n            path.node.expression.right.name,\n            path.node.expression.left.property.name\n          );\n          return;\n        }\n      }\n      if (path.node.expression.type == \"ConditionalExpression\") {\n        \u002F\u002F handle cases like: `\u003Ctest> ? c : d;`\n        \u002F\u002F convert to: `if (\u003Ctest>) { c; } else { d; }`\n        const test = path.node.expression.test;\n        const consequent = path.node.expression.consequent;\n        const alternate = path.node.expression.alternate;\n\n        const ifStmt = types.ifStatement(\n          test,\n          types.blockStatement([types.expressionStatement(consequent)]),\n          types.blockStatement([types.expressionStatement(alternate)])\n        );\n        path.replaceWith(ifStmt);\n        return;\n      }\n      if (path.node.expression.type == \"LogicalExpression\") {\n        \u002F\u002F handle cases like: `a && b;`\n        \u002F\u002F convert to: `if (a) { b; }`\n        const test = path.node.expression.left;\n        const consequent = path.node.expression.right;\n\n        const ifStmt = types.ifStatement(\n          test,\n          types.blockStatement([types.expressionStatement(consequent)]),\n          null\n        );\n        path.replaceWith(ifStmt);\n        return;\n      }\n    },\n    IfStatement(path) {\n      if (!path.node.test || path.node.test.type != \"SequenceExpression\") {\n        return;\n      }\n      const exprs = path.node.test.expressions;\n      let exprStmts = exprs.map((e) => {\n        return types.expressionStatement(e);\n      });\n      let lastExpr = exprStmts.pop();\n      path.node.test = lastExpr.expression;\n      exprStmts.push(path.node);\n      path.replaceWithMultiple(exprStmts);\n    },\n    ReturnStatement(path) {\n      if (\n        !path.node.argument ||\n        path.node.argument.type != \"SequenceExpression\"\n      ) {\n        return;\n      }\n      const exprs = path.node.argument.expressions;\n      let exprStmts = exprs.map((e) => {\n        return types.expressionStatement(e);\n      });\n      let lastExpr = exprStmts.pop();\n      let returnStmt = types.returnStatement(lastExpr.expression);\n      exprStmts.push(returnStmt);\n      path.replaceWithMultiple(exprStmts);\n    },\n    VariableDeclaration(path) {\n      \u002F\u002F change `const a = 1, b = 2;` to `const a = 1; const b = 2;`\n      if (path.node.declarations.length > 1) {\n        let newDecls = path.node.declarations.map((d) => {\n          return types.variableDeclaration(path.node.kind, [d]);\n        });\n        path.replaceWithMultiple(newDecls);\n      }\n    },\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n### 4. require的模块id取名\n\n由于压缩之后的代码，require依赖只有moduleid，已经失去了原来的文件名称，所以这里我们需要手动映射（当然也可以借助GPT）推断一下不同文件的名称，维护一个map文件，然后在ast里将模块id替换为有语义的模块名：\n\n```jsx\nfunction transformRequire(ast) {\n  const moduleTransformer = {\n    VariableDeclaration(path) {\n        if (path.node.declarations[0].init && path.node.declarations[0].init.type === \"CallExpression\") {\n            if (path.node.declarations[0].init.callee.name === \"require\") {\n                const moduleId = path.node.declarations[0].init.arguments[0].value;\n                if (NameMap[moduleId]) {\n                    const { name, path: modulePath} = NameMap[moduleId];\n\n                    path.node.declarations[0].init.arguments[0].value = '\"'+modulePath+'\"';\n                    path.scope.rename(path.node.declarations[0].id.name, name);\n                }\n              }\n        }\n      \n    },\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n至此，我们逆向相关的准备工作就完成了。\n\n## 入口分析\n\n虽然前面我们已经为逆向做了大量的工作，但实际上，逆向JS代码还是一个体力活，在有限的精力下，我们也只能手动将一些上下文压缩变量进行推断替换，尽可能还原一些核心文件的代码。\n\n入口可以很轻易找到它的模块id是91238：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_832bc9869c6c.png)\n\n经过一系列的手动优化操作，我们可以大致还原这个入口文件的原始样貌：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_ea5396e97d3c.png)\n\n在VSCode的active函数中，copilot做了大量初始化相关的工作，以及将各个模块的示例注册到context中，后续取实例就从context上下文来取。\n\n我们的核心还是想探索copilot的代码补全能力，入口文件的细节在这里就不展开了。\n\n## 代码提示入口逻辑\n\n代码提示逻辑是在`registerGhostText`中注册的：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_d3cf8de50f6f.png)\n\n在vscode中，主要通过`InlineCompletionItemProvider`来实现编辑器中的代码补全能力。\n\n整个实现的入口逻辑经过还原后大致如下：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_212d21aacba7.png)\n\n整体还是比较清晰的，它大致做了以下几件事情：\n\n- 如果用户关闭了`InlineSuggestEnable`、或者document不在处理白名单内，或者用户取消了输入，都会提前return，不进行代码提示。\n- 调用`getGhostText`方法拿到texts，这个大概就是最终会返回给用户的代码提示文本。\n- 调用`completionsFromGhostTextResults`，拿到最终的completions。这个函数比较简单，主要对文本进行了一些格式化的处理，比如处理Tab空格的问题，以及根据光标当前的位置计算出代码提示应当显示在编辑器中的坐标范围。\n\n## getGhostText核心逻辑\n\ngetGhostText是获取提示代码的核心方法，整体代码较多，我们将其拆分一下：\n\n### 1. 提取Prompt\n\n```jsx\nconst prompt = await extractprompt.extractPrompt(ctx, document, position);\n```\n\n提取prompt是一个比较复杂的操作，接下来我们单独拆一小节详细分析。\n\n### 2. 边界判断\n\n```jsx\nif (\"copilotNotAvailable\" === prompt.type) {\n    exports.ghostTextLogger.debug(\n      ctx,\n      \"Copilot not available, due to the .copilotignore settings\"\n    );\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Copilot not available due to the .copilotignore settings\",\n    };\n  }\n  if (\"contextTooShort\" === prompt.type) {\n    exports.ghostTextLogger.debug(ctx, \"Breaking, not enough context\");\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Not enough context\",\n    };\n  }\n  if (token?.isCancellationRequested) {\n    exports.ghostTextLogger.info(ctx, \"Cancelled after extractPrompt\");\n    return {\n      type: \"abortedBeforeIssued\",\n      reason: \"Cancelled after extractPrompt\",\n    };\n  }\n```\n\n这里的边界范围主要是三种情况：\n\n- 包含在.copilotignore里的文件\n- 上下文太少了\n- 用户已经取消了\n\n### 3. 二级缓存\n\n在copilot内部做了两层缓存处理，第一层缓存是保存了上一次的`prefix`和`suffix`：\n\n```jsx\nfunction updateGlobalCacheKey(prefix, suffix, promptKey) {\n  prefixCache = prefix;\n  suffixCache = suffix;\n  promptKeyCache = promptKey;\n}\n```\n\n这里的`promptKey`是根据`prefix`和`suffix`的内容计算得到。在copilot向后台发起请求前，如果判断这次请求的prefix和suffix还是和之前的一样，则会读取缓存的内容：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_8e27b07d0e75.png)\n\n紧接着，如果上一层的缓存没有命中，copilot还会计算二级缓存，会计算当前的prompt在不在缓存范围内：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_dfc61c68e578.png)\n\n在这里，copilot采取的缓存是LRU缓存策略，prompt默认会缓存100条：\n\n```jsx\nexports.completionCache = new s.LRUCacheMap(100);\n```\n\n而keyForPrompt函数就是一个对prefix和suffix的hash：\n\n```jsx\nexports.keyForPrompt = function (e) {\n  return r.SHA256(e.prefix + e.suffix).toString();\n};\n```\n\n### 4. 真正发起请求\n\n到了真正到向后台发送prompt请求的时候，copilot还是做了两件比较细致的事情：\n\n1. 设置`Debounce`时延\n2. 判断`contexualFilterScore`是否达到阈值\n\n首先，为了避免频繁向后台发送请求，copilot做了debounce，要知道模型计算是十分消耗算力的，因此在这个场景下，必须要做debounce。copilot的这个debounce也不是一般的，让我们看看它的实现细节：\n\n```jsx\nexports.getDebounceLimit = async function (e, t) {\n  let n;\n  if ((await e.get(r.Features).debouncePredict()) && t.measurements.contextualFilterScore) {\n    const e = t.measurements.contextualFilterScore;\n    const r = .3475;\n    const i = 7;\n    n = 25 + 250 \u002F (1 + Math.pow(e \u002F r, i));\n  } else n = await e.get(r.Features).debounceMs();\n  return n > 0 ? n : 75;\n};\n```\n\ncopilot有一个预测开关，如果这个预测开关打开，会根据当前的内容相关性评分预测当前的debounce时延，这个处理就比较高级了。当然在开关没打开的情况下默认值为75ms。\n\n其次就是`contexualFilterScore` 了，这个值代表的是上下文的评分，copilot会记录之前几次上下文有没有采纳的结果，貌似是通过一个简单的线性回归来预测当前的上下文被采纳的可能性，如果小于一定的阈值，则不会再给用户进行提示，优化用户体验。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_252041897696.png)\n\n当前版本的阈值应该是35%。这个`contextualFilterEnable`开关默认是打开的。\n\n最后，就是向后台真正发起请求了：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_a01ff042eeb0.png)\n\n### 5. 流程总结\n\n画个图总结一下copilot向后台发起请求之前做的事情：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_b2106fc8fa0f.png)\n\n## Extract核心逻辑\n\nExtract首层逻辑其实并不复杂，最终返回了prompt对象：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_10354104e41c.png)\n\n上图中用红框标出的字段来源于配置，其他的字段来自于`getPrompt`方法的返回，getPrompt是获取prompt的核心逻辑，这块我们接下来单独展开讨论，先来看看配置的问题。\n\n在copilot（VSCode）体系中，有很多配置是对接了微软的AB实验平台的，可以在文件中找到这样的模块：\n\n```jsx\nasync fetchExperiments(e, t) {\n      const n = e.get(r.Fetcher);\n      let o;\n      try {\n        o = await n.fetch(\"https:\u002F\u002Fdefault.exp-tas.com\u002Fvscode\u002Fab\", {\n          method: \"GET\",\n          headers: t\n        });\n      } catch (t) {\n        return i.ExpConfig.createFallbackConfig(e, `Error fetching ExP config: ${t}`);\n      }\n      if (!o.ok) return i.ExpConfig.createFallbackConfig(e, `ExP responded with ${o.status}`);\n      const s = await o.json(),\n        a = s.Configs.find(e => \"vscode\" === e.Id) ?? {\n          Id: \"vscode\",\n          Parameters: {}\n        },\n        c = Object.entries(a.Parameters).map(([e, t]) => e + (t ? \"\" : \"cf\"));\n      return new i.ExpConfig(a.Parameters, s.AssignmentContext, c.join(\";\"));\n    }\n```\n\n这个就是拉取了ab实验的平台，很多特性开关都是通过配置下发，copilot的相关配置也不例外。\n\n这些配置在平台没有指定的时候，都是以它的默认值。\n\n经过我实际抓包，发现我的Copilot插件配置好像没有经过配置平台单独指定，因此整个字段应该取的默认值：\n\n- `suffixPercent`，默认值为15.\n- `fimSuffixLengthThreshold`，默认值为0\n- `maxPromptCompletionTokens`，默认值为2048\n- `neighboringTabsOption`，默认值为eager\n- `neighboringSnippetTypes`，默认值为NeighboringSnippets\n- `numberOfSnippets`，默认值为4\n- `snippetPercent`，默认值为0\n- `suffixStartMode`，默认值为CursorTrimStart\n- `tokenizerName，` 默认值为cushman002\n- `indentationMinLength`，默认值为undefined\n- `indentationMaxLength`，默认值为undefined\n- `cursorContextFix`，默认值为false\n\n这些会作为Prompt的基础配置字段传给getPrompt方法。\n\n## getPrompt核心逻辑\n\n### 一些额外的配置字段\n\n在getPrompt逻辑里，首先扩充了一系列配置字段：\n\n- `languageMarker`，默认值为Top\n- `pathMarker`，默认值为Top\n- `localImportContext`，默认值为Declarations\n- `snippetPosition`，默认值为TopOfText\n- `lineEnding`，默认值为ConvertToUnix\n- `suffixMatchThreshold`，默认值为0\n- `suffixMatchCriteria`，默认值为`Levenshtein`\n- `cursorSnippetsPickingStrategy`，默认值为`CursorJaccard`\n\n### prompt的组成\n\n在Copilot中，prompt是由多种类型组合而成，可以在PromptElementKind中找到：\n\n- `BeforeCursor`，是光标前的内容\n- `AfterCursor`，是光标后的内容\n- `SimilarFile`，与当前文件相似度较高的内容\n- `ImportedFile`：import依赖\n- `LanguageMarkder`，文件开头的标记语法\n- `PathMarker`，文件的路径信息\n\n### PromptElement的优先级\n\nCopilot实现了一个优先级的辅助类，用来设置不同类型的Element优先级：\n\n```jsx\nclass Priorities {\n  constructor() {\n    this.registeredPriorities = [0, 1];\n  }\n  register(e) {\n    if (e > Priorities.TOP || e \u003C Priorities.BOTTOM) throw new Error(\"Priority must be between 0 and 1\");\n    this.registeredPriorities.push(e);\n    return e;\n  }\n  justAbove(...e) {\n    const t = Math.max(...e);\n    const n = Math.min(...this.registeredPriorities.filter(e => e > t));\n    return this.register((n + t) \u002F 2);\n  }\n  justBelow(...e) {\n    const t = Math.min(...e);\n    const n = Math.max(...this.registeredPriorities.filter(e => e \u003C t));\n    return this.register((n + t) \u002F 2);\n  }\n  between(e, t) {\n    if (this.registeredPriorities.some(n => n > e && n \u003C t) || !this.registeredPriorities.includes(e) || !this.registeredPriorities.includes(t)) throw new Error(\"Priorities must be adjacent in the list of priorities\");\n    return this.register((e + t) \u002F 2);\n  }\n}\n```\n\n可以看到justAbove和justBelow，就是生成一个比传入优先级略高或略低的优先级，保证这个优先级在目前的情况下只比传入的优先级高或低一点。\n\n在Copilot中，不同类型的优先级是这样产生的：\n\n```jsx\nconst beforeCursorPriority = priorities.justBelow(p.Priorities.TOP);\n  const languageMarkerPriority =\n    promptOpts.languageMarker === h.Always\n      ? priorities.justBelow(p.Priorities.TOP)\n      : priorities.justBelow(beforeCursorPriority);\n  const pathMarkerPriority =\n    promptOpts.pathMarker === f.Always ? priorities.justBelow(p.Priorities.TOP) : priorities.justBelow(beforeCursorPriority);\n  const importedFilePriority = priorities.justBelow(beforeCursorPriority);\n  const lowSnippetPriority = priorities.justBelow(importedFilePriority);\n  const highSnippetPriority = priorities.justAbove(beforeCursorPriority);\n```\n\n这里可以简单推断一下：\n\n- `beforeCursorPriority`，为0.5\n- `languageMarkerPriority`，为0.25\n- `pathMarkderPriority`，为0.375\n- `importedFilePriority`，为0.4375\n- `lowSnippetPriority`，为0.40625\n- `highSnippetPriority`，为0.75\n\n所以在默认的场景下，这几种类型的优先级排序为：`highSnippetPriority` > `beforeCursorPriority` > `importedFilePriority` > `lowSnippetPriority` > `pathMarkderPriority` > `languageMarkerPriority`\n\n### PromptElement主要内容\n\n1. **languageMarker和pathMarker**\n\nlanguageMarker和pathMarker是最先被放进promptWishList中的，经过前面的分析，我们知道在配置中，languageMarker和pathMarker都是有默认值的，因此下面的判断分支一定会走到：\n\n  ```jsx\n    if (promptOpts.languageMarker !== h.NoMarker) {\n        const e = newLineEnded(r.getLanguageMarker(resourceInfo));\n        languageMarkerId = promptWishlist.append(e, p.PromptElementKind.LanguageMarker, languageMarkerPriority);\n      }\n      if (promptOpts.pathMarker !== f.NoMarker) {\n        const e = newLineEnded(r.getPathMarker(resourceInfo));\n        if (e.length > 0) {\n          pathMarkerId = promptWishlist.append(e, p.PromptElementKind.PathMarker, pathMarkerPriority);\n        }\n      }\n  ```\n    \n    这两个函数实现也比较简单，我们先来看一下getLanguageMarker：\n    \n    ```jsx\n    exports.getLanguageMarker = function (e) {\n      const {\n        languageId: t\n      } = e;\n      return -1 !== n.indexOf(t) || hasLanguageMarker(e) ? \"\" : t in r ? r[t] : comment(`Language: ${t}`, t);\n    };\n    ```\n    \n    这里首先确认了languageId，不在ignoreList当中，在copilot中，有两种语言是被排除在外的：\n    \n    ```jsx\n    const n = [\"php\", \"plaintext\"];\n    ```\n    \n    其次再看一下语言本身是否有标记语法，在这个Map中（HTML、Python、Ruby、Shell、YAML）：\n    \n    ```jsx\n    const r = {\n      html: \"\u003C!DOCTYPE html>\",\n      python: \"#!\u002Fusr\u002Fbin\u002Fenv python3\",\n      ruby: \"#!\u002Fusr\u002Fbin\u002Fenv ruby\",\n      shellscript: \"#!\u002Fbin\u002Fsh\",\n      yaml: \"# YAML data\"\n    };\n    ```\n    \n    其余的情况就返回一行注释，类似这样：\n    \n    ```jsx\n    \u002F\u002F Language: ${languageId}\n    ```\n    \n    getPathMarker逻辑更简单些，只是一行注释，标明文件路径（暂时搞不清楚这个信息给模型有什么用，可能路径里面包含了目录结构信息和文件名帮助模型更好进行推断？）：\n    \n    ```jsx\n    exports.getPathMarker = function (e) {\n      return e.relativePath ? comment(`Path: ${e.relativePath}`, e.languageId) : \"\";\n    };\n    ```\n    \n2. **localImportContext**\n\nlocalImportContext的实现要复杂一点，通过上面的配置我们可以看到这个也是默认有值的，会进到下面这个分支当中：\n\n    ```jsx\n    if (promptOpts.localImportContext !== y.NoContext)\n        for (const e of await i.extractLocalImportContext(resourceInfo, promptOpts.fs))\n          promptWishlist.append(newLineEnded(e), p.PromptElementKind.ImportedFile, importedFilePriority);\n    ```\n    \n    extractLocalImportContext是一个异步函数，让我们看一下这里面的实现：\n    \n    ```jsx\n    const reg = \u002F^\\s*import\\s*(type|)\\s*\\{[^}]*\\}\\s*from\\s*['\"]\\.\u002Fgm;\n      exports.extractLocalImportContext = async function (resourceInfo, fs) {\n        let {\n          source: source,\n          uri: uri,\n          languageId: languageId\n        } = resourceInfo;\n        return fs && \"typescript\" === languageId ? async function (source, uri, fs) {\n          let language = \"typescript\";\n          let result = [];\n          const importEndIndex = function (source) {\n            let match;\n            let lastIndex = -1;\n            reg.lastIndex = -1;\n            do {\n                match = reg.exec(source);\n              if (match) {\n                lastIndex = reg.lastIndex + match.length;\n              }\n            } while (match);\n            if (-1 === lastIndex) return -1;\n            const nextNewLine = source.indexOf(\"\\n\", lastIndex);\n            return -1 !== nextNewLine ? nextNewLine : source.length;\n          }(source);\n          if (-1 === importEndIndex) return result;\n          source = source.substring(0, importEndIndex);\n          let ast = await i.parseTreeSitter(language, source);\n          try {\n            for (let node of function (node) {\n              let t = [];\n              for (let childNode of node.namedChildren) if (\"import_statement\" === childNode.type) {\n                t.push(childNode);\n              }\n              return t;\n            }(ast.rootNode)) {\n              let filePath = getTSFilePath(uri, node);\n              if (!filePath) continue;\n              let namedImports = parseNamedImport(node);\n              if (0 === namedImports.length) continue;\n              let exports = await getExports(filePath, language, fs);\n              for (let e of namedImports) if (exports.has(e.name)) {\n                result.push(...exports.get(e.name));\n              }\n            }\n          } finally {\n            ast.delete();\n          }\n          return result;\n        }(source, uri, fs) : [];\n      }\n    ```\n    \n    首先我们可以关注到的是，这个函数先判断了Typescript的语言，也就意味着当前版本的Copilot，只对ts文件的import依赖做了处理。\n    \n    这个函数之所以是异步的，就是这里要拿到import语句的语法树，这个过程比较复杂，copilot是使用了wasm的方式，通过tree-sitter来解析语法树的，这个过程是异步的。\n    \n    最后，copilot提取出所有的import，并且返回了所有named import对应的export代码，也就是最终索引到了依赖文件，将用到的export都作为上下文extract出来。\n    \n3. **snippets**\n\nsnippets的处理是比较复杂的，在Copilot中，首先拿到了一个snippets：\n    \n    ```jsx\n    const snippets = [\n        ...retrievalSnippets,\n        ...(promptOpts.neighboringTabs === a.NeighboringTabsOption.None || 0 === neighborDocs.length\n          ? []\n          : await a.getNeighborSnippets(\n              resourceInfo,\n              neighborDocs,\n              promptOpts.neighboringSnippetTypes,\n              promptOpts.neighboringTabs,\n              promptOpts.cursorContextFix,\n              promptOpts.indentationMinLength,\n              promptOpts.indentationMaxLength,\n              promptOpts.snippetSelection,\n              promptOpts.snippetSelectionK,\n              lineCursorHistory,\n              promptOpts.cursorSnippetsPickingStrategy\n            )),\n      ];\n    ```\n    \n    在默认的场景下，`retrievalSnippets`是空的，而`neighboringTabs`在我们前面的分析中是`eager`，所以会通过`getNeighborSnippets`去拿到这个数组。\n    \n    注意这里传入了`neighborDocs`，这个是在extract的入口就传过来的，对应的代码是：\n    \n    ```jsx\n    let neighborDocs = [];\n          let neighborSource = new Map();\n          try {\n            const t = await u.NeighborSource.getNeighborFiles(ctx, uri, repoUserData);\n            neighborDocs = t.docs;\n            neighborSource = t.neighborSource;\n          } catch (t) {\n            telemetry.telemetryException(ctx, t, \"prompt.getPromptForSource.exception\");\n          }\n    ```\n    \n    在默认的情况下，这里拿到的fileType是`OpenTabs`，所以会默认通过VSCode拿到目前打开的tab中，包含同类型语言文件的所有内容(按访问时间排序)，对应的代码如下：\n    \n    ```jsx\n    exports.OpenTabFiles = class {\n      constructor(e, t) {\n        this.docManager = e;\n        this.neighboringLanguageType = t;\n      }\n      async truncateDocs(e, t, n, r) {\n        const o = [];\n        let s = 0;\n        for (const a of e) if (!(s + a.getText().length > i.NeighborSource.MAX_NEIGHBOR_AGGREGATE_LENGTH) && (\"file\" == a.uri.scheme && a.fileName !== t && i.considerNeighborFile(n, a.languageId, this.neighboringLanguageType) && (o.push({\n          uri: a.uri.toString(),\n          relativePath: await this.docManager.getRelativePath(a),\n          languageId: a.languageId,\n          source: a.getText()\n        }), s += a.getText().length), o.length >= r)) break;\n        return o;\n      }\n      async getNeighborFiles(e, t, n, o) {\n        let s = [];\n        const a = new Map();\n        s = await this.truncateDocs(utils2.sortByAccessTimes(this.docManager.textDocuments), e.fsPath, n, o);\n        a.set(i.NeighboringFileType.OpenTabs, s.map(e => e.uri));\n        return {\n          docs: s,\n          neighborSource: a\n        };\n      }\n    };\n    ```\n    \n    接着我们来看一下`getNeighborSnippets`的实现：\n    \n    ```jsx\n    exports.getNeighborSnippets = async function (\n      resourceInfo,\n      neighborDocs,\n      neighboringSnippetTypes,\n      neighboringTabs,\n      cursorContextFix,\n      indentationMinLength,\n      indentationMaxLength,\n      snippetSelection,\n      snippetSelectionK,\n      lineCursorHistory,\n      cursorSnippetsPickingStrategy\n    ) {\n      const options = {\n        ...exports.neighborOptionToSelection[neighboringTabs],\n      };\n      const y = (function (\n        resourceInfo,\n        neighboringSnippetTypes,\n        options,\n        cursorContextFix,\n        indentationMinLength,\n        indentationMaxLength,\n        lineCursorHistory,\n        cursorSnippetsPickingStrategy = i.CursorSnippetsPickingStrategy\n          .CursorJaccard\n      ) {\n        let d;\n        if (neighboringSnippetTypes === s.NeighboringSnippets) {\n          d =\n            void 0 !== indentationMinLength && void 0 !== indentationMaxLength\n              ? o.IndentationBasedJaccardMatcher.FACTORY(\n                  indentationMinLength,\n                  indentationMaxLength,\n                  cursorContextFix\n                )\n              : o.FixedWindowSizeJaccardMatcher.FACTORY(\n                  options.snippetLength,\n                  cursorContextFix\n                );\n        } else {\n          if (neighboringSnippetTypes === s.NeighboringFunctions) {\n            d = o.FunctionJaccardMatcher.FACTORY(\n              options.snippetLength,\n              cursorContextFix,\n              indentationMinLength,\n              indentationMaxLength\n            );\n          } else {\n            r.ok(\n              void 0 !== lineCursorHistory,\n              \"lineCursorHistory should not be undefined\"\n            );\n            d = i.CursorHistoryMatcher.FACTORY(\n              options.snippetLength,\n              lineCursorHistory,\n              cursorSnippetsPickingStrategy,\n              cursorContextFix\n            );\n          }\n        }\n        return d.to(resourceInfo);\n      })(\n        resourceInfo,\n        neighboringSnippetTypes,\n        options,\n        cursorContextFix,\n        indentationMinLength,\n        indentationMaxLength,\n        lineCursorHistory,\n        cursorSnippetsPickingStrategy\n      );\n      return 0 === options.numberOfSnippets\n        ? []\n        : (\n            await neighborDocs\n              .filter((e) => e.source.length \u003C 1e4 && e.source.length > 0)\n              .slice(0, 20)\n              .reduce(\n                async (e, t) =>\n                  (\n                    await e\n                  ).concat(\n                    (\n                      await y.findMatches(t, snippetSelection, snippetSelectionK)\n                    ).map((e) => ({\n                      relativePath: t.relativePath,\n                      ...e,\n                    }))\n                  ),\n                Promise.resolve([])\n              )\n          )\n            .filter((e) => e.score && e.snippet && e.score > options.threshold)\n            .sort((e, t) => e.score - t.score)\n            .slice(-options.numberOfSnippets);\n    };\n    ```\n    \n    在这个实现中，我们可以得到以下关键信息：\n    \n    - neighboringSnippetTypes默认为NeighboringSnippets，所以会走到`FixedWindowSizeJaccardMatcher`的逻辑里\n    - 返回值是根据neighborDocs的内容，过滤掉过小和过大文件，经过findMatchers拿到的结果\n    - 最后过滤掉score较低的，不过threshold默认为0，所以这里应该保留了所有的内容\n    - 根据score进行排序，选取较大的4条（numberOfSnippets默认为4）\n    \n    紧接着我们就来看看`FixedWindowSizeJaccardMatcher`的逻辑：\n    \n    ```jsx\n    class FixedWindowSizeJaccardMatcher extends i.WindowedMatcher {\n        constructor(resourceInfo, snippetLength, cursorContextFix) {\n          super(resourceInfo, cursorContextFix);\n          this.windowLength = snippetLength;\n          this.cursorContextFix = cursorContextFix;\n        }\n        id() {\n          return \"fixed:\" + this.windowLength;\n        }\n        getWindowsDelineations(e) {\n          return o.getBasicWindowDelineations(this.windowLength, e);\n        }\n        trimDocument(e) {\n          return e.source.slice(0, e.offset).split(\"\\n\").slice(-this.windowLength).join(\"\\n\");\n        }\n        _getCursorContextInfo(e) {\n          return r.getCursorContext(e, {\n            maxLineCount: this.windowLength,\n            cursorContextFix: this.cursorContextFix\n          });\n        }\n        similarityScore(e, t) {\n          return computeScore(e, t);\n        }\n      }\n    ```\n    \n    这里的`snippetLength` 在eager的情况下默认为60，也就意味着snippet最多不超过60行。\n    \n    这个类继承了`WindowedMatcher`，findMatches就在WindowedMatcher里：\n    \n    ```jsx\n    async findMatches(e, t = i.SnippetSelectionOption.BestMatch, n) {\n          if (t == i.SnippetSelectionOption.BestMatch) {\n            const t = await this.findBestMatch(e);\n            return t ? [t] : [];\n          }\n          return t == i.SnippetSelectionOption.TopK && (await this.findTopKMatches(e, n)) || [];\n        }\n    ```\n    \n    在这里第二个参数其实默认是undefined，所以默认走到BestMatch的分支：\n    \n    ```jsx\n    async findBestMatch(e) {\n          if (0 === e.source.length || 0 === this.referenceTokens.size) return;\n          const t = e.source.split(\"\\n\");\n          const n = this.retrieveAllSnippets(e, s.Descending);\n          return 0 !== n.length && 0 !== n[0].score ? {\n            snippet: t.slice(n[0].startLine, n[0].endLine).join(\"\\n\"),\n            semantics: o.SnippetSemantics.Snippet,\n            provider: o.SnippetProvider.NeighboringTabs,\n            ...n[0]\n          } : void 0;\n        }\n    ```\n    \n    可以看到所谓BestMatch，就是取出`retrieveAllSnippets` 的第0条结果作为snippet返回。\n    \n    ```jsx\n    retrieveAllSnippets(e, t = s.Descending) {\n          const n = [];\n          if (0 === e.source.length || 0 === this.referenceTokens.size) return n;\n          const sourceArr = e.source.split(\"\\n\");\n          const key = this.id() + \":\" + e.source;\n          const result = c.get(key) ?? [];\n          const noCache = 0 == result.length;\n          const tokens = noCache ? sourceArr.map(this.tokenizer.tokenize, this.tokenizer) : [];\n          for (const [index, [startLine, endLine]] of this.getWindowsDelineations(sourceArr).entries()) {\n            if (noCache) {\n              const e = new Set();\n              tokens.slice(startLine, endLine).forEach(t to add to the set);\n              result.push(e);\n            }\n            const r = result[index];\n            const s = this.similarityScore(r, this.referenceTokens);\n            n.push({\n              score: s,\n              startLine: startLine,\n              endLine: endLine\n            });\n          }\n          if (noCache) {\n            c.put(key, result);\n          }\n          return this.sortScoredSnippets(n, t);\n        }\n    ```\n    \n    这段代码的核心是根据窗口计算出不同的代码片段与当前文件的相似度，并返回排序后的片段列表。\n    \n    首先这里做了个缓存处理，用来缓存已经计算过相似度的代码；\n    \n    然后我们重点关注下这里的几个逻辑：\n    \n    - 经过tokenize获取到当前代码片段每一行的token\n    - 通过getWindowsDelineations将代码分割成不同的小窗口（步长为1）\n    - 每个窗口的token和当前文件（referenceDoc）的token做一次相似度计算（`Jaccard`相似度）\n    \n    这三个点都非常关键，我们展开来分析下：\n    \n    1. **tokenize计算每一行的token**\n        \n        ```jsx\n        const p = new Set([\"we\", \"our\", \"you\", \"it\", \"its\", \"they\", \"them\", \"their\", \"this\", \"that\", \"these\", \"those\", \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"have\", \"has\", \"had\", \"having\", \"do\", \"does\", \"did\", \"doing\", \"can\", \"don\", \"t\", \"s\", \"will\", \"would\", \"should\", \"what\", \"which\", \"who\", \"when\", \"where\", \"why\", \"how\", \"a\", \"an\", \"the\", \"and\", \"or\", \"not\", \"no\", \"but\", \"because\", \"as\", \"until\", \"again\", \"further\", \"then\", \"once\", \"here\", \"there\", \"all\", \"any\", \"both\", \"each\", \"few\", \"more\", \"most\", \"other\", \"some\", \"such\", \"above\", \"below\", \"to\", \"during\", \"before\", \"after\", \"of\", \"at\", \"by\", \"about\", \"between\", \"into\", \"through\", \"from\", \"up\", \"down\", \"in\", \"out\", \"on\", \"off\", \"over\", \"under\", \"only\", \"own\", \"same\", \"so\", \"than\", \"too\", \"very\", \"just\", \"now\"]);\n        const d = new Set([\"if\", \"then\", \"else\", \"for\", \"while\", \"with\", \"def\", \"function\", \"return\", \"TODO\", \"import\", \"try\", \"catch\", \"raise\", \"finally\", \"repeat\", \"switch\", \"case\", \"match\", \"assert\", \"continue\", \"break\", \"const\", \"class\", \"enum\", \"struct\", \"static\", \"new\", \"super\", \"this\", \"var\", ...p]);\n        \n        tokenize(e) {\n          return new Set(splitIntoWords(e).filter(e => !this.stopsForLanguage.has(e)));\n        }\n        \n        function splitIntoWords(e) {\n          return e.split(\u002F[^a-zA-Z0-9]\u002F).filter(e => e.length > 0);\n        }\n        ```\n        \n        可以看到处理tokens其实就是分词的过程，比普通单词分割多了一步，就是过滤常见的关键词，这些关键词不影响相似度的计算（比如if、for这种）。\n        \n    2. **getWindowsDelineations分割窗口**\n        \n        ```jsx\n        exports.getBasicWindowDelineations = function (e, t) {\n          const n = [];\n          const r = t.length;\n          if (0 == r) return [];\n          if (r \u003C e) return [[0, r]];\n          for (let t = 0; t \u003C r - e + 1; t++) n.push([t, t + e]);\n          return n;\n        };\n        ```\n        \n        `getWindowsDelineations` 本身逻辑并不复杂，就是根据传入的windowSize返回一个二维数组，这个二维数组的每一项都是一个起始行数和终止行数，它返回的是步长为1，在文件里面windowSize长度内的所有可能区间。\n        \n        得到这些区间后，会跟当前的内容（同样windowSize）进行相似度计算，选择出相似度最高的区间内容返回，这个内容就是最终的snippet。\n        \n        其中，获取当前内容的方法如下：\n        \n        ```jsx\n        get referenceTokens() {\n          if (void 0 === this._referenceTokens) {\n            this._referenceTokens = this.tokenizer.tokenize(this._getCursorContextInfo(this.referenceDoc).context);\n          }\n          return this._referenceTokens;\n        }\n        \n        exports.getCursorContext = function e(doc, opts = {}) {\n            const opts = function (e) {\n              return {\n                ...i,\n                ...e\n              };\n           }(opts);\n            const s = r.getTokenizer(opts.tokenizerName);\n            \n            if (void 0 === opts.maxTokenLength && void 0 !== opts.maxLineCount) {\n              const e = doc.source.slice(0, doc.offset).split(\"\\n\").slice(-opts.maxLineCount);\n              const n = e.join(\"\\n\");\n              return {\n                context: n,\n                lineCount: e.length,\n                tokenLength: s.tokenLength(n),\n                tokenizerName: opts.tokenizerName\n              };\n            }\n        \t\t\u002F\u002F ...\n          };\n        ```\n        \n        可以看到，这里取的是当前光标前所有内容在窗口大小的截断，这个会token分词之后与对应的相关文件token进行相似度计算。\n        \n    3. **相似度计算（`Jaccard`）**\n        \n        Copilot通过一个非常简单的**`Jaccard`** 相似度计算方法：\n        \n        ```jsx\n        function computeScore(e, t) {\n            const n = new Set();\n            e.forEach(e => {\n              if (t.has(e)) {\n                n.add(e);\n              }\n            });\n            return n.size \u002F (e.size + t.size - n.size);\n          }\n        ```\n        \n        实际上，Jaccard相似度计算公式为：\n        \n        ![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_35dc1b672d53.png)  \n      \n        这是一个非常简单的集合运算，利用交集占比来求相似度，Copilot利用两个分词集合来快速计算文本相似度。\n        \n    \n    最后，copilot调用了processSnippetsForWishlist，将snippet加入到wishList当中：\n    \n    ```jsx\n    function $() {\n        const maxSnippetLength = Math.round((promptOpts.snippetPercent \u002F 100) * promptOpts.maxPromptLength);\n        c.processSnippetsForWishlist(\n          snippets,\n          resourceInfo.languageId,\n          tokenizer,\n          promptOpts.snippetProviderOptions,\n          {\n            priorities: priorities,\n            low: lowSnippetPriority,\n            high: highSnippetPriority,\n          },\n          promptOpts.numberOfSnippets,\n          maxSnippetLength\n        ).forEach((e) => {\n          let t = p.PromptElementKind.SimilarFile;\n          if (e.provider === c.SnippetProvider.Retrieval) {\n            t = p.PromptElementKind.RetrievalSnippet;\n          } else {\n            if (e.provider == c.SnippetProvider.SymbolDef) {\n              t = p.PromptElementKind.SymbolDefinition;\n            }\n          }\n          promptWishlist.append(e.announcedSnippet, t, e.priority, e.tokens, e.normalizedScore);\n        });\n      }\n    ```\n    \n    从前面我们可以得知snippetPercent默认为0，所以这里maxSnippetLength也为0.\n    \n    我们深入看一下processSnippetsForWishList的实现：\n    \n    ```jsx\n    exports.processSnippetsForWishlist = function (snippets, languageId, tokenizer, snippetProviderOptions, priorities, numberOfSnippets, maxSnippetLength) {\n        const {\n          reserved: reserved,\n          candidates: candidates\n        } = selectSnippets(snippets, numberOfSnippets, snippetProviderOptions);\n        let d = 0;\n        let h = [];\n        let highPriorities = priorities.high;\n        let lowPriorities = priorities.low;\n        function g(snippet, r) {\n          const o = announceSnippet(snippet, languageId);\n          const c = tokenizer.tokenLength(o);\n          let l;\n          if (r + c \u003C= maxSnippetLength) {\n            l = highPriorities;\n            highPriorities = priorities.priorities.justBelow(l);\n          } else {\n            l = lowPriorities;\n            lowPriorities = priorities.priorities.justBelow(l);\n          }\n          h.push({\n            announcedSnippet: o,\n            provider: snippet.provider,\n            providerScore: snippet.providerScore,\n            normalizedScore: snippet.normalizedScore,\n            priority: l,\n            tokens: c,\n            relativePath: snippet.relativePath\n          });\n          return r + c;\n        }\n        for (const snippet of [...reserved, ...candidates]) {\n          if (h.length >= numberOfSnippets) break;\n          d = g(snippete, d);\n        }\n        l(h);\n        h.reverse();\n        return h;\n      };\n    ```\n    \n    可以看到这里maxSnippetLength影响的是Priority，在这里默认情况下就是lowPriority了。\n    \n    这里的处理其实本质上是对score进行正则化，重排序，然后返回announcedSnippet，这个announceSnippet就是最后被加入到Prompt文本里的内容：\n    \n    ```jsx\n    function announceSnippet(e, t) {\n        const n = s[e.semantics];\n        let i = (e.relativePath ? `Compare this ${n} from ${e.relativePath}:` : `Compare this ${n}:`) + \"\\n\" + e.snippet;\n        if (i.endsWith(\"\\n\")) {\n          i += \"\\n\";\n        }\n        return r.commentBlockAsSingles(i, t);\n      }\n    ```\n    \n    可以看到这里，相关文件的snippet会包裹在注释里，并在头部加上一行`Compare this …`的文案，提供给模型。\n    \n4. **beforeCursor**\n\nbeforeCursor的代码比较简单：\n\n    ```jsx\n    promptWishlist.appendLineForLine(source.substring(0, offset), p.PromptElementKind.BeforeCursor, beforeCursorPriority).forEach((e) =>\n          V.push(e)\n        );\n    ```\n    \n    注意这里用了appendLineForLine，而不是append，让我们看一下appendLineForLine的实现：\n    \n    ```jsx\n    appendLineForLine(text, kind, priority) {\n        const lineArr = (lines = this.convertLineEndings(text)).split(\"\\n\");\n        for (let i = 0; i \u003C lineArr.length - 1; i++) lineArr[i] += \"\\n\";\n        const lines = [];\n        lineArr.forEach((line) => {\n          if (\"\\n\" === line && lines.length > 0 && !lines[lines.length - 1].endsWith(\"\\n\\n\")) {\n            lines[lines.length - 1] += \"\\n\";\n          } else {\n            lines.push(line);\n          }\n        });\n        const result = [];\n        lines.forEach((text, index) => {\n          if (\"\" !== text) {\n            result.push(this.append(text, kind, priority));\n            if (index > 0) {\n              this.content[this.content.length - 2].requires = [\n                this.content[this.content.length - 1],\n              ];\n            }\n          }\n        });\n        return result;\n      }\n    ```\n    \n    实际上这段代码的作用就是将光标前的内容按行append，这样在token有限的情况下，能够按行保留最大的上下文。\n\n### wishList 的 fullfill 整合处理\n\n接下来是一系列依赖关系的处理：\n\n```jsx\nif (h.Top === promptOpts.languageMarker && V.length > 0 && void 0 !== languageMarkerId) {\n    promptWishlist.require(languageMarkerId, V[0]);\n  }\n  if (f.Top === promptOpts.pathMarker && V.length > 0 && void 0 !== pathMarkerId) {\n    if (languageMarkerId) {\n      promptWishlist.require(pathMarkerId, languageMarkerId);\n    } else {\n      promptWishlist.require(pathMarkerId, V[0]);\n    }\n  }\n  if (void 0 !== languageMarkerId && void 0 !== pathMarkerId) {\n    promptWishlist.exclude(pathMarkerId, languageMarkerId);\n  }\n```\n\n这里有一点我不太理解：pathMarker 和 languageMarker 在这个逻辑中是互斥的。从我们之前的分析可以看出，pathMarker 的优先级高于 languageMarker，而这里的 exclude 操作意味着 languageMarker 永远不会出现。\n\n最后，如果 suffixPercent 为 0，代码到这里就直接结束了，调用 fulfill 方法返回最终的结果：\n\n```jsx\nif (0 === promptOpts.suffixPercent || q.length \u003C= promptOpts.fimSuffixLengthThreshold)\n    return promptWishlist.fulfill(promptOpts.maxPromptLength);\n```\n\n当然，根据我们之前的分析，suffixPercent 在当前版本中的默认值是 15，不为 0，因此会进入 suffix 的逻辑。\n\n不过我们可以先看一下 fulfill 的处理流程，suffix 的逻辑暂且不表：\n\n```jsx\nfulfill(maxPromptLength) {\n    const promptChoices = new PromptChoices();\n    const promptBackground = new PromptBackground();\n    const elements = this.content.map((e, t) => ({\n      element: e,\n      index: t,\n    }));\n    elements.sort((e, t) =>\n      e.element.priority === t.element.priority\n        ? t.index - e.index\n        : t.element.priority - e.element.priority\n    );\n    const requires = new Set();\n    const excludes = new Set();\n    let lastElement;\n    const results = [];\n    let promptLength = maxPromptLength;\n    elements.forEach((e) => {\n      const element = e.element;\n      const index = e.index;\n      if (\n        promptLength >= 0 &&\n        (promptLength > 0 || void 0 === lastElement) &&\n        element.requires.every((e) => requires.has(e.id)) &&\n        !excludes.has(r.id)\n      ) {\n        let tokens = element.tokens;\n        const nextElement = (function (e, t) {\n          let n;\n          let r = 1 \u002F 0;\n          for (const i of e)\n            if (i.index > t && i.index \u003C r) {\n              n = i;\n              r = i.index;\n            }\n          return n;\n        })(results, index)?.element;\n        if (element.text.endsWith(\"\\n\\n\") && nextElement && !nextElement.text.match(\u002F^\\s\u002F)) {\n          tokens++;\n        }\n        if (promptLength >= tokens) {\n            promptLength -= tokens;\n            requires.add(r.id);\n          element.excludes.forEach((e) => excludes.add(e.id));\n          promptChoices.markUsed(element);\n          promptBackground.markUsed(element);\n          results.push(e);\n        } else {\n          if (void 0 === lastElement) {\n            lastElement = e;\n          } else {\n            promptChoices.markUnused(e.element);\n            promptBackground.markUnused(e.element);\n          }\n        }\n      } else {\n        promptChoices.markUnused(element);\n        promptBackground.markUnused(element);\n      }\n    });\n    results.sort((e, t) => e.index - t.index);\n    let prefix = results.reduce((e, t) => e + t.element.text, \"\");\n    let prefixLength = this.tokenizer.tokenLength(prefix);\n    for (; prefixLength > maxPromptLength; ) {\n      u.sort((e, t) =>\n        t.element.priority === e.element.priority\n          ? t.index - e.index\n          : t.element.priority - e.element.priority\n      );\n      const e = u.pop();\n      if (e) {\n        promptChoices.undoMarkUsed(e.element);\n        promptChoices.markUnused(e.element);\n        promptBackground.undoMarkUsed(e.element);\n        promptBackground.markUnused(e.element);\n        if (void 0 !== lastElement) {\n          promptChoices.markUnused(lastElement.element);\n          promptBackground.markUnused(lastElement.element);\n        }\n        lastElement = void 0;\n      }\n      u.sort((e, t) => e.index - t.index);\n      prefix = u.reduce((e, t) => e + t.element.text, \"\");\n      prefixLength = this.tokenizer.tokenLength(prefix);\n    }\n    const f = [...u];\n    if (void 0 !== lastElement) {\n      f.push(lastElement);\n      f.sort((e, t) => e.index - t.index);\n      const prefix = f.reduce((e, t) => e + t.element.text, \"\");\n      const prefixLength = this.tokenizer.tokenLength(prefix);\n      if (prefixLength \u003C= maxPromptLength) {\n        promptChoices.markUsed(l.element);\n        promptBackground.markUsed(l.element);\n        const promptElementRanges = new PromptElementRanges(f);\n        return {\n          prefix: prefix,\n          suffix: \"\",\n          prefixLength: prefixLength,\n          suffixLength: 0,\n          promptChoices: promptChoices,\n          promptBackground: promptBackground,\n          promptElementRanges: promptElementRanges,\n        };\n      }\n      promptChoices.markUnused(l.element);\n      promptBackground.markUnused(l.element);\n    }\n    const m = new PromptElementRanges(u);\n    return {\n      prefix: prefix,\n      suffix: \"\",\n      prefixLength: prefixLength,\n      suffixLength: 0,\n      promptChoices: promptChoices,\n      promptBackground: promptBackground,\n      promptElementRanges: m,\n    };\n  }\n```\n\n这个 fulfill 逻辑的核心有两点：\n\n- 首先按照 Priority 排序（Priority 相同按 index），处理文本内容。这意味着，在 Token 数量有限的情况下，Priority 越高的文本越能被优先保留。\n- 输出时，文本按照插入 wishList 的先后顺序排序。也就是说，Priority 只用于决定文本的处理顺序，最终组合成的 prefix 文本顺序则取决于它们被加入 wishList 的时间顺序。\n\n因此，结合前面的分析，我们可以得出文本的优先级顺序如下：\n\n- `languageMarker`\n- `pathMarker`\n- `importedFile`\n- `Snippet`\n- `beforeCursor`\n\n而处理优先级则是：\n\n- `beforeCursor`\n- `importedFile`\n- `Snippet`\n- `pathMarker`\n- `languageMarker`\n\n### Prompt 组成的示意图\n\n从代码上看，prompt 的结构比较复杂。为了总结一下 prefix 的组成，我们可以将其整体画出来：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_cd0a89ed511b.png)\n\n## 抓包实验一下\n\n我们找一个 TS 文件来试试：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_56e5471cac3f.png)\n\n可以看到，在 Copilot 发起的请求中，prompt 包含了 Path Marker 和 BeforeCursor 两部分，这也是我们在使用过程中最常见的场景。\n\n如果代码的相关性足够高，我们还会看到 snippet 的部分。比如我们复制了一个简单的文件：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_d02d9bb6def0.png)\n\n这时就会生成对应的 snippet：\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_readme_a7604b1d0158.png)\n\n## 小结\n\n通过分析 Copilot，我们可以学到几个核心思想：\n\n- 对编辑器输入的各种边界情况进行了全面考虑，包括输入过少、过多、取消等众多场景。\n- 运用了缓存思想，通过多级缓存策略保护后端服务，因为模型运算本身成本很高。\n- prompt 的设计不仅包含了上下文代码，还在文件解析和编辑器打开的相关代码上做了很多优化。\n- 利用简单的 Jaccard 算法计算分词后的文本相似度，从而快速决策出与当前上下文相关的 snippet。\n- 实验驱动的设计理念：Copilot 中的大量参数、优先级和设置字段都是通过实验来调整的，并且有一套完整的监控上报体系，帮助团队不断优化这些参数以达到更好的效果。\n\n总的来说，Copilot 的逻辑比我想象的要复杂得多，逆向分析的难度也更高。我在解析这部分代码上花费了大量时间。本文中提到的工具链和相关代码都已经上传到 GitHub，希望能对有需要的同学有所帮助：\n\n[https:\u002F\u002Fgithub.com\u002Fmengjian-github\u002Fcopilot-analysis](https:\u002F\u002Fgithub.com\u002Fmengjian-github\u002Fcopilot-analysis)","# copilot-analysis 快速上手指南\n\n`copilot-analysis` 并非一个直接运行的 AI 工具，而是一套用于**逆向分析 GitHub Copilot VSCode 插件**的代码处理流程。本指南旨在帮助开发者还原混淆后的 Copilot 源码，以便研究其代码补全逻辑、Prompt 构建机制及缓存策略。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**: macOS, Linux 或 Windows (推荐 macOS\u002FLinux，路径结构与原文示例更契合)\n*   **运行时**: Node.js (建议 v14+)\n*   **核心依赖**:\n    *   `@babel\u002Fparser`: 解析 JS 源码为 AST\n    *   `@babel\u002Ftraverse`: 遍历和操作 AST\n    *   `@babel\u002Fgenerator`: 将 AST 重新生成代码\n    *   `@babel\u002Ftypes`: 构建和验证 AST 节点\n    *   `prettier`: 代码格式化辅助\n*   **目标文件**: 已安装的 GitHub Copilot VSCode 插件源码 (`extension.js`)\n\n> **提示**: 国内开发者可使用淘宝镜像源加速依赖安装：\n> ```bash\n> npm config set registry https:\u002F\u002Fregistry.npmmirror.com\n> ```\n\n## 安装与源码获取\n\n由于 Copilot 未开源，首先需要从本地 VSCode 插件目录获取混淆后的源码。\n\n### 1. 定位插件文件\n找到 VSCode 插件安装目录中的 `extension.js` 文件：\n*   **macOS**: `~\u002F.vscode\u002Fextensions\u002Fgithub.copilot-\u003Cversion>\u002Fdist\u002Fextension.js`\n*   **Windows**: `%USERPROFILE%\\.vscode\\extensions\\github.copilot-\u003Cversion>\\dist\\extension.js`\n*   **Linux**: `~\u002F.vscode\u002Fextensions\u002Fgithub.copilot-\u003Cversion>\u002Fdist\u002Fextension.js`\n\n### 2. 初始化分析项目\n克隆或创建您的分析项目，并安装必要的 Babel 依赖：\n\n```bash\nmkdir copilot-analysis && cd copilot-analysis\nnpm init -y\nnpm install @babel\u002Fparser @babel\u002Ftraverse @babel\u002Fgenerator @babel\u002Ftypes prettier\n```\n\n将上一步获取的 `extension.js` 复制到项目根目录。\n\n## 基本使用：四步还原源码\n\n本工具的核心逻辑是通过 AST 变换将压缩混淆的 Webpack bundle 还原为可读代码。请按顺序执行以下四个步骤。\n\n### 步骤 1: 分割 Webpack Modules\n使用 `babel-parser` 解析源码，通过 `babel-traverse` 提取 `__webpack_modules__` 变量，将单个大文件分割为独立的模块文件。\n\n```javascript\nconst parser = require(\"@babel\u002Fparser\");\nconst traverse = require(\"@babel\u002Ftraverse\").default;\nconst generate = require(\"@babel\u002Fgenerator\").default;\nconst fs = require(\"fs\");\n\n\u002F\u002F 读取混淆源码\nconst source = fs.readFileSync(\".\u002Fextension.js\", \"utf8\");\nconst ast = parser.parse(source);\n\nfunction parseModules() {\n  traverse(ast, {\n    enter(path) {\n      if (\n        path.node.type === \"VariableDeclarator\" &&\n        path.node.id.name === \"__webpack_modules__\"\n      ) {\n        const modules = path.node.init.properties;\n        for (const module of modules) {\n          const moduleId = module.key.value;\n          const moduleAst = module.value;\n          const moduleSource = generate(moduleAst).code;\n          \n          \u002F\u002F 此处需调用后续的清参和美化函数\n          \u002F\u002F const processedAst = transformRequire(prettier(clearfyParams(moduleId, moduleSource)));\n          \u002F\u002F ...写入文件逻辑\n          console.log(`Extracted module: ${moduleId}`);\n        }\n      }\n    },\n  });\n}\n\nparseModules();\n```\n*执行后，您将获得数百个以 Module ID 命名的独立 JS 文件。*\n\n### 步骤 2: 识别模块依赖 (作用域替换)\nWebpack 打包后的函数参数通常为 `(e, t, n)`，需将其重命名为 `(module, exports, require)` 以理清依赖关系。\n\n```javascript\nfunction clearfyParams(moduleId, moduleSource) {\n  if (moduleSource.trim().startsWith(\"function\")) {\n    moduleSource = moduleSource.replace(\"function\", \"\");\n    moduleSource = moduleSource.replace(\")\", \") =>\");\n  }\n\n  const moduleAst = parser.parse(moduleSource);\n  let flag = false;\n\n  traverse(moduleAst, {\n    ArrowFunctionExpression(path) {\n      if (flag) return;\n      const params = path.node.params;\n      params.forEach((param) => {\n        if (param.name === \"e\" || param.name === \"t\" || param.name === \"n\") {\n          path.scope.rename(\n            param.name,\n            {\n              e: \"module\",\n              t: \"exports\",\n              n: \"require\",\n            }[param.name]\n          );\n        }\n      });\n      flag = true;\n    },\n  });\n  return moduleAst;\n}\n```\n\n### 步骤 3: 优化压缩语法\n移除逗号运算符、短路写法、三元表达式等混淆结构，提升代码可读性。\n\n```javascript\nfunction prettier(ast) {\n  const moduleTransformer = {\n    CallExpression(path) {\n      \u002F\u002F 处理 (0, func)(args) -> func(args)\n      if (path.node.callee.type != \"SequenceExpression\") return;\n      if (\n        path.node.callee.expressions.length == 2 &&\n        path.node.callee.expressions[0].type == \"NumericLiteral\"\n      ) {\n        path.node.callee = path.node.callee.expressions[1];\n      }\n    },\n    ExpressionStatement(path) {\n      \u002F\u002F 处理三元表达式转为 if-else\n      if (path.node.expression.type == \"ConditionalExpression\") {\n        const test = path.node.expression.test;\n        const consequent = path.node.expression.consequent;\n        const alternate = path.node.expression.alternate;\n        const ifStmt = types.ifStatement(\n          test,\n          types.blockStatement([types.expressionStatement(consequent)]),\n          types.blockStatement([types.expressionStatement(alternate)])\n        );\n        path.replaceWith(ifStmt);\n        return;\n      }\n      \u002F\u002F 处理逻辑表达式 a && b -> if(a){b}\n      if (path.node.expression.type == \"LogicalExpression\") {\n         \u002F\u002F ... (参考原文逻辑实现)\n      }\n    },\n    \u002F\u002F ...其他转换器 (VariableDeclaration, ReturnStatement 等)\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n### 步骤 4: 语义化模块名称\n建立 Module ID 到文件名的映射表 (`NameMap`)，将 `require(12345)` 替换为 `require(\".\u002Futils\u002Fstream\")` 等形式。\n\n```javascript\n\u002F\u002F 假设 NameMap 已通过人工分析或 AI 辅助构建完成\nconst NameMap = {\n  \"12781\": { name: \"Stream\", path: \".\u002Finternal\u002Fstream\" },\n  \"73837\": { name: \"Config\", path: \".\u002Fconfig\u002Findex\" }\n};\n\nfunction transformRequire(ast) {\n  const moduleTransformer = {\n    VariableDeclaration(path) {\n        if (path.node.declarations[0].init && path.node.declarations[0].init.type === \"CallExpression\") {\n            if (path.node.declarations[0].init.callee.name === \"require\") {\n                const moduleId = path.node.declarations[0].init.arguments[0].value;\n                if (NameMap[moduleId]) {\n                    const { name, path: modulePath} = NameMap[moduleId];\n                    \u002F\u002F 替换 require 参数为语义化路径\n                    path.node.declarations[0].init.arguments[0].value = '\"'+modulePath+'\"';\n                    \u002F\u002F 重命名接收变量\n                    path.scope.rename(path.node.declarations[0].id.name, name);\n                }\n              }\n        }\n    },\n  };\n  traverse(ast, moduleTransformer);\n  return ast;\n}\n```\n\n## 核心逻辑分析指引\n\n完成上述还原步骤后，您可以重点关注以下入口进行深入研究：\n\n1.  **插件入口**: 搜索 Module ID `91238` (版本号不同可能变化)，查看 `activate` 函数中的初始化逻辑。\n2.  **代码提示注册**: 查找 `registerGhostText`，这是 `InlineCompletionItemProvider` 的注册点。\n3.  **核心补全流程**:\n    *   `getGhostText`: 获取提示文本的核心方法。\n    *   `extractPrompt`: 分析如何构建发送给 LLM 的 Prompt（包含上下文提取逻辑）。\n    *   **缓存机制**: 关注 `updateGlobalCacheKey` 和 `LRUCacheMap`，理解 Copilot 如何利用 Prefix\u002FSuffix 进行二级缓存加速。\n\n通过以上步骤，您将获得一份相对清晰的 Copilot 内部实现代码，可用于学习其上下文推断、Prompt 工程及性能优化策略。","某安全团队在评估企业代码隐私风险时，需要深入理解 GitHub Copilot 如何提取本地代码上下文并发送至云端模型。\n\n### 没有 copilot-analysis 时\n- 面对经过 Webpack 压缩混淆的 `extension.js`，研究人员无法直接阅读源码，只能盲目猜测数据流向。\n- 缺乏有效的模块分割手段，700 多个捆绑在一起的代码块难以拆解，导致定位核心逻辑如大海捞针。\n- 变量名被混淆为单字符（如 `e`, `t`, `n`），无法识别参数含义，难以判断哪些代码片段被作为了提示词发送。\n- 复杂的逗号运算符和短路写法严重阻碍静态分析，人工还原 AST 结构耗时数周且极易出错。\n- 无法验证 Copilot 的缓存策略和实验特性，只能依赖官方文档的黑盒描述，存在合规盲区。\n\n### 使用 copilot-analysis 后\n- 利用 AST 解析技术自动将混淆的 Webpack 包分割为 752 个独立的模块文件，清晰呈现代码结构。\n- 通过作用域替换自动还原 `require`、`module` 和 `exports` 依赖关系，快速梳理出数据调用的完整链路。\n- 智能重命名混淆参数并优化语法糖，将晦涩的压缩代码转化为可读性强的标准 JavaScript，直观暴露上下文获取逻辑。\n- 自动化处理逗号表达式和闭包结构，大幅降低逆向门槛，使团队在几天内即可定位到代码提示的核心入口。\n- 成功复现并分析了缓存机制与实验特性，为企业制定精准的 AI 编码工具管控策略提供了确凿的技术依据。\n\ncopilot-analysis 将原本需要数周的黑盒逆向工作缩短至数天，让开发者能透明地掌控 AI 辅助编程背后的数据隐私逻辑。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmengjian-github_copilot-analysis_f5e2016d.png","mengjian-github","孟健","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fmengjian-github_b71dfc82.jpg","10年+技术经验，《DeepSeek极简入门与应用》作者，销量突破94万册，欢迎加我wx：mjcoding3","Nextfield Labs LLC","北京，中国","384709054@qq.com",null,"https:\u002F\u002Fmengjian.site","https:\u002F\u002Fgithub.com\u002Fmengjian-github",[87],{"name":88,"color":89,"percentage":90},"JavaScript","#f1e05a",100,2211,254,"2026-04-10T02:35:43",4,"macOS, Windows","未说明",{"notes":98,"python":96,"dependencies":99},"该工具并非直接运行的 AI 模型，而是一套用于逆向分析 GitHub Copilot VSCode 插件的脚本流程。主要运行环境为已安装 VSCode 及 Copilot 插件的系统（文中明确提及 macOS 和 Windows）。核心依赖为 Node.js 生态下的 Babel 系列库，用于解析、遍历和重构混淆后的 JavaScript 代码（webpack bundles）。无需 GPU 或特定 Python 环境，但需要手动获取插件源码并进行 AST 抽象语法树处理。",[100,101,102,103,104,105],"VSCode","babel-parser","babel-traverse","babel-generator","babel-types","prettier",[15,25],"2026-03-27T02:49:30.150509","2026-04-13T16:15:25.399596",[],[]]