【笔记】浏览器PNA/LNA策略——记一次iframe中CORS报错的问题排查经历

浏览器 PNA/LNA 策略——记一次 iframe 中 CORS 报错的问题排查经历 问题背景 最近在排查一个非常诡异的问题: 页面 A:正常业务页面,直接打开一切 OK。 页面 B:通过 <iframe src="页面 A"> 把 A 嵌进来。 页面A 里以<script>的方式引用了一个内部 CDN 脚本 https://xxxx/a.js,CDN 域名(代号xxxx)和页面A域名(代号yyyy)不同,页面A和页面B(代号zzzz)域名也不同。 在 Chrome(新版本)访问页面B时,控制台报错,页面无法正常访问: 1 2 3 Access to script at 'https://xxxx/a.js' from origin 'https://yyyy' has been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space. 开发者工具Network面板中也显示这几个 js 文件请求都是CORS error 看到这个报错时整个人都懵了,因为<script>标签引用的脚本,怎么可能有 CORS 问题?像 JSONP 这种技巧不也是利用了<script>标签的特性嘛。 面对这种奇怪的现象,我做了一些实验。发现从现象上有以下奇怪的点: 单独访问页面A时一切正常,cdn 的 js 不会报 CORS 错误,只有在访问页面B时(以iframe形式访问页面A)才会报错; 报错时<script>标签引用的脚本请求会报 CORS 错误,页面A其他 ajax 跨域请求也会报错(这些请求都做了 CORS 设置); 尝试了其他浏览器,如 Edge/Safari,这些浏览器不会有这个问题、即页面A可以正常访问; 尝试了低版本的 Chrome,也不会有这个问题、即页面A可以正常访问; 错误里出现了 unknown address space 这种字样,相比其他 CORS 错误信息是很陌生的; 结合这些信息,我基本断定是近期新版 Chrome 在网络策略上做了什么调整。在分析更新日志等信息后,最终排查下来,根因其实不是传统意义上的 CORS,而是 Chrome 最近上线的一套 Local Network Access / Private Network Access(LNA/PNA)安全策略 + iframe 权限机制 在背后搞事情。 一、现象复盘:为什么看起来像 CORS,又不像 CORS? 回顾错误信息: 1 2 3 Access to script at 'https://xxxx/a.js' from origin 'https://yyyy' has been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space. 几个关键信息: 资源 URL:https://xxxx/a.js Origin:https://yyyy —— 注意这是页面A的域,而不是页面B的域。 报错被归类为blocked by CORS policy,但额外带了unknown address space的提示。 结合几个“奇怪”的点,这已经在提示我们:真正做决策的是“顶层站点 + 地址空间”,而不是 iframe 自己的 origin——这正是 Local Network Access / Private Network Access 的行为特征。 二、排查过程:从“CORS”到“Local Network Access” 第一步:先排除“普通 CORS 配置错误“ 经典的 CORS 问题一般长这样: 1 No 'Access-Control-Allow-Origin' header is present on the requested resource. 或者 1 The 'Access-Control-Allow-Origin' header has a value 'xxx' that is not equal to the supplied origin. 而这次的错误信息多了这样一句: 1 Permission was denied for this request to access the `unknown` address space. 这句话用在很多类似案例里(如StackOverflow 问题示例),几乎都是 Chrome 的 Private Network Access / Local Network Access 安全检查触发 的结果,而不是简单的 CORS 头缺失。 再结合现象: 顶层打开 页面A 正常; iframe 场景才报错; 说明: 服务器对 https://xxxx 这个 origin 的 CORS 配置本身是 OK 的; 但当顶层是 页面B 的域名(https://zzzz)时,Chrome 用的是另一套安全逻辑。 第二步:顺着错误关键词搜一圈 用报错中的关键字去搜: “Permission was denied for this request to access the ‘unknown’ address space” “Local Network Access Chrome 142 iframe” “Access to script at has been blocked by CORS policy unknown address space” 会发现大量类似提问或者官方说明,都指向这几个关键点: 这是 Chrome 新的 Local Network Access / Private Network Access 策略 带来的变化; 只在 Chrome / Chromium 系列中新版本 执行,其他浏览器暂未完全跟进,因此出现“Chrome 挂了,Edge/Safari 正常”的现象; 很多案例里也是 iframe 场景,并且常被误认为是“CORS 头没配好”。 第三步:对比顶层 vs iframe 的行为差异 进一步验证: 顶层打开 页面A(Origin 为 https://xxxx)时,CDN js 资源加载正常; 同一个 URL,iframe 场景下却被以 CORS policy + unknown address space 拦截。 这基本就把问题锁定在: Chrome 把“顶层站点 + 目标资源”看作一次「跨地址空间访问」,并在 iframe 场景下启用了更严格的 LNA / PNA 检查。 三、策略机制科普:PNA(Private Network Access) / LNA(Local Network Access) 到底是啥? 要理解这个问题,需要先大致了解 Chrome 近几年在做的两件事: Private Network Access(PNA):限制公网网站随意访问内网 / 本机服务(https://developer.chrome.com/blog/private-network-access-preflight); Local Network Access(LNA):在 PNA 的基础上,引入“用户权限弹窗 + Permissions Policy”的新模式(https://developer.chrome.com/blog/local-network-access)。 地址空间(Address Space)划分 规范里把目标地址按“私密程度”分了几档: public:公网 IP / 域名; private / local:内网 IP(10.x / 192.168.x / 172.16–31.x 等); loopback:本机地址(127.0.0.1 / localhost 等); unknown:浏览器无法可靠判断所属空间的时候(某些 VPN / Zero Trust / 特殊代理场景经常掉进这里)。 核心安全模型是: 从「更开放的地址空间」访问「更私密的地址空间」时,要么被禁止,要么需要额外的 CORS/PNA 头或用户授权。 Private Network Access:基于 CORS 的第一阶段 PNA(以前叫 CORS-RFC1918)是第一阶段方案: 目标:防止公网网站扫描 / 操作你的内网设备(路由器、打印机、本机服务等),减少 CSRF / fingerprinting 风险; 机制: - 对从公网(public)发往私网(private/loopback)的请求,强制加一层 预检请求(preflight): 请求头带:Access-Control-Request-Private-Network: true 服务端必须响应:Access-Control-Allow-Private-Network: true 否则直接在浏览器侧报错(通常表现为 CORS error)。 后来由于落地难度和兼容性问题,Chrome 在 2024 年宣布 PNA 全量 rollout 暂停,会基于权限模型重新设计方案。 Local Network Access:基于权限的第二阶段 2025 年开始,Chrome 推出了新的 LNA 规范: 核心变化: 从“纯 CORS + 预检”转为“用户权限 + 站点设置”; 当站点要访问本地 / 内网 / unknown 地址空间时,会弹出 Local Network Access 权限框,让用户决定 Allow/Block(https://support.esri.com/en-us/knowledge-base/what-to-know-about-new-permission-prompt-in-google-chro-000039171); 站点的 LNA 权限可以被持久化、也可以由企业策略统一下发。 时间线大致是: 2025-06:Chrome 138 引入 LNA 权限提示的实验 flag(chrome://flags#local-network-access-check),开发者可以主动开启测试(https://developer.chrome.com/blog/local-network-access); 2025-09~10:从 Chrome 141/142 开始,默认为用户开启 LNA 权限提示,对连接本地网络的场景开始实打实拦截(https://developer.chrome.com/release-notes/142)。 iframe 与 Permissions Policy:allow="local-network-access" LNA 还跟 Permissions Policy(原 Feature Policy) 集成在一起,特别是 iframe 场景: 顶层页面要想让 iframe 里的代码访问本地 / 内网,需要显式声明: 1 <iframe src="https://xxxx/pageA" allow="local-network-access"></iframe> 并且如果有多层嵌套 iframe,需要层层透传这个 allow,否则最内层拿不到权限; 旦 iframe 没被授权,iframe 里的 fetch / <script> / WebSocket 等对本地/内网/unknown 地址空间的访问,就会被 Chrome 直接拦截,DevTools 里通常表现为你看到的这种 CORS+unknown address space 报错。 *PNA / LNA 相关重要节点 2020-11:Chrome 团队提出 CORS-RFC1918(后改名为 Private Network Access),征求反馈。https://developer.chrome.com/blog/cors-rfc1918-feedback 2021 Q2–Q4(Chrome 90+): 对从非安全上下文访问私网资源开始给出警告,并逐步拦截; 推出 Deprecation Trial 供站点缓冲迁移。https://developer.chrome.com/blog/private-network-access-update 2022-01:发布《Private Network Access: introducing preflights》,正式将 PNA 与 CORS 预检机制结合,引入 Access-Control-Allow-Private-Network 等头。https://developer.chrome.com/blog/private-network-access-preflight 2024-03~04:Chrome 发布 PNA 更新文章,宣布 PNA rollout 暂时搁置,将探索基于权限的替代机制,同时继续在部分场景中扩展 PNA 保护(按官方公告)。https://developer.chrome.com/blog/private-network-access-update-2024-03 2025-06(Chrome 138,按官方博客的计划时间线):发布《New permission prompt for Local Network Access》,引入 LNA 权限弹窗(默认通过 flag opt-in),开始用“权限 + 站点设置”模式管理本地网络访问。https://developer.chrome.com/blog/local-network-access 2025-09~10(Chrome 141/142,依据 release notes 标注的逐步放量): LNA 权限 prompt 面向更多用户逐步默认开启; 各大厂(Esri、Box、Stripe、SAP 等)的文档开始集中出现「Chrome 142 之后访问本地/内网服务被 CORS+unknown address space 拦截」的说明和 workaround。https://support.esri.com/en-us/knowledge-base/what-to-know-about-new-permission-prompt-in-google-chro-000039171 四、回到这次案例:为什么会在 script 上报unknown address space 把前面的信息套进来,我们可以比较有把握地还原一下这次的问题链路: 顶层 页面B:https://zzzz(public 站点); iframe 中 页面A:https://xxxx; 页面A 里引用脚本:<script src="https://xxxx/a.js"></script>; 在实际的网络环境里,https://xxxx 很可能通过公司的 DNS / ZTNA / VPN 等解析到 内网或特殊网络(事实证明也确实解析到了192的网络),对 Chrome 来说 IP 所属地址空间是 private 或 unknown; Chrome 142 之后,LNA 生效: 以 “顶层站点”的身份在访问 xxxx 对应的(unknown / private)地址空间; 又没有在 iframe 上声明 allow="local-network-access"; 可能还有站点级 LNA 权限尚未授予或被用户/策略 Block; 于是这条 script 请求在发出前就被 LNA 拦截,DevTools 以统一形式打印: 1 2 3 Access to script at 'https://xxxx/a.js' from origin 'https://yyyy' has been blocked by CORS policy: Permission was denied for this request to access the `unknown` address space. 从浏览器视角看,这是:一个 public 顶层站点在未经授权的情况下,试图从 iframe 中访问 unknown/local/private 网络资源。 从我们的视角看,就是:明明是同一个脚本 URL,顶层页面能加载,iframe 就报奇怪的 CORS。 实质上是 LNA + iframe 权限 + 地址空间判断 的组合拳。 五、快速验证 / 自查清单 在遇到 ...unknown/private/local address space 报错时,可以按下面的顺序快速确认是否为 LNA/PNA: DevTools → Network,查看失败请求解析到的 IP,判断是否落在 127.0.0.1 / 10.x / 192.168.x / VPN 或 Zero Trust 网段(unknown/private/local)。 如果是 iframe 场景,临时给 iframe 加 allow="local-network-access" 验证是否能消除报错;多层 iframe 需层层透传。 查看地址栏 → 站点设置 → Local Network Access 权限是否被 Block/Prompt,必要时手动 Allow(仅用于诊断)。 临时切换 chrome://flags#local-network-access-check 为 Non-blocking/Disabled 验证(只用于定位,不是正式解决方案)。 若目标在私网/本机,检查响应是否包含 Access-Control-Allow-Private-Network: true,并确保预检 OPTIONS 正确返回。 六、解决方案与实践建议 6.1 架构层优选方案:尽量消灭“公网 → 内网”的跨地址空间访问 从安全模型来看,Chrome 的判断并不是“反常”,而是架构上的风险被暴露出来了: 业务页面部署在 public 域名上(https://yyyy / https://xxxx); 实际资源或 API 落在内网 / 本地 / unknown 地址空间; 以前浏览器默认放行,现在开始收紧访问能力。 最根本、最长期稳妥的方案是: 将内网服务“挂”在一层 API 网关 / 反向代理 后面,对浏览器暴露为同一地址空间: 例如 Nginx / API Gateway 把内网 10.x.x.x:port 代理为 https://api.example.com; 浏览器看到的是 public→public,不会触发 LNA/PNA。 或者业务页面本身就跑在内网环境中,在浏览器眼里整体都是 local/private 地址空间。 这类改造成本会高一些,但可以一次性消掉大部分 LNA/PNA 类问题。 6.2 短期或受限环境下的 workaround 在没法马上改架构的情况下,可以考虑这些策略(主要适用于内网/企业环境): 为站点显式授予 Local Network Access 手动:在 Chrome 地址栏点击锁头 → 站点设置 → 将 Local Network Access 设置为 Allow; 企业统一:通过 Chrome Enterprise / Edge 管理策略(如 LocalNetworkAccessAllowedForUrls 等),为指定域名统一开启本地网络访问权。 为 iframe 增加 allow="local-network-access" 例如 <iframe src="https://xxxx/pageA" allow="local-network-access"></iframe> 如果 B 里还有多层 iframe,要保证每一层都透传该权限,https://learn.microsoft.com/en-us/answers/questions/5646980/local-network-access-iframe-restrictions-causing-d 如果脚本/接口确实在私网/本机,补充 PNA 相关 header(兼容旧实现) 在已有 CORS 响应头基础上增加:Access-Control-Allow-Private-Network: true 并确保预检 OPTIONS 请求能正确返回这个头。 调试阶段可通过 flags 验证是否确实是 LNA/PNA 导致 比如在本机把 chrome://flags#local-network-access-check 改为 Non-blocking / Disabled,看问题是否消失; 只能用于定位问题,不能作为线上解决方案。 6.3 代理落地的简单示例 以 Nginx 反代为例,把内网 10.1.2.3:8080 挂到外层域名 api.example.com,浏览器视角是 public→public: 1 2 3 4 5 6 7 8 9 10 11 server { listen 443 ssl; server_name api.example.com; ssl_certificate /path/fullchain.pem; ssl_certificate_key /path/privkey.pem; location / { proxy_pass http://10.1.2.3:8080; proxy_set_header Host api.example.com; } } 这样页面与 API 同为 public 地址空间,LNA/PNA 不再触发;同时保持 HTTPS,方便复用现有 CORS/缓存策略。 6.4 排查思路总结:以后再遇到类似报错可以这样查 1 2 ... has been blocked by CORS policy: Permission was denied for this request to access the `unknown/local/private` address space. 可以按下面这条“套路”来排查: 先确认是不是传统 CORS: 顶层打开同一页面 / 同一资源是否正常? 其他浏览器(Edge/Safari/旧版 Chrome)是否正常? 关注错误信息是否包含: unknown address space / private network / local network access 等关键词; 在 Network 里查看资源解析到的实际 IP: 是否为 127.0.0.1 / 10.x / 192.168.x / 其它私网段; 是否是某些 Zero Trust / VPN 网关转出来的地址。 检查是否为 iframe 场景 & 是否有 allow=”local-network-access”: 如果顶层访问 OK,iframe 挂,优先查这里。 看站点的 Local Network Access 权限: 地址栏 → 站点设置里是否被 Block; 企业环境下是否有限制策略。 根据情况选择: 架构改造(代理/网关,同一地址空间); iframe 权限 + 站点权限; 服务端补充 PNA 头,保证 preflight 正确。 最后 PNA/LNA 的本质,是浏览器在给“网页能不能碰你本机/内网”这件事重新立规矩:过去网页默认可以直接访问内网 IP、localhost 等资源,容易被用来扫内网、攻击路由器、探测隐私环境,所以 Chrome 先通过 PNA 把“公网 → 内网/本机”的请求纳入 CORS,高危路径要额外 preflight 和新头;再演进到 LNA,用权限弹窗、站点设置、企业策略和 allow=”local-network-access” 这类 iframe 权限,把决策变为“用户/企业明确授权 + 细粒度控制”;发展趋势很清晰——未来从公网页面直连内网/本机会越来越难,iframe、第三方脚本会被限制得更死,推荐模式会转向“浏览器只连受控中间层或本地代理”,对我们做前端和架构的人来说,需要把“浏览器直连内网”当成过渡方案,长期用“网关/代理 + 明确权限”的架构来规避这类风险。 相关链接 [官方] Private Network Access: introducing preflights — https://developer.chrome.com/blog/private-network-access-preflight [官方] Local Network Access 权限模式 — https://developer.chrome.com/blog/local-network-access [官方] Release notes 142(LNA 放量)— https://developer.chrome.com/release-notes/142 [官方] PNA 更新:暂缓 rollout,探索权限模型 — https://developer.chrome.com/blog/private-network-access-update-2024-03 [官方] CORS-RFC1918 反馈征集 — https://developer.chrome.com/blog/cors-rfc1918-feedback [官方] PNA 更新(Deprecation Trial 等)— https://developer.chrome.com/blog/private-network-access-update [官方] 在 Chrome中调整网站的 LNA 限制 - https://docs.google.com/document/d/1QQkqehw8umtAgz5z0um7THx-aoU251p705FbIQjDuGs/edit?hl=zh-cn&tab=t.0#heading=h.v8oobsqxbxxy [案例] Chrome LNA 权限弹窗说明(Esri)— https://support.esri.com/en-us/knowledge-base/what-to-know-about-new-permission-prompt-in-google-chro-000039171 [案例] iframe 限制讨论(MS Q&A)— https://learn.microsoft.com/en-us/answers/questions/5646980/local-network-access-iframe-restrictions-causing-d [社区] StackOverflow 报错示例 — https://stackoverflow.com/questions/79823001/cors-error-permission-was-denied-for-this-request-to-access-the-unknown-addres

2025/12/6
articleCard.readMore

【工具】spec驱动开发解析

【工具】Spec驱动开发(Specification Driven Development, SDD)解析 为什么需要 SDD 传统“代码先行、文档事后”的开发方式在大模型时代的问题被放大:AI 易误解意图、输出不稳、改动不可追溯,返工成本高。 SDD目前尚无严格定义,但它的核心思想可以概括为: 1 “让规范(specification)成为开发过程中的中心实体,使人和 AI 都以此为唯一事实源(single source of truth)。” 简言之,SDD 并非全新的方法论,而是对“生成式 AI 参与软件开发”这一趋势的系统化回应。它探讨的问题是:当 AI 能够读懂并据此生成代码时,我们是否应当以规范为起点重新组织开发流程? 规范驱动开发(Specification-Driven Development, SDD) 要求先写清楚要做什么和验收标准,再让人和 AI 严格按规范实现,把文档提升为一等公民。 背景脉络与提出者 “Specification-Driven Development” 没有单一权威定义,它继承了“先定义契约/接口再实现”的工程传统,与 API First、契约测试、TDD/BDD 等理念一脉相承。 大模型编码兴起让“规范先行”成为显性需求。 GitHub 的 Spec-Kit、Fission AI 的 OpenSpec,以及多代理框架 BMAD 等项目强化了 SDD 的术语和流程,使其从“工程常识”演化为可复用的工作流。 核心主张:规范是输入和审查基线;接口/契约先于实现;验收标准前置;让 AI 严格受规范约束。 SDD 是什么:一套“先约定、后实现、可验证”的工作方式 文档即契约:规范写清 What/Why/约束,成为设计、实现和评审的共同基线。 接口优先:先定义 API/模块接口、输入输出、边界条件,再编码,便于并行开发和松耦合。 渐进细化:从目标 → 澄清 → 方案 → 任务 → 验收 → 实现,避免陷入技术细节前就做决策。 验收前置:规范中直接写验收场景,测试从规范派生,形成闭环。 可追溯性:规范、任务、实现、测试之间可映射,利于审计和复盘。 SDD三个层次 根据 Martin Fowler 团队的观察,当前关于 SDD 的实践大致可分为三个层次,分别体现出规范在开发生命周期中的不同角色: Spec-first(规范先行)在这一层次上,开发流程以撰写规范为起点。开发者首先以结构化方式描述系统需求、接口和行为,然后再由人工或 AI 编写代码。此时,规范主要用于“指导实现”,其地位类似于传统的软件需求规格说明书(SRS),但通常更加可执行化。 Spec-anchored(规范锚定)该层次的特点是:规范不仅在初始阶段使用,而且在后续维护与扩展过程中持续存在。代码与规范之间保持双向关联,任何修改都需要在两者之间保持一致。这一模式强调演进过程中的一致性管理。 Spec-as-source(规范即源)这是最激进的一种形态。在此模式下,开发者直接编辑规范,而代码由生成式 AI 自动生成并更新。代码文件通常包含提示信息(如 // GENERATED FROM SPEC - DO NOT EDIT),明确指出源文件来自规范而非人工撰写。此时,“源代码”的地位实际上被“规范”取代,开发的本质变成了规范工程(spec engineering)。 三层AI参与度和自动化程度也逐层提升。 与 TDD、BDD 的关系 TDD 用代码层测试断言描述行为,SDD 在更高层写文档+接口定义,适合组合使用。 BDD 更偏用户视角场景,SDD 可嵌入 BDD 场景格式,但更全面覆盖需求到实现。 快速流程示意(30 分钟上手) 写目标与接口草稿、边界/约束; 补疑点与非目标; 拆出任务,附验收条件; 实施与对齐; 回写规范,归档成正式文档。 SDD 的适用与限制场景 ✅ 适用: 多团队并行协作、大型系统; 跨模块改造、大功能开发; API/平台型项目(需提前 Mock/定义); 从零构建时需要骨架/共识的场景; 需要审计/知识沉淀/可回溯过程的系统。 🚫 不适用或可简化: 脚本、小改动、快速验证原型; 模糊探索期(只记录关键约束即可)。 当前SDD面临术语不统一、AI服从性不足等挑战,但“先定规范再开发”已能提升代码一致性与效率,未来需解决规范语义统一、AI规范服从性、自动一致性验证以推动普及。 三种代表性工具与用法 快速对比表 工具定位/擅长节奏与粒度适用场景 BMAD多角色 AI 模拟敏捷团队,产出需求/架构/任务/实现重、全周期,偏大版本0→1、重构、架构升级 OpenSpec轻量变更驱动,每次变更都有提案/任务/归档轻、线性,小步快跑维护、接口新增 Spec-Kit结构化七步流程,产出规范与任务库中等偏重,强调一致性新项目规划、大功能设计 BMAD(多代理敏捷团队模拟) 定位:用多角色 AI(Analyst/PM/Architect/Dev/QA)模拟团队,从需求到交付。 典型步骤: 1) /analyst 需求分析(生成项目简报/目标); 2) /pm 编写 PRD、划分 Epic/优先级; 3) /architect 设计架构/接口/数据; 4) /sm 生成用户故事与任务、验收标准; 5) /dev 实现与测试;循环迭代。 优点:流程完整、角色分明、能输出较完整的需求/架构/任务包、适合大版本启动; 限制:流程重,偏好从零开始的大版本,不适合高频迭代、小改小修;需上下文长期维护,增量小改动时显得“过度工程”。 什么时候用:新产品、跨团队大版本、需要完整需求-架构-实现链条时优先。 简单示例: 1 2 3 4 5 6 7 8 9 # 安装(一次性) npx bmad-method install # 触发一次完整迭代 /analyst 目标:做一个支持扫码点餐的小程序,核心是菜单浏览与下单 /pm 输出 PRD,列出必做/可选功能和优先级 /architect 选择技术栈(UniApp + Node + MongoDB),设计主要接口 /sm 给出下一轮 Sprint 的用户故事与任务 /dev 实现任务并附单元/集成测试 OpenSpec(轻量规范驱动) 定位:维护期每次功能/接口变更都走 Proposal → Tasks → Apply → Archive 流程,让每次变更都有提案、任务和归档,保持“规范即现状”。 目录结构: openspec/specs/ 当前生效规范 openspec/changes/ 变更中提案(proposal.md、tasks.md 等) 典型步骤: 1) Proposal:/openspec:proposal 或 CLI 生成变更目录与 proposal.md(Why/What/Impact); 2) Review & Align:补充/澄清约束,用 MUST/SHOULD 固化; 3) Plan & Tasks:自动生成 tasks.md(含测试任务),必要时添加 design.md; 4) Apply:/openspec:apply 按任务顺序实现并勾选; 5) Archive:迁移变更目录到 archive,并把新增/修改的 spec 合并进 specs/。 优点:流程轻、贴合增量迭代;接口友好、Mock 与测试自动生成;归档让规范与代码同步; 限制:不含架构设计、不负责 0→1 全局设计,复杂决策需人工介入或需配合 Spec-Kit/BMAD 立骨架;提案粒度过大时质量易下降。 什么时候用:小步快跑的功能迭代、接口新增、线上缺陷修复后的补规范。 示例(现有项目新增导出报表接口): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 # 初始化(一次性) npm install -g @fission-ai/openspec@latest openspec init # 创建提案 /openspec:proposal 新增 GET /reports/export 接口,支持店铺ID和时间范围,导出 CSV # 补充约束(在 proposal/design 中) - MUST 时间范围不超过 7 天 - MUST Content-Type: text/csv,流式输出避免 OOM # 生成任务 /openspec:tasks # 实施 /openspec:apply # AI 按 tasks 逐项实现并勾选 # 归档并合并规范 /openspec:archive Spec-Kit(结构化规范生成器) 定位:为 0→1 项目或大功能提供结构化七步,明确项目目标、接口、方案与任务,产出可执行的规范与任务库,强调前后一致性。 七步(斜杠命令):/constitution(原则)→ /specify(需求)→ /clarify(澄清疑点)→ /plan(技术方案)→ /tasks(任务拆解)→ /analyze(一致性检查)→ /implement(按任务实现与测试)。 优势:阶段清晰、可做跨文档一致性检查;AI/技术栈无关,可基于同一规范尝试多方案;形成可传承的知识库。 局限:文档量大、上手成本高;小项目或快节奏需求可能不划算;需统一运行环境(如 Python/依赖)。 什么时候用:新项目规划、跨模块大功能、需要规范沉淀和一致性检查的团队。 示例(新建“照片管理”项目): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # 安装 CLI pip install spec-kit # 初始化 specify init photo-manager --ai cursor # 依次运行七步 /constitution 关注性能、易用性、可维护性,函数不超 50 行,单测覆盖率 80% /specify 构建照片管理应用,支持拖拽整理、日期分组、平铺预览 /clarify (让 AI 提问并补充:导入方式、批量操作、删除策略等) /plan 采用 Vite + vanilla JS,SQLite 存元数据,本地存储图片 /tasks (生成任务清单) /analyze (检查 Spec/Plan/Tasks 一致性) /implement (按任务顺序实现并带测试) 工具协同建议 “Spec-Kit 立骨架 + OpenSpec 管迭代”:前期用 Spec-Kit 输出 Constitution/Spec/Plan/Tasks,后续需求变更用 OpenSpec 的 Proposal → Tasks → Apply → Archive 保持规范常新。 “BMAD 做大版本 + OpenSpec 做小步”:大版本或架构升级用 BMAD 规划与设计,日常维护/小需求用 OpenSpec 快速交付。 借鉴而不堆叠:已用 BMAD 可吸收 Spec-Kit 的 Clarify/Analyze;已用 Spec-Kit 可用 OpenSpec 的归档保持规范-代码同步。 实战案例摘选 1) API 平台新增导出能力(OpenSpec) 背景:已有交易报表系统,需要新增 CSV 导出,前端和后端由不同团队负责。 做法:用 /openspec:proposal 固化需求与约束(时间范围 ≤7 天、Content-Type: text/csv、流式输出防 OOM),生成 tasks.md。 成果:后端先按规范提供 Mock,前端并行开发;上线后按 tasks.md 勾选并归档,规范与实现同步。 2) 数据标注工具重构(BMAD → OpenSpec) 背景:旧版前端性能差,需重构并分期上线。 做法:先用 BMAD 产出完整 PRD、架构、数据流设计和验收标准;每个迭代用 OpenSpec 拆变更(提案→任务→归档)。 成果:大方向与接口在 BMAD 阶段一次对齐,后续小步交付;避免“边重构边改需求”带来的返工。 3) 0→1 设备管理系统(Spec-Kit) 背景:要做 IoT 设备管理,接口多、边界复杂,团队需要统一原则和一致性检查。 做法:用 Spec-Kit 跑七步,明确非目标(不做 OTA)、性能约束(1 万设备秒级查询),并在 /analyze 阶段校验 Spec/Plan/Tasks 一致。 成果:上线前发现两处接口与约束不一致(分页规则、告警阈值),提前修正;规范文档直接变成培训材料。 典型落地误区 规范写成“备忘录”,缺少验收场景 现象:只有需求陈述,没有 BDD 场景,测试无法对齐。 纠正:每条需求至少列 1 个“WHEN/THEN”场景,覆盖主流程与关键边界。 粒度失衡:要么太大要么太碎 现象:一个提案覆盖多个子系统,导致任务不可验证;或拆得过碎,审阅成本高。 纠正:以“可独立验收的接口/用户旅程”作为粒度;大版本先用 BMAD/Spec-Kit 定骨架,再用 OpenSpec 小步落地。 规范与代码不同步 现象:上线后不回填,规范失真,AI/新人拿到旧信息。 纠正:把“归档/更新 spec”作为发布前的必做检查,可在 CI 或 PR 模板中加入核对项。 只写需求不写约束/非目标 现象:AI 按默认假设补充实现,导致超范围或性能踩坑。 纠正:显式写“非目标”“已知风险/约束”(比如 SLA、限流、数据上限),避免隐含假设。 工具堆叠、流程过重 现象:同时跑 BMAD + Spec-Kit + OpenSpec,重复产出,团队疲劳。 纠正:按阶段选 1-2 个核心工具,明确交接点;重在“规范可执行、可验证”,而非工具数量。 落地建议 选痛点切入:维护质量痛点先试 OpenSpec,需求对齐痛点试 Spec-Kit,大版本规划试 BMAD,先小范围试点再推广。 流程本地化:约定哪些文档必审、哪些可简化;把 Proposal/Tasks 接入现有评审或 PR 模板。 规范先行习惯:提交代码前更新规范;新增功能必须补接口定义与验收场景;测试用例对齐规范。 规范实时性:设定归档/合并规则,CI 或合并检查规范是否更新,避免“文档滞后”。 人机协同:AI 负责生成/执行,人工把关架构与风险;关键决策、验收与测试需人工确认。 持续复盘:记录使用成本与收益,跟进工具版本/最佳实践,按团队节奏调整流程深度。 结语 规范先行,是让 AI 真正可信的关键。SDD 提倡“先对齐、再实现”,让文档成为共识入口,也让自动化从规范出发,带来更可靠的交付、更少的返工。 延伸资料 GitHub: bmad-code-org/BMAD-METHOD GitHub: fission-ai/OpenSpec GitHub: github/spec-kit OpenAPI 官方规范: https://www.openapis.org/ 《Understanding Spec-Driven Development: Kiro, spec-kit, and Tessl》

2025/12/1
articleCard.readMore

Agent设计模式

Agent设计模式 我们可以将智能体(Agent)理解为一个具备自主理解、规划、记忆和工具使用能力的数字化实体。想象一个高度智能的个人助理,你只需告诉他“帮我规划一次去千岛湖的周末旅行”,他就能自主完成以下任务: 感知(Perception):理解用户的自然语言指令。 规划与推理(Planning & Reasoning):借助模型推理能力,将任务拆解为查询往返机票、筛选酒店、规划景点路线、预估预算等子任务。 记忆(Memory):记住你之前的偏好,比如喜欢靠窗的座位、偏爱的经济型酒店。 工具(Tool):调用外部工具,如机票预订 API、酒店查询系统、地图服务等,来执行这些子任务。 反馈与迭代(Feedback & Iteration):将规划好的行程草案反馈给你,并根据你的修改意见进行调整,最终完成预订。 智能体让 AI 从一个只会内容生成的语言模型,进化成一个具备自主规划能力的行动者。 1、Chain of Thought(思维链) 提出背景:Google Research 在 2022 年发表的论文《Chain-of-Thought Prompting Elicits Reasoning in Large Language Models》。 核心思想:让模型在回答前,把推理过程一步步写出来。不是一口气报出答案,而是把整个推理过程展示出来。 场景例子:问小王比小李大 1 岁,小张的年龄是小李的两倍。如果三个人的年龄加起来是 41岁,问小王多大?思维链方式:假设小李的年龄是 x,那么小王 = x + 3,小张 = 2x,总和 = (x + 1) + x + (2x) = 4x + 1,4x + 1 = 41,4x = 38,x = 10,所以小王 = 10 + 3 = 13。结果小王 13 岁。这种方式在逻辑推理、数值计算、逐步分析类问题里,会显得更稳健。 2、Self-Ask(自问自答) 提出背景:Microsoft Research 在 2022 年的研究工作《Self-Ask with Search》(https://arxiv.org/abs/2210.03350,https://github.com/ofirpress/self-ask)。 核心思想:让模型在回答时学会“反问自己”,把大问题拆成多个小问题,然后逐个回答。 场景例子:问2016 年奥斯卡最佳男主角的年龄是多少?Self-Ask 会先问:2016 年奥斯卡最佳男主是谁?(答:李奥纳多·狄卡比奥),再问他当时多大?(答:41 岁),最后组合答案。这种方式特别适合事实链路长的问题。 3、Reflection / Self-Critique Loop(反思/自我批评循环) 提出背景:论文 《Self‑Reflection in LLM Agents: Effects on Problem‑Solving Performance(Renze & Guven, 2024)》提出让大语言模型(LLM)在回答后反思自己的错误并修正。另外,框架 Reflexion(Shinn et al., 2023)提出语言代理通过“口头强化(verbal reinforcement)”方式记忆反思([https://arxiv.org/abs/2303.11366])(https://arxiv.org/abs/2303.11366))。 核心思想:在模型输出答案之后,主动让模型“回顾”其推理或行动过程,识别可能的错误/偏差,然后基于反思内容生成修正或改进版答案。类似“生成 → 检查 →修正”的循环。 场景例子:你让 Agent 撰写一份技术方案或代码片段:首先模型给出版本 A;然后进行反思:「我可能漏掉了异常处理 X」;然后生成版本 B 加入异常处理。结果输出版本 B 更健壮。 4、ReAct(推理 + 行动) 提出背景:Princeton 与 Google Research 在 2022 年论文《ReAct: Synergizing Reasoning and Acting in Language Models》(https://research.google/blog/react-synergizing-reasoning-and-acting-in-language-models/)。 核心思想:在推理(Reasoning)和外部行动(Acting,比如调用搜索引擎或 API)之间交替进行。ReAct 比 CoT、Self-Ask 更全能,原因在于它不仅是推理模式,还内建了与外部世界交互的闭环。 场景例子:问杭州昨天的天气?ReAct 会先想:“我不知道昨天的天气,需要查询”,然后执行“调用天气 API”,再推理并回答。这让 Agent 既有思维,又能动手。 5、Plan-and-Execute(计划与执行) 提出背景:出现在 2023 年前后的 Agent 应用开发框架实践(如 LangChain 社区),参考https://aclanthology.org/2023.acl-long.147.pdf、https://blog.langchain.com/planning-agents/。 核心思想:把任务拆成两个阶段,先生成计划(Planning),再逐步执行(Execution)。 场景例子:假设你让 Agent 写一篇“新能源车的市场调研报告”,它不会直接生成报告,而是先拟定计划:收集销量数据,分析政策趋势,总结消费者反馈,撰写结论。然后逐条执行。适合多步骤、需长时间任务的场景。 6、Tree of Thoughts (ToT,树状思维) 提出背景:Princeton 和 DeepMind 在 2023 年的论文《Tree of Thoughts: Deliberate Problem Solving with Large Language Models》。 核心思想:不是单线思维,而是生成多条思路分支,像树一样展开,再通过评估机制选出最佳分支。 场景例子:解一道数独时,Agent 会尝试多个候选解法(分支 A、B、C),逐步排除错误分支,最终选出唯一解。适合复杂规划和解谜任务。 7、Multi-Agent / Collaboration 模式 提出背景:综述论文 《Multi‑Agent Collaboration Mechanisms: A Survey of LLMs(Tran et al., 2025)》专门对 LLM 为基础的多代理系统进行了归纳。 此外,研究 Scaling Large Language Model‑based Multi‑Agent Collaboration(Qian et al., 2024/25)探讨了代理数量扩展的协作效应。 核心思想:将多个 Agent(每个可能具备不同角色/能力)组合起来协作,通过分工、沟通、协调完成比单一 Agent 更复杂的任务。可以有“专门角色 Agent”“监督 Agent”“执行 Agent”等。 场景例子:一个市场调研任务:Agent A 负责数据采集,Agent B 负责数据分析,Agent C 负责报告撰写。三者协作完成整体任务,比一个 Agent 从头做更高效、更模块化。 8、World-Model / Simulation Pattern(世界模型/模拟推演) 提出背景:论文 《Is Your LLM Secretly a World Model of the Internet? Model‑Based Planning for Web Agents(Gu et al., 2024)》提出让 LLM 担任世界模型来预测动作后果。 另一个相关框架 Reasoning with Language Model is Planning with World Knowledge Model(Hao et al., 2023)也讨论了基于状态模拟的推理结构。 核心思想:在模型真正执行行动之前,先在一个「内在世界模型/模拟环境」中,对可能的动作路径进行推演、预测后果,然后选择最优策略再执行。 场景例子:Agent 需要在网页中执行一系列操作(比如填写表格、点击按钮、获取结果) — 它先在模拟环境中预测「如果我先点击 X,再输入 Y,会得到啥?」「或者我先输入 Y,再点击 X 会怎样?」然后选最优顺序正式执行真实操作。 9、Meta-Planning / Hierarchical Agent 模式 提出背景:论文 《Interactive Planning with Large Language Models Enables General Agent Automation(Wang et al., 2023)》探讨了用 LLM 作为规划器 + 执行者的双层结构。 虽然“Meta-Agent”这个具体标签较少,但这种“规划层 + 执行层”架构正在成为趋势。 核心思想:在系统中引入“元代理”(Meta-Agent)负责战略规划、目标拆解;底层多个子代理或模块负责执行具体子任务。系统结构分层:最高层负责“做什么”“为什么做”,下一层负责“怎么做”“谁做”。 场景例子:你让 Agent 完成一个“产品上线发布”任务:Meta-Agent 制定计划(调研 → 开发 → 测试 → 上线),然后各子模块 Agent 分别执行(调研 Agent、开发 Agent、测试 Agent、部署 Agent)。Meta-Agent 在必要时重新协调更新计划。 10、Graph-/Tree-Expansion 推理模式(“图思维/树思维” 的扩展) 提出背景:Tree of Thoughts: Deliberate Problem Solving with Large Language Models(Yao et al., 2023)是树状思维基础,但后续有论文如 《SimuRA: Towards General Goal‑Oriented Agent via Simulative Reasoning Architecture with LLM‑Based World Model(Deng et al., 2025)》采用“图(Graph)”形式的思维扩展。 核心思想:不仅生成一条思路(线性链),也不是仅树状,而是“图状”展开多个候选思路/路径(节点=状态/想法,边=转换),然后通过评估机制选出最佳路径。比简单树状更灵活,适用更大解空间。 场景例子:Agent 解决一个复杂规划问题(如多步跨部门项目、谜题或游戏)。它首先展开多个可能路径(例如路径 A、B、C …),在每个路径内部再展开子分支;通过评估机制(成本、风险、收益)最终选中一个最优路径执行。 11、Tool-Chain Agent(工具链式智能体) 提出背景:这一模式由 LangChain、OpenDevin、AutoGPT 等框架实践逐步形成;学术上相关研究如 Toolformer: Language Models Can Teach Themselves to Use Tools(Schick et al., Meta AI, 2023)奠定了让 LLM 自学使用外部工具的基础。LangChain Agents 文档示例:https://python.langchain.com/docs/modules/agents/ 核心思想:让 Agent 不仅能调用单一工具,而是构建和执行一个工具调用链(Tool → Tool → Tool)。Agent 会根据任务自动选择合适的外部接口或函数,形成“计划—调用—验证”的流水线。 场景例子:例如一个数据分析 Agent:1.调用爬虫 API 抓取数据;2.调用 Python 计算函数分析结果;3.再调用 chart API 绘制图表;4.最后生成报告。整个过程像流水线一样由 Agent 自动调度完成。 12、Memory-Augmented Agent(记忆增强型智能体) 提出背景:来源于 Generative Agents: Interactive Simulacra of Human Behavior(Park et al., Stanford University, 2023)——该论文展示了 Agent 拥有长期记忆、短期记忆和反思能力的行为模拟系统。同类框架包括 MemGPT(2023)与 LangGraph(2024)均实现了可读写的记忆组件。 核心思想:给 Agent 加入可持久化的“记忆系统”,使其能从历史交互中提取经验并在未来决策中使用。记忆可分为: 短期记忆(Working Memory):当前会话上下文; 长期记忆(Episodic Memory):跨会话持久信息; 反思记忆(Reflective Memory):自我总结与知识抽象。 场景例子:例如一个个人助理 Agent,你昨天让它订酒店,今天让它订机票,它会记得你昨天的出行目的地,从而自动推荐匹配的航班与时间,而不是“重头问起”。 13、Self-Evolution / Self-Improvement Agent(自我进化型智能体) 提出背景:源自开源项目 EvoAgent(2024)与论文 Evolving Agents: Autonomously Improving via Evaluation and Mutation(Liu et al., 2024)。该方向强调让 Agent 自动评估自身表现并演化出更优版本。GitHub 项目:https://github.com/openbmb/EvoAgent 核心思想:Agent 拥有“自我评估—优化—再训练”能力:1.先执行任务并记录结果;2.对自身行为进行评估;3.基于反馈进行参数或策略变异;4.生成改进版 Agent。类似于强化学习中的“自举改进(bootstrapped improvement)”,但通过语言层完成。 场景例子:一个写作 Agent 自动撰写文章后,分析自己哪些部分得分低,再基于评估规则改进提示、调整风格或参考示例,最终进化出更高质量输出版本。 总结一下,这些认知框架,其实构成了 Agent 世界里的思维模式库: CoT:一步步写出推理过程 Self-Ask:把大问题拆成小问题逐步回答 ReAct:边推理边行动,与外部世界交互 Plan-Execute:先生成计划,再按步骤执行 ToT:多分支探索思路,选最优路径 Reflexion:自我反思并改进输出 Multi-Agent:多角色协作分工完成复杂任务 World-Model:先在模拟世界推演,再决定行动 Meta-Planning:分层规划,顶层统筹子任务执行 Graph-of-Thoughts:图状展开多路径推理与评估 Tool-Chain:串联多个工具形成调用流水线 Memory-Agent:具备短期与长期记忆的持续学习 Self-Evolution:自动评估与迭代优化自身能力 它们并不是互斥的,可以混搭使用,理解这些模式,能让我们在应用开发框架选型和使用时,想的更为透彻,一些设计模式,例如 ReAct,已经被 LangChain、LlamaIndex、Dify、Spring AI Alibaba 等 Agent 开发框架内置成基础框架,帮助开发者提升模型的调用效果。 Agent 的应用开发框架天然就很难收敛。不同的框架都有自己的设计模式哲学,只要定位清晰,都能获得一部分开发者群体的青睐,一家独大的情况很难出现。 另外推荐今年一本关于Agent设计模式的书:《Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems》

2025/11/8
articleCard.readMore

【工具】2025年AI Coding部分产品技术分析——ClaudeCode和CodexCLI

2025年AI Coding部分产品技术分析——ClaudeCode和CodexCLI 能力情况: Coding AgentCode SearchFile OpsShellWeb SearchTestingMCPMultimodalContext Claude Code✓✓✓✓✓✓✓ Codex✓✓✓✓✓✓✓ Claude Code https://claude.com/product/claude-code,逆向项目(v1.0.33版本):https://github.com/shareAI-lab/analysis_claude_code 技术创新 1. 实时 Steering 机制 基础架构: h2A 双重缓冲异步消息队列 核心特性: 零延迟消息传递,吞吐量 > 10,000 消息/秒 实现原理: Promise-based 异步迭代器 + 智能背压控制 技术优势: 真正的非阻塞异步处理,支持实时流式响应 2. 分层多 Agent 架构 主Agent: nO 主循环引擎,负责核心任务调度 SubAgent: I2A 子任务代理,提供隔离执行环境 Task Agent: 专用任务处理器,支持并发执行 权限隔离: 每个Agent都有独立的权限范围和资源访问控制 3. 智能上下文管理 压缩算法: 92% 阈值自动触发上下文压缩 内存优化: wU2 压缩器,智能保留关键信息 持久化: CLAUDE.md 文件作为长期记忆存储 动态管理: 根据Token使用情况动态调整上下文大小 4. 强化安全防护 6层权限验证: 从UI到工具执行的完整安全链 沙箱隔离: 工具执行环境完全隔离 输入验证: 多层次的恶意输入检测和过滤 权限网关: 细粒度的功能权限控制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 Claude Code Agent 系统架构 ┌─────────────────────────────────────────────────────────────────┐ │ 用户交互层 │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ CLI接口 │ │ VSCode集成 │ │ Web界面 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────┬───────────────┬───────────────┬───────────────────┘ │ │ │ ┌─────────────▼───────────────▼───────────────▼───────────────────┐ │ Agent核心调度层 │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ nO主循环引擎 │◄────────┤ h2A消息队列 │ │ │ │ (AgentLoop) │ │ (AsyncQueue) │ │ │ └─────────────────┘ └─────────────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌─────────────────┐ ┌─────────────────┐ │ │ │ wu会话流生成器 │ │ wU2消息压缩器 │ │ │ │ (StreamGen) │ │ (Compressor) │ │ │ └─────────────────┘ └─────────────────┘ │ └─────────────┬───────────────────────┬─────────────────────────────┘ │ │ ┌─────────────▼───────────────────────▼─────────────────────────────┐ │ 工具执行与管理层 │ │ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌─────────────────┐│ │ │MH1工具引擎 │ │UH1并发控制│ │SubAgent管理│ │ 权限验证网关 ││ │ │(ToolEngine)│ │(Scheduler) │ │(TaskAgent) │ │ (PermissionGW) ││ │ └────────────┘ └────────────┘ └────────────┘ └─────────────────┘│ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ │ │ ┌────────────────────────────────────────────────────────────────┐│ │ │ 工具生态系统 ││ │ │ 文件操作│搜索发现│任务管理│系统执行│网络交互│特殊功能│MCP集成 ││ │ └────────────────────────────────────────────────────────────────┘│ └─────────────┬─────────────────────────────────────────────────────┘ │ ┌─────────────▼─────────────────────────────────────────────────────┐ │ 存储与持久化层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │短期记忆存储 │ │中期压缩历史 │ │长期持久存储 │ │状态缓存系统 │ │ │ │(Messages) │ │(Compressed) │ │(CLAUDE.md) │ │(StateCache) │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ └───────────────────────────────────────────────────────────────────┘ 记忆与上下文管理机制 三层记忆架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 记忆与上下文管理系统架构 ┌─────────────────────────────────────────────────────────────────┐ │ 短期记忆层 │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ 当前会话上下文 ││ │ │ messages[] - 实时消息数组 ││ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ││ │ │ │ User │ │Assistant│ │ Tool │ │ System │ ││ │ │ │ Message │ │ Message │ │ Result │ │ Prompt │ ││ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ ││ │ │ ││ │ │ 特征:O(1)查找,实时访问,自动Token统计 ││ │ └─────────────────────────────────────────────────────────────┘│ └─────────────┬───────────────────────────────────────────────────┘ │ 92%阈值触发 ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 中期记忆层 │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ 8段式结构化压缩 (AU2算法) ││ │ │ ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ │ │ 背景上下文 │ │ 关键决策 │ │ 工具使用 │ ││ │ │ │ Context │ │ Decisions │ │ Tool Usage │ ││ │ │ └─────────────┘ └─────────────┘ └─────────────┘ ││ │ │ ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ │ │ 用户意图 │ │ 执行结果 │ │ 错误处理 │ ││ │ │ │ User Intent │ │ Results │ │ Error Cases │ ││ │ │ └─────────────┘ └─────────────┘ └─────────────┘ ││ │ │ ││ │ │ ┌─────────────┐ ┌─────────────┐ ││ │ │ │ 未解决问题 │ │ 后续计划 │ ││ │ │ │ Open Issues │ │ Future Plans │ ││ │ │ └─────────────┘ └─────────────┘ ││ │ │ ││ │ │ 特征:智能压缩,上下文连续,大幅节省Token ││ │ └─────────────────────────────────────────────────────────────┘│ └─────────────┬───────────────────────────────────────────────────┘ │ 持久化存储 ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 长期记忆层 │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ CLAUDE.md系统 ││ │ │ ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ │ │ 项目上下文 │ │ 用户偏好 │ │ 工作流程 │ ││ │ │ │ Project Info│ │Preferences │ │ Workflows │ ││ │ │ └─────────────┘ └─────────────┘ └─────────────┘ ││ │ │ ││ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ │ │ 代码风格 │ │ 开发环境 │ │ 安全配置 │ ││ │ │ │ Code Style │ │ Environment │ │ Security │ ││ │ │ └─────────────┘ └─────────────┘ └─────────────┘ ││ │ │ ││ │ │ 特征:跨会话恢复,用户定制,项目持续记忆 ││ │ └─────────────────────────────────────────────────────────────┘│ └───────────────────────────────────────────────────────────────────┘ 上下文注入与恢复机制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 文件内容注入与恢复流程 用户提及文件 系统检测到文件引用 │ │ ▼ ▼ ┌─────────────┐ ┌─────────────┐ │ 文件路径 │ │ 自动检测 │ │ 解析验证 │ │ 相关文件 │ └──────┬──────┘ └──────┬──────┘ │ │ ▼ ▼ ┌─────────────┐ ┌─────────────┐ │ 安全检查 │ │ 智能推荐 │ │ • 路径验证 │ │ • 依赖分析 │ │ • 权限检查 │ │ • 关联度计算│ │ • 文件存在 │ │ • 优先级排序│ └──────┬──────┘ └──────┬──────┘ │ │ └─────────────┬─────────────────┘ ▼ ┌─────────────┐ │ 容量控制 │ │ • 最大20文件│ │ • 每个8K Token│ │ • 总计32K限制│ └──────┬──────┘ │ ▼ ┌─────────────┐ │ 内容注入 │ │ • 格式化处理│ │ • 语法高亮 │ │ • 行号显示 │ └──────┬──────┘ │ ▼ ┌─────────────┐ │ 上下文更新 │ │ 并返回给用户│ └─────────────┘ 工具执行引擎架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 工具执行引擎 (MH1) 完整流水线 用户工具调用请求 │ ▼ ┌─────────────┐ │ 阶段1: │ ┌──────────────────────────────────┐ │ 工具发现 │◄───┤ • 工具名称解析 │ │ & 验证 │ │ • 工具注册表查找 │ └──────┬──────┘ │ • 可用性检查 │ │ └──────────────────────────────────┘ ▼ ┌─────────────┐ │ 阶段2: │ ┌──────────────────────────────────┐ │ 输入验证 │◄───┤ • Zod Schema验证 │ │ (Schema) │ │ • 参数类型检查 │ └──────┬──────┘ │ • 必填参数验证 │ │ │ • 格式化错误消息 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 阶段3: │ ┌──────────────────────────────────┐ │ 权限检查 │◄───┤ • checkPermissions调用 │ │ & 门控 │ │ • allow/deny/ask三种行为 │ └──────┬──────┘ │ • Hook机制支持 │ │ │ • 安全策略应用 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 阶段4: │ ┌──────────────────────────────────┐ │ 取消检查 │◄───┤ • AbortController信号 │ │ (Abort) │ │ • 用户中断处理 │ └──────┬──────┘ │ • 超时控制 │ │ └──────────────────────────────────┘ ▼ ┌─────────────┐ │ 阶段5: │ ┌──────────────────────────────────┐ │ 工具执行 │◄───┤ • pW5具体执行函数 │ │ (Execute) │ │ • 异步生成器处理 │ └──────┬──────┘ │ • 流式结果输出 │ │ │ • 错误捕获与处理 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 阶段6: │ ┌──────────────────────────────────┐ │ 结果格式化 │◄───┤ • mapToolResultToToolResultBlock │ │ & 清理 │ │ • 结果标准化 │ └──────┬──────┘ │ • 状态清理 │ │ │ • 分析事件记录 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 输出结果 │ │ 到Agent Loop │ └─────────────┘ SubAgent架构与Task工具 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 SubAgent架构与Task工具机制 主Agent (nO循环) │ │ Task工具调用 ▼ ┌─────────────┐ │ Task工具 │ ┌──────────────────────────────────┐ │ cX="Task" │◄───┤ • 用户任务描述解析 │ └──────┬──────┘ │ • SubAgent环境准备 │ │ │ • 工具集合配置 │ │ └──────────────────────────────────┘ ▼ ┌─────────────┐ │ I2A函数 │ ┌──────────────────────────────────┐ │ SubAgent │◄───┤ • 新的Agent实例创建 │ │ 实例化 │ │ • 独立执行环境 │ └──────┬──────┘ │ • 隔离权限管理 │ │ │ • 专用工具子集 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ CN5 Schema │ ┌──────────────────────────────────┐ │ 输入验证 │◄───┤ description: 任务简短描述(3-5词) │ └──────┬──────┘ │ prompt: 详细任务执行指令 │ │ └──────────────────────────────────┘ ▼ ┌─────────────┐ │ SubAgent │ ┌──────────────────────────────────┐ │ 独立执行 │◄───┤ • 独立的nO循环实例 │ │ Environment │ │ • 专用消息队列 │ └──────┬──────┘ │ • 隔离的工具权限 │ │ │ • 独立错误处理 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 执行结果 │ ┌──────────────────────────────────┐ │ 返回主Agent│◄───┤ • 单一消息返回机制 │ └─────────────┘ │ • 无状态通信模式 │ │ • 结果摘要生成 │ └──────────────────────────────────┘ 长期规划机制——Todo系统技术实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 Todo系统完整架构图 ┌─────────────────────────────────────────────────────────────────┐ │ Todo工具对象层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ TodoWrite │ │ TodoRead │ │ │ │ (yG对象) │ │ (oN对象) │ │ │ │ │ │ │ │ │ │• 任务创建 │ │• 任务查询 │ │ │ │• 状态更新 │ │• 状态显示 │ │ │ │• 优先级设置 │ │• 进度跟踪 │ │ │ └─────────────┘ └─────────────┘ │ └─────────────┬─────────────────────┬─────────────────────────────┘ │ │ ▼ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 数据管理层 │ │ │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ YJ1排序算法引擎 ││ │ │ ││ │ │ 状态优先级: pending(0) → in_progress(1) → completed(2) ││ │ │ 重要性排序: high(0) → medium(1) → low(2) ││ │ │ ││ │ │ 排序逻辑: ││ │ │ 1. 按状态分组 (进行中 > 待处理 > 已完成) ││ │ │ 2. 组内按优先级排序 (高 > 中 > 低) ││ │ │ 3. 相同优先级按创建时间排序 ││ │ └─────────────────────────────────────────────────────────────┘│ └─────────────┬───────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ 存储持久化层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ React │ │ 会话状态 │ │ 本地缓存 │ │ │ │ 状态管理 │ │ 存储 │ │ 系统 │ │ │ │ │ │ │ │ │ │ │ │• useState │ │• 轮次隔离 │ │• 浏览器缓存 │ │ │ │• useEffect │ │• 状态同步 │ │• 会话恢复 │ │ │ │• 组件更新 │ │• 数据一致性 │ │• 离线支持 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └───────────────────────────────────────────────────────────────────┘ System-Reminder动态注入机制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 System-Reminder动态注入与上下文管理流程 Agent Loop执行过程 │ ▼ ┌─────────────┐ │ 状态检测 │ ┌──────────────────────────────────┐ │ 触发器 │◄────┤ • Todo列表变化检测 │ └──────┬──────┘ │ • 文件系统状态变化 │ │ │ • 用户行为模式分析 │ ▼ │ • 错误模式识别 │ ┌─────────────┐ └──────────────────────────────────┘ │ 条件匹配 │ ┌──────────────────────────────────┐ │ 引擎 │◄────┤ • 规则表达式匹配 │ └──────┬──────┘ │ • 上下文相关性分析 │ │ │ • 时机适当性判断 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 内容生成 │ ┌──────────────────────────────────┐ │ 与格式化 │◄────┤ • 动态内容模板 │ └──────┬──────┘ │ • 个性化信息生成 │ │ │ • 格式标准化处理 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ 注入时机 │ ┌──────────────────────────────────┐ │ 控制 │◄────┤ • 消息流插入点选择 │ └──────┬──────┘ │ • 用户体验优化 │ │ │ • 干扰最小化原则 │ ▼ └──────────────────────────────────┘ ┌─────────────┐ │ <system- │ 在消息流中动态插入: │ reminder> │ <system-reminder> │ 标签注入 │ 内容会在这里动态生成,提供实时指导 └─────────────┘ </system-reminder> 6层安全防护架构 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 Claude Code 6层安全防护体系 ┌─────────────────────────────────────────────────────────────────┐ │ 第1层: 输入验证层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Zod Schema │ │ 参数类型 │ │ 格式验证 │ │ │ │ 严格验证 │ │ 强制检查 │ │ 边界约束 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────┬───────────────────────────────────────────────────┘ │ ┌─────────────▼───────────────────────────────────────────────────┐ │ 第2层: 权限控制层 │ │ │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ 权限验证三元组 ││ │ │ ││ │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ││ │ │ │ Allow │ │ Deny │ │ Ask │ ││ │ │ │ 直接执行│ │ 拒绝执行│ │用户确认 │ ││ │ │ └─────────┘ └─────────┘ └─────────┘ ││ │ │ │ │ │ ││ │ │ └───────────────┼───────────────┘ ││ │ │ ▼ ││ │ │ Hook机制绕过通道 ││ │ └─────────────────────────────────────────────────────────────┘│ └─────────────┬───────────────────────────────────────────────────┘ │ ┌─────────────▼───────────────────────────────────────────────────┐ │ 第3层: 沙箱隔离层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Bash沙箱 │ │ 文件系统 │ │ 网络访问 │ │ │ │ sandbox=true│ │ 写入限制 │ │ 域名白名单 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────┬───────────────────────────────────────────────────┘ │ ┌─────────────▼───────────────────────────────────────────────────┐ │ 第4层: 执行监控层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │AbortController│ │ 超时控制 │ │ 资源限制 │ │ │ │ 中断信号 │ │ 防止卡死 │ │ 内存/CPU │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────┬───────────────────────────────────────────────────┘ │ ┌─────────────▼───────────────────────────────────────────────────┐ │ 第5层: 错误恢复层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ 异常捕获 │ │ 错误分类 │ │ 自动重试 │ │ │ │ try/catch │ │ 详细日志 │ │ 降级处理 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └─────────────┬───────────────────────────────────────────────────┘ │ ┌─────────────▼───────────────────────────────────────────────────┐ │ 第6层: 审计记录层 │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ 操作日志 │ │ 安全事件 │ │ 合规报告 │ │ │ │ 完整追踪 │ │ 实时告警 │ │ 定期审计 │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ └───────────────────────────────────────────────────────────────────┘ 关键Prompt System prompt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user. IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation. IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files. If the user asks for help or wants to give feedback inform them of the following: - /help: Get help with using Claude Code - To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues When the user directly asks about Claude Code (eg 'can Claude Code do...', 'does Claude Code have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from Claude Code docs at https://docs.anthropic.com/en/docs/claude-code. - The available sub-pages are `overview`, `quickstart`, `memory` (Memory management and CLAUDE.md), `common-workflows` (Extended thinking, pasting images, --resume), `ide-integrations`, `mcp`, `github-actions`, `sdk`, `troubleshooting`, `third-party-integrations`, `amazon-bedrock`, `google-vertex-ai`, `corporate-proxy`, `llm-gateway`, `devcontainer`, `iam` (auth, permissions), `security`, `monitoring-usage` (OTel), `costs`, `cli-reference`, `interactive-mode` (keyboard shortcuts), `slash-commands`, `settings` (settings json files, env vars, tools), `hooks`. - Example: https://docs.anthropic.com/en/docs/claude-code/cli-usage # Tone and style You should be concise, direct, and to the point. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do. IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity: <example> user: 2 + 2 assistant: 4 </example> <example> user: what is 2+2? assistant: 4 </example> <example> user: is 11 a prime number? assistant: Yes </example> <example> user: what command should I run to list files in the current directory? assistant: ls </example> <example> user: what command should I run to watch files in the current directory? assistant: [runs ls to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files] npm run dev </example> <example> user: How many golf balls fit inside a jetta? assistant: 150000 </example> <example> user: what files are in the directory src/? assistant: [runs ls and sees foo.c, bar.c, baz.c] user: which file contains the implementation of foo? assistant: src/foo.c </example> When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system). Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification. Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session. If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences. Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked. IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. # Proactiveness You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between: - Doing the right thing when asked, including taking actions and follow-up actions - Not surprising the user with actions you take without asking For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions. # Following conventions When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns. - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language). - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions. - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic. - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository. # Code style - IMPORTANT: DO NOT ADD ***ANY*** COMMENTS unless asked # Task Management You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress. These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable. It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed. Examples: <example> user: Run the build and fix any type errors assistant: I'm going to use the TodoWrite tool to write the following items to the todo list: - Run the build - Fix any type errors I'm now going to run the build using Bash. Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list. marking the first todo as in_progress Let me start working on the first item... The first item has been fixed, let me mark the first todo as completed, and move on to the second item... .. .. </example> In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors. <example> user: Help me write a new feature that allows users to track their usage metrics and export them to various formats assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task. Adding the following todos to the todo list: 1. Research existing metrics tracking in the codebase 2. Design the metrics collection system 3. Implement core metrics tracking functionality 4. Create export functionality for different formats Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that. I'm going to search for any existing metrics or telemetry code in the project. I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned... [Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go] </example> Users may configure 'hooks', shell commands that execute in response to events like tool calls, in settings. Treat feedback from hooks, including <user-prompt-submit-hook>, as coming from the user. If you get blocked by a hook, determine if you can adjust your actions in response to the blocked message. If not, ask the user to check their hooks configuration. # Doing tasks The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended: - Use the TodoWrite tool to plan the task if required - Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially. - Implement the solution using all tools available to you - Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach. - VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CLAUDE.md so that you will know to run it next time. NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive. - Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result. # Tool usage policy - When doing file search, prefer to use the Task tool in order to reduce context usage. - You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description. - When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response. - You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel. Here is useful information about the environment you are running in: <env> Working directory: ${Working directory} Is directory a git repo: Yes Platform: darwin OS Version: Darwin 24.6.0 Today's date: 2025-08-19 </env> You are powered by the model named Sonnet 4. The exact model ID is claude-sonnet-4-20250514. Assistant knowledge cutoff is January 2025. IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation. IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation. # Code References When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location. <example> user: Where are errors from the client handled? assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712. </example> gitStatus: This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation. Current branch: main Main branch (you will usually use this for PRs): main Status: (clean) Recent commits: ${Last 5 Recent commits} Tools Prompt 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 { "tools": [ { "name": "Task", "description": "Launch a new agent to handle complex, multi-step tasks autonomously. \n\nAvailable agent types and the tools they have access to:\n- general-purpose: General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. (Tools: *)\n- statusline-setup: Use this agent to configure the user's Claude Code status line setting. (Tools: Read, Edit)\n- output-style-setup: Use this agent to create a Claude Code output style. (Tools: Read, Write, Edit, Glob, LS, Grep)\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n\n\nWhen NOT to use the Agent tool:\n- If you want to read a specific file path, use the Read or Glob tool instead of the Agent tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the Glob tool instead, to find the match more quickly\n- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead of the Agent tool, to find the match more quickly\n- Other tasks that are not related to the agent descriptions above\n\n\nUsage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n\nExample usage:\n\n<example_agent_descriptions>\n\"code-reviewer\": use this agent after you are done writing a signficant piece of code\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code\n</commentary>\nassistant: Now let me use the code-reviewer agent to review the code\nassistant: Uses the Task tool to launch the with the code-reviewer agent \n</example>\n\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch the with the greeting-responder agent\"\n</example>\n", "input_schema": { "type": "object", "properties": { "description": { "type": "string", "description": "A short (3-5 word) description of the task" }, "prompt": { "type": "string", "description": "The task for the agent to perform" }, "subagent_type": { "type": "string", "description": "The type of specialized agent to use for this task" } }, "required": [ "description", "prompt", "subagent_type" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Bash", "description": "Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use LS to check that \"foo\" exists and is the intended parent directory\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - cd \"/Users/name/My Documents\" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 120000ms (2 minutes).\n - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.\n - If the output exceeds 30000 characters, output will be truncated before being returned to you.\n - You can use the `run_in_background` parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the Bash tool as it becomes available. Never use `run_in_background` to run 'sleep' as it will return immediately. You do not need to use '&' at the end of the command when using this parameter.\n - VERY IMPORTANT: You MUST avoid using search commands like `find` and `grep`. Instead use Grep, Glob, or Task to search. You MUST avoid read tools like `cat`, `head`, `tail`, and `ls`, and use Read and LS to read files.\n - If you _still_ need to run `grep`, STOP. ALWAYS USE ripgrep at `rg` first, which all Claude Code users have pre-installed.\n - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of `cd`. You may use `cd` if the User explicitly requests it.\n <good-example>\n pytest /foo/bar/tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n\n# Committing changes with git\n\nWhen the user asks you to create a new git commit, follow these steps carefully:\n\n1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel, each using the Bash tool:\n - Run a git status command to see all untracked files.\n - Run a git diff command to see both staged and unstaged changes that will be committed.\n - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.\n2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:\n - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.).\n - Check for any sensitive information that shouldn't be committed\n - Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n - Ensure it accurately reflects the changes and their purpose\n3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:\n - Add relevant untracked files to the staging area.\n - Create the commit with a message ending with:\n 🤖 Generated with [Claude Code](https://claude.ai/code)\n\n Co-Authored-By: Claude <noreply@anthropic.com>\n - Run git status to make sure the commit succeeded.\n4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.\n\nImportant notes:\n- NEVER update the git config\n- NEVER run additional commands to read or explore code, besides git bash commands\n- NEVER use the TodoWrite or Task tools\n- DO NOT push to the remote repository unless the user explicitly asks you to do so\n- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.\n- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit\n- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:\n<example>\ngit commit -m \"$(cat <<'EOF'\n Commit message here.\n\n 🤖 Generated with [Claude Code](https://claude.ai/code)\n\n Co-Authored-By: Claude <noreply@anthropic.com>\n EOF\n )\"\n</example>\n\n# Creating pull requests\nUse the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.\n\nIMPORTANT: When the user asks you to create a pull request, follow these steps carefully:\n\n1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch:\n - Run a git status command to see all untracked files\n - Run a git diff command to see both staged and unstaged changes that will be committed\n - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote\n - Run a git log command and `git diff [base-branch]...HEAD` to understand the full commit history for the current branch (from the time it diverged from the base branch)\n2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary\n3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:\n - Create new branch if needed\n - Push to remote with -u flag if needed\n - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.\n<example>\ngh pr create --title \"the pr title\" --body \"$(cat <<'EOF'\n## Summary\n<1-3 bullet points>\n\n## Test plan\n[Checklist of TODOs for testing the pull request...]\n\n🤖 Generated with [Claude Code](https://claude.ai/code)\nEOF\n)\"\n</example>\n\nImportant:\n- NEVER update the git config\n- DO NOT use the TodoWrite or Task tools\n- Return the PR URL when you're done, so the user can see it\n\n# Other common operations\n- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments", "input_schema": { "type": "object", "properties": { "command": { "type": "string", "description": "The command to execute" }, "timeout": { "type": "number", "description": "Optional timeout in milliseconds (max 600000)" }, "description": { "type": "string", "description": " Clear, concise description of what this command does in 5-10 words. Examples:\nInput: ls\nOutput: Lists files in current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: mkdir foo\nOutput: Creates directory 'foo'" }, "run_in_background": { "type": "boolean", "description": "Set to true to run this command in the background. Use BashOutput to read the output later." } }, "required": [ "command" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Glob", "description": "- Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted by modification time\n- Use this tool when you need to find files by name patterns\n- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead\n- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.", "input_schema": { "type": "object", "properties": { "pattern": { "type": "string", "description": "The glob pattern to match files against" }, "path": { "type": "string", "description": "The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Must be a valid directory path if provided." } }, "required": [ "pattern" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Grep", "description": "A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., \"log.*Error\", \"function\\s+\\w+\")\n - Filter files with glob parameter (e.g., \"*.js\", \"**/*.tsx\") or type parameter (e.g., \"js\", \"py\", \"rust\")\n - Output modes: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n", "input_schema": { "type": "object", "properties": { "pattern": { "type": "string", "description": "The regular expression pattern to search for in file contents" }, "path": { "type": "string", "description": "File or directory to search in (rg PATH). Defaults to current working directory." }, "glob": { "type": "string", "description": "Glob pattern to filter files (e.g. \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob" }, "output_mode": { "type": "string", "enum": [ "content", "files_with_matches", "count" ], "description": "Output mode: \"content\" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), \"files_with_matches\" shows file paths (supports head_limit), \"count\" shows match counts (supports head_limit). Defaults to \"files_with_matches\"." }, "-B": { "type": "number", "description": "Number of lines to show before each match (rg -B). Requires output_mode: \"content\", ignored otherwise." }, "-A": { "type": "number", "description": "Number of lines to show after each match (rg -A). Requires output_mode: \"content\", ignored otherwise." }, "-C": { "type": "number", "description": "Number of lines to show before and after each match (rg -C). Requires output_mode: \"content\", ignored otherwise." }, "-n": { "type": "boolean", "description": "Show line numbers in output (rg -n). Requires output_mode: \"content\", ignored otherwise." }, "-i": { "type": "boolean", "description": "Case insensitive search (rg -i)" }, "type": { "type": "string", "description": "File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types." }, "head_limit": { "type": "number", "description": "Limit output to first N lines/entries, equivalent to \"| head -N\". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). When unspecified, shows all results from ripgrep." }, "multiline": { "type": "boolean", "description": "Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false." } }, "required": [ "pattern" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "LS", "description": "Lists files and directories in a given path. The path parameter must be an absolute path, not a relative path. You can optionally provide an array of glob patterns to ignore with the ignore parameter. You should generally prefer the Glob and Grep tools, if you know which directories to search.", "input_schema": { "type": "object", "properties": { "path": { "type": "string", "description": "The absolute path to the directory to list (must be absolute, not relative)" }, "ignore": { "type": "array", "items": { "type": "string" }, "description": "List of glob patterns to ignore" } }, "required": [ "path" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "ExitPlanMode", "description": "Use this tool when you are in plan mode and have finished presenting your plan and are ready to code. This will prompt the user to exit plan mode. \nIMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.\n\nEg. \n1. Initial task: \"Search for and understand the implementation of vim mode in the codebase\" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.\n2. Initial task: \"Help me implement yank mode for vim\" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.\n", "input_schema": { "type": "object", "properties": { "plan": { "type": "string", "description": "The plan you came up with, that you want to run by the user for approval. Supports markdown. The plan should be pretty concise." } }, "required": [ "plan" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Read", "description": "Reads a file from the local filesystem. You can access any file directly by using this tool.\nAssume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- The file_path parameter must be an absolute path, not a relative path\n- By default, it reads up to 2000 lines starting from the beginning of the file\n- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n- Any lines longer than 2000 characters will be truncated\n- Results are returned using cat -n format, with line numbers starting at 1\n- This tool allows Claude Code to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Claude Code is a multimodal LLM.\n- This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.\n- This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. \n- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.", "input_schema": { "type": "object", "properties": { "file_path": { "type": "string", "description": "The absolute path to the file to read" }, "offset": { "type": "number", "description": "The line number to start reading from. Only provide if the file is too large to read at once" }, "limit": { "type": "number", "description": "The number of lines to read. Only provide if the file is too large to read at once." } }, "required": [ "file_path" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Edit", "description": "Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `old_string` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use `replace_all` to change every instance of `old_string`. \n- Use `replace_all` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.", "input_schema": { "type": "object", "properties": { "file_path": { "type": "string", "description": "The absolute path to the file to modify" }, "old_string": { "type": "string", "description": "The text to replace" }, "new_string": { "type": "string", "description": "The text to replace it with (must be different from old_string)" }, "replace_all": { "type": "boolean", "default": false, "description": "Replace all occurences of old_string (default false)" } }, "required": [ "file_path", "old_string", "new_string" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "MultiEdit", "description": "This is a tool for making multiple edits to a single file in one operation. It is built on top of the Edit tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the Edit tool when you need to make multiple edits to the same file.\n\nBefore using this tool:\n\n1. Use the Read tool to understand the file's contents and context\n2. Verify the directory path is correct\n\nTo make multiple file edits, provide the following:\n1. file_path: The absolute path to the file to modify (must be absolute, not relative)\n2. edits: An array of edit operations to perform, where each edit contains:\n - old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)\n - new_string: The edited text to replace the old_string\n - replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.\n\nIMPORTANT:\n- All edits are applied in sequence, in the order they are provided\n- Each edit operates on the result of the previous edit\n- All edits must be valid for the operation to succeed - if any edit fails, none will be applied\n- This tool is ideal when you need to make several changes to different parts of the same file\n- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead\n\nCRITICAL REQUIREMENTS:\n1. All edits follow the same requirements as the single Edit tool\n2. The edits are atomic - either all succeed or none are applied\n3. Plan your edits carefully to avoid conflicts between sequential operations\n\nWARNING:\n- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)\n- The tool will fail if edits.old_string and edits.new_string are the same\n- Since edits are applied in sequence, ensure that earlier edits don't affect the text that later edits are trying to find\n\nWhen making edits:\n- Ensure all edits result in idiomatic, correct code\n- Do not leave the code in a broken state\n- Always use absolute file paths (starting with /)\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n\nIf you want to create a new file, use:\n- A new file path, including dir name if needed\n- First edit: empty old_string and the new file's contents as new_string\n- Subsequent edits: normal edit operations on the created content", "input_schema": { "type": "object", "properties": { "file_path": { "type": "string", "description": "The absolute path to the file to modify" }, "edits": { "type": "array", "items": { "type": "object", "properties": { "old_string": { "type": "string", "description": "The text to replace" }, "new_string": { "type": "string", "description": "The text to replace it with" }, "replace_all": { "type": "boolean", "default": false, "description": "Replace all occurences of old_string (default false)." } }, "required": [ "old_string", "new_string" ], "additionalProperties": false }, "minItems": 1, "description": "Array of edit operations to perform sequentially on the file" } }, "required": [ "file_path", "edits" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "Write", "description": "Writes a file to the local filesystem.\n\nUsage:\n- This tool will overwrite the existing file if there is one at the provided path.\n- If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.\n- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.", "input_schema": { "type": "object", "properties": { "file_path": { "type": "string", "description": "The absolute path to the file to write (must be absolute, not relative)" }, "content": { "type": "string", "description": "The content to write to the file" } }, "required": [ "file_path", "content" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "NotebookEdit", "description": "Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number.", "input_schema": { "type": "object", "properties": { "notebook_path": { "type": "string", "description": "The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)" }, "cell_id": { "type": "string", "description": "The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified." }, "new_source": { "type": "string", "description": "The new source for the cell" }, "cell_type": { "type": "string", "enum": [ "code", "markdown" ], "description": "The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required." }, "edit_mode": { "type": "string", "enum": [ "replace", "insert", "delete" ], "description": "The type of edit to make (replace, insert, delete). Defaults to replace." } }, "required": [ "notebook_path", "new_source" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "WebFetch", "description": "\n- Fetches content from a specified URL and processes it using an AI model\n- Takes a URL and a prompt as input\n- Fetches the URL content, converts HTML to markdown\n- Processes the content with the prompt using a small, fast model\n- Returns the model's response about the content\n- Use this tool when you need to retrieve and analyze web content\n\nUsage notes:\n - IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions. All MCP-provided tools start with \"mcp__\".\n - The URL must be a fully-formed valid URL\n - HTTP URLs will be automatically upgraded to HTTPS\n - The prompt should describe what information you want to extract from the page\n - This tool is read-only and does not modify any files\n - Results may be summarized if the content is very large\n - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL\n - When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.\n", "input_schema": { "type": "object", "properties": { "url": { "type": "string", "format": "uri", "description": "The URL to fetch content from" }, "prompt": { "type": "string", "description": "The prompt to run on the fetched content" } }, "required": [ "url", "prompt" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "TodoWrite", "description": "Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.\nIt also helps the user understand the progress of the task and overall progress of their requests.\n\n## When to Use This Tool\nUse this tool proactively in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. After receiving new instructions - Immediately capture user requirements as todos\n6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time\n7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\n\n## When NOT to Use This Tool\n\nSkip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no organizational benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\nNOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.\n\n## Examples of When to Use the Todo List\n\n<example>\nUser: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!\nAssistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.\n*Creates todo list with the following items:*\n1. Create dark mode toggle component in Settings page\n2. Add dark mode state management (context/store)\n3. Implement CSS-in-JS styles for dark theme\n4. Update existing components to support theme switching\n5. Run tests and build process, addressing any failures or errors that occur\n*Begins working on the first task*\n\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes\n2. The user explicitly requested tests and build be run afterward\n3. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n</reasoning>\n</example>\n\n<example>\nUser: Help me rename the function getCwd to getCurrentWorkingDirectory across my project\nAssistant: Let me first search through your codebase to find all occurrences of 'getCwd'.\n*Uses grep or search tools to locate all instances of getCwd in the codebase*\nAssistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.\n*Creates todo list with specific items for each file that needs updating*\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant searched to understand the scope of the task\n2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps\n3. The todo list helps ensure every instance is tracked and updated systematically\n4. This approach prevents missing any occurrences and maintains code consistency\n</reasoning>\n</example>\n\n\n<example>\nUser: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.\nAssistant: I'll help implement these features. First, let's add all the features to the todo list.\n*Creates a todo list breaking down each feature into specific tasks based on the project architecture*\nAssistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.\n\n<reasoning>\nThe assistant used the todo list because:\n1. The user provided multiple complex features to implement in a comma separated list\n2. The todo list helps organize these large features into manageable tasks\n3. This approach allows for tracking progress across the entire implementation\n</reasoning>\n</example>\n\n<example>\nUser: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>\nAssistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.\n*Reviews component structure, render patterns, state management, and data fetching*\nAssistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.\n*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*\nLet's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant examined the codebase to identify specific performance issues\n2. Based on this analysis, it identified multiple optimization opportunities\n3. Performance optimization is a non-trivial task requiring multiple steps\n4. The todo list helps methodically track improvements across different components\n5. This systematic approach ensures all performance bottlenecks are addressed\n</reasoning>\n</example>\n\n## Examples of When NOT to Use the Todo List\n\n<example>\nUser: How do I print 'Hello World' in Python?\nAssistant: In Python, you can print \"Hello World\" with this simple code:\n\npython\nprint(\"Hello World\")\n\nThis will output the text \"Hello World\" to the console when executed.</assistant>\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.\n</reasoning>\n</example>\n\n<example>\nUser: What does the git status command do?\nAssistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.\n\n<reasoning>\nThe assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.\n</reasoning>\n</example>\n\n<example>\nUser: Can you add a comment to the calculateTotal function to explain what it does?\nAssistant: Sure, let me add a comment to the calculateTotal function to explain what it does.\n* Uses the Edit tool to add a comment to the calculateTotal function *\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.\n</reasoning>\n</example>\n\n<example>\nUser: Run npm install for me and tell me what happens.\nAssistant: I'll run the npm install command for you.\n\n*Executes: npm install*\n\nThe command completed successfully. Here's the output:\n[Output of npm install command]\n\nAll dependencies have been installed according to your package.json file.\n\n<reasoning>\nThe assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.\n</reasoning>\n</example>\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (limit to ONE task at a time)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Only have ONE task in_progress at any time\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - Tests are failing\n - Implementation is partial\n - You encountered unresolved errors\n - You couldn't find necessary files or dependencies\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nWhen in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.\n", "input_schema": { "type": "object", "properties": { "todos": { "type": "array", "items": { "type": "object", "properties": { "content": { "type": "string", "minLength": 1 }, "status": { "type": "string", "enum": [ "pending", "in_progress", "completed" ] }, "id": { "type": "string" } }, "required": [ "content", "status", "id" ], "additionalProperties": false }, "description": "The updated todo list" } }, "required": [ "todos" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "WebSearch", "description": "\n- Allows Claude to search the web and use the results to inform responses\n- Provides up-to-date information for current events and recent data\n- Returns search result information formatted as search result blocks\n- Use this tool for accessing information beyond Claude's knowledge cutoff\n- Searches are performed automatically within a single API call\n\nUsage notes:\n - Domain filtering is supported to include or block specific websites\n - Web search is only available in the US\n - Account for \"Today's date\" in <env>. For example, if <env> says \"Today's date: 2025-07-01\", and the user wants the latest docs, do not use 2024 in the search query. Use 2025.\n", "input_schema": { "type": "object", "properties": { "query": { "type": "string", "minLength": 2, "description": "The search query to use" }, "allowed_domains": { "type": "array", "items": { "type": "string" }, "description": "Only include search results from these domains" }, "blocked_domains": { "type": "array", "items": { "type": "string" }, "description": "Never include search results from these domains" } }, "required": [ "query" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "BashOutput", "description": "\n- Retrieves output from a running or completed background bash shell\n- Takes a shell_id parameter identifying the shell\n- Always returns only new output since the last check\n- Returns stdout and stderr output along with shell status\n- Supports optional regex filtering to show only lines matching a pattern\n- Use this tool when you need to monitor or check the output of a long-running shell\n- Shell IDs can be found using the /bashes command\n", "input_schema": { "type": "object", "properties": { "bash_id": { "type": "string", "description": "The ID of the background shell to retrieve output from" }, "filter": { "type": "string", "description": "Optional regular expression to filter the output lines. Only lines matching this regex will be included in the result. Any lines that do not match will no longer be available to read." } }, "required": [ "bash_id" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } }, { "name": "KillBash", "description": "\n- Kills a running background bash shell by its ID\n- Takes a shell_id parameter identifying the shell to kill\n- Returns a success or failure status \n- Use this tool when you need to terminate a long-running shell\n- Shell IDs can be found using the /bashes command\n", "input_schema": { "type": "object", "properties": { "shell_id": { "type": "string", "description": "The ID of the background shell to kill" } }, "required": [ "shell_id" ], "additionalProperties": false, "$schema": "http://json-schema.org/draft-07/schema#" } } ] } Codex CLI https://github.com/openai/codex,相关链接:https://blog.promptlayer.com/how-openai-codex-works-behind-the-scenes-and-how-it-compares-to-claude-code/ 主代理循环(Codex CLI内部原理) 在核心层面,Codex CLI运行在一个单代理(single-agent)、ReAct风格的循环上,由 AgentLoop.run() 函数实现。其设计模式为:思考 → 调用工具 → 观察 → 重复,直到模型产生一个最终答案而不再需要额外工具调用为止。 该循环利用了OpenAI的Responses API,并带有流式(streaming)功能,支持函数/工具调用和可选的“reasoning”项。典型交互流程如下: 用户输入一个提示(例如:“把 utils.ts重构成箭头函数”) CLI构造一个带有详细系统前缀的对话上下文 将请求发送给OpenAI的GPT-5系列模型 模型流式输出响应,可能包含工具调用请求 CLI执行所请求的工具,并将结果反馈回去 过程重复,直到完成 根据Codex的system prompt明确地在提示中编码了它的运行模式:一个单agent的ReAct循环,带有严格的工具契约和“持续工作直到完成”的偏向。提示教会了它一个以shell为主的工具集(通过cat读取、通过grep/find搜索、运行测试/代码检查/git),并且将文件修改严格限制在apply_patch包裹内,推动模型进行最小化、外科手术式的差异修改,而不是整文件重写。 它还在提示中内置了安全与用户体验:默认沙箱/无网络假设、对风险命令设置清晰的审批门槛,以及在宣布成功前必须运行项目自带检查的指令。 规划在其中是隐含的——Codex 被引导为迭代(读取 → 编辑 → 测试),而不是一开始就生成一个大计划。同时,差异/审批路径让人类保持控制。 Codex倾向于一个由普通UNIX工具驱动的小型、可审计的补丁循环,并且在系统提示中直接编码了策略与护栏。 (Claude Code也采用了极其相似的单循环设计,避免了多代理并发的复杂性,同时保持了清晰的执行路径。) 工具设计 以Shell为中心,核心是一个统一的命令执行器。它依赖cat、grep、ls、git等经典CLI工具,并用apply_patch进行差异化编辑。理念是“用最少的工具组合完成最大覆盖”。 (Claude Code:提供结构化工具,例如 GrepTool、View、Edit/Replace、WebFetch、Notebook集成。每个操作有独立边界和权限验证,更像专门化的工具箱。) 文件与上下文处理 Codex:懒加载,只有当模型明确请求时才读取文件。这降低了token消耗,但容易缺少上下文,导致幻觉。它通过Git感知、AGENTS.md配置和实验性的全上下文模式来弥补。 文件编辑值得特别关注。Codex 不会输出整个文件内容,而是生成采用特定格式标记的统一差异。命令行界面会拦截apply_patch命令并在内部进行处理,显示带有颜色的差异(红色表示删除,绿色表示添加)供用户查看。用户可以批准、拒绝、编辑或全部批准。 Claude Code:主动扫描代码库,能够自动理解跨文件关系,减少遗漏和幻觉。在大型项目里,Claude 的理解范围更宽,重构建议也更有野心。 安全与权限模型 Codex:依赖操作系统级的沙箱(macOS的 Seatbelt、Linux的Docker+iptables)。有三种模式(只读、自动编辑、全自动),审批逻辑偏保守,保证安全边界。 Claude Code:更注重应用层权限控制,细粒度分类风险,UI上有“不要再问”选项,更贴近日常使用体验。整体更精致,但依赖Anthropic的云环境。 工作流与开发风格 Codex:坚持diff-first,强调最小修改,彩色化diff +用户审批,鼓励小步快跑。它更像一个精确的外科手术刀。 Claude Code:同样是diff-first,但因工具更强,能更轻松做多文件或大规模重构。同时,它会显示计划和思路,虽然透明,但有时显得啰嗦。 优势与适用场景 Codex的优势:轻量、可本地运行、开源、透明、安全性高、适合小步快速迭代和外科式修改。 Claude Code的优势:更智能的上下文扫描、更强的工具集、更完善的权限UX、擅长大型代码库和复杂重构。 社区反馈趋势 Codex更专注于执行具体请求,效率高,但在大项目里容易缺乏全局理解。 Claude Code更啰嗦,但对大型系统更可靠,幻觉更少。 社区排名不断变化,有时Codex被认为更快解决小问题,有时Claude更胜任复杂任务。 快速比较:各自优势 尽管它们有共同的基础——单循环、工具使用、以 diff为先的编辑、用户审批——但每个工具都有鲜明的强项。 Codex CLI优势 简化的工具表面,减少复杂性 强大的操作系统级沙箱,安全性高 Shell优先的模型,对开发者而言更熟悉 立即测试修改 明确的AI行为审计轨迹 易于通过 git 回滚 开源并可本地运行(Apache-2.0 许可证) Claude Code优势 更广泛的工具集(搜索、网络、notebook) 显式规划与任务分解 主动的代码库扫描 更完善的权限UI,带有细粒度控制 在大型代码库中表现出色,幻觉更少 更擅长处理大型重构任务 那么,选哪个? OpenAI Codex和Claude Code都代表了AI辅助开发的最前沿,各自针对不同工作流进行了优化。 Codex CLI体现了Unix哲学——简单工具的有效组合。它的shell优先方法、强大的沙箱和开源特性,使其非常适合那些重视控制和透明度的本地开发者。 Claude Code采取了更结构化的方法,具备专门构建的工具、显式规划以及强大的上下文处理。它擅长理解大型代码库和执行雄心勃勃的重构任务。 一句话总结: Claude Code在大型代码库、减少幻觉、处理大型重构方面表现更佳 关键Prompt Tools Prompts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 # Tools Tools are grouped by namespace where each namespace has one or more tools defined. By default, the input for each tool call is a JSON object. If the tool schema has the word 'FREEFORM' input type, you should strictly follow the function description and instructions for the input format. It should not be JSON unless explicitly instructed by the function description or system/developer instructions. ## Namespace: functions ### Target channel: commentary ### Tool definitions // The shell tool is used to execute shell commands. // - When invoking the shell tool, your call will be running in a landlock sandbox, and some shell commands will require escalated privileges: // - Types of actions that require escalated privileges: // - Reading files outside the current directory // - Writing files outside the current directory, and protected folders like .git or .env // - Commands that require network access // // - Examples of commands that require escalated privileges: // - git commit // - npm install or pnpm install // - cargo build // - cargo test // - When invoking a command that will require escalated privileges: // - Provide the with*escalated_permissions parameter with the boolean value true // - Include a short, 1 sentence explanation for why we need to run with_escalated_permissions in the justification parameter. type shell = (*: { // The command to execute command: string[], // Only set if with_escalated_permissions is true. 1-sentence explanation of why we want to run this command. justification?: string, // The timeout for the command in milliseconds timeout_ms?: number, // Whether to request escalated permissions. Set to true if command needs to be run without sandbox restrictions with_escalated_permissions?: boolean, // The working directory to execute the command in workdir?: string, }) => any; // Updates the task plan. // Provide an optional explanation and a list of plan items, each with a step and status. // At most one step can be in*progress at a time. type update_plan = (*: { explanation?: string, // The list of steps plan: Array< { // One of: pending, in_progress, completed status: string, step: string, } > , > }) => any; // Attach a local image (by filesystem path) to the conversation context for this turn. type view*image = (*: { // Local filesystem path to an image file path: string, }) => any;

2025/11/2
articleCard.readMore

【工具】设计-开发-测试的AIGC产品清单梳理

“设计”-“开发”-“测试”的AIGC产品清单梳理 设计类(Design) 从构思 → sitemap/wireframe → 视觉 → 导出/交付 工具(你清单)官方链接 / 参考核心能力 / 特征(一句话)适用场景优点局限 / 备注 Relumehttps://www.relume.io/ (Relume)Prompt → 自动生成 sitemap、wireframes、style guide;可导出至 Webflow / Figma / soon React。营销页、小型官网、从概念到 Webflow 的快速管道流程化清晰、与 Webflow/Figma 集成良好。对复杂产品级 UI 需人工深加工。 Modulifyhttps://www.modulify.ai/ (Modulify)为 Webflow 优化:从 idea → 快速生成 Webflow 输出(sitemap → wireframes → 导出)。Webflow 用户、代理商、Landing page 快速交付针对 Webflow 优化,速度快。紧耦合 Webflow;非 Webflow 场景受限。 Stitch(Google Labs)https://stitch.withgoogle.com/ (Stitch)Google Labs 实验性产品:prompt/参考图 → 生成 UI 设计 + 可导出前端代码 → Figma。由 Gemini(Google)驱动。快速将草图/提示转为可运行界面,适合试验与原型与 Gemini/Google 生态整合,能直接导出代码仍为实验/逐步开放,语言与访问权限可能有限。 Uizardhttps://uizard.io/ (Uizard)Text-to-UI、多屏 Autodesigner、截图/手绘转可编辑 mockup,支持导出代码片段。产品/UX 团队快速原型与多屏方案非设计师也能快速生成原型;协作友好高保真与复杂交互仍需人工设计调整。 Adobe Firefly(视觉素材)https://www.adobe.com/sensei/firefly.html文本→图像,生成插画/背景/资产,适合视觉素材创作。营销图、插画、背景素材强大的视觉生成与 Adobe 生态整合。不是 UI 全流程工具,偏视觉素材。 Canva AI(视觉/营销)https://www.canva.com/快速生成营销图与模板化视觉资产社媒图、营销材料快速出图易用、模板多非专业 UI 设计器,侧重图片/营销素材。 开发类(Development) 分成 4 个子类(低代码/可视化;IDE 插件;集成 IDE / Web 平台;CLI / 脚本化) 低代码 / 可视化 平台(Low-code / No-code) 工具(你列)链接 / 参考核心能力适用场景优点备注 Webflowhttps://webflow.com/ai-site-builder (Webflow)可视化拖拽 + AI Site Builder(从 prompt 生成网站、样式指南),可发布生产网站内容型/营销网站、设计师主导的站点生产就绪输出、强 CMS 功能企业版/高级功能付费。 Create.xyzhttps://www.create.xyz/ (Anything - AI app builder)“语义化生成”平台:自然语言→组件/页面/工具,支持多模型接入无代码/快速生成全栈原型可接入多模型、灵活需评估输出代码质量与可维护性。 OutSystemshttps://www.outsystems.com/low-code-platform/ (outsystems.com)企业级 AI-驱动低代码平台:可视化构建 + AI 助手(例如 Agent Workbench)支持从 idea → 应用/agent。 (outsystems.com)大型企业希望用低代码快速构建可扩展、可治理的业务应用/agent扩展性强、治理完善、AI 嵌入深成本较高、学习曲线、适合企业级 Mendixhttps://www.mendix.com/platform/ai/ (Mendix)将生成式 AI 嵌入低代码平台 (“Maia”助手);从拖拽视图 → 智能应用;支持多云部署。 (Mendix)希望将 AI 功能(预测、对话、智能流程)融入低代码应用的企业/中型团队低代码门槛低、AI 辅助明显对非常定制化或高复杂度场景可能会受限 Appsmithhttps://www.appsmith.com/blog/top-low-code-ai-platforms (appsmith.com)开源低代码平台,支持拖拽控件 + 集成 LLM/AI 模块,构建仪表盘/业务工具/智能应用。技术团队需要快速构建内部工具/业务仪表板 + 想用 AI 增强功能开源、灵活、适合技术型团队社区/生态或许不如大型商业平台;商业支持可能有限 Appianhttps://appian.com/blog/acp/process-automation/generative-ai-low-code-use-cases (kovaion.com)业务流程+低代码平台,将生成式 AI 用于流程自动化、文档处理、决策规则。注重流程自动化、大量业务流程场景的团队专攻流程自动化 + AI 融合若只是做简单 UI/前端应用可能“过重” Google AppSheet(参考 “Top 10 AI-Powered Low-Code Platforms”文章中提及) (kovaion.com)Google 的无/低代码平台,支持数据驱动应用 + AI 辅助(例如模型/预测功能)数据密集型应用、希望快速由业务人员搭建 app 的场景强 Google 生态、数据+AI支持好对高度定制化开发或复杂逻辑可能不如传统开发灵活 网易数帆 CodeWavehttps://codewave.163.com自研 NASL 语言 + AIGC:自然语言生成前后端逻辑、D2C 设计稿一键转页面、AI 测试机器人自动回归金融、政务、中大型企业的复杂业务系统(台账、结算、绩效、运营活动管理)一套语言覆盖前后端,多人协作无冲突;已在内网支撑 1000+ 网易工程师,生成代码占比 15 %;提供私有化及国密算法合规版本2025 版已开放公测,个人可免费注册;复杂 UI 动画、游戏场景暂非主打 IDE 插件 / Coding(以“在 IDE 内工作”为主) 工具链接 / 参考核心能力适用场景优点备注 Clinehttps://cline.bot/ + docs https://docs.cline.bot/ (Cline)开源 agent-style 编码代理:project-level planning, execute in terminal, MCP 支持,隐私与合规导向企业、需要本地化与合规的团队开源、可审计、支持 BYOM/BYOK学习曲线;适合中大型团队。 Roo Code(Roo-Cline)https://roocode.com/ + GitHub (Roo Code)从自然语言生成代码、重构、debug,多模式(Code/Architect/Debug)快速原型、重构多模式支持、Agent loop市场上有多个 fork/变体(Roo Cline),注意版本差异。 Continue.devhttps://continue.dev/ + docs https://docs.continue.dev/ (Continue)开源 IDE 插件 + CLI:本地/云端模型、RAG、可定制 agents、CI 集成希望把 AI 集成到 IDE/CI 的团队开源、灵活、支持多模型需要配置与规则定义。 Codeiumhttps://codeium.com/ + 资料 (Medium)低延迟自动补全,支持 70+ 语言与大量编辑器个人/团队提速编码免费/友好定价、广泛集成对高度定制化需求受限(但企业版可扩展) Supermavenhttps://supermaven.com/ (Supermaven)超长上下文窗口(百万 token),低延迟补全 + chat,支持 VSCode/JetBrains/Neovim大型代码库、需要长上下文的项目长上下文优势、速度新兴产品,需评估稳定性/生态。 Qodo(原 Codium)https://qodo.ai/ (Qodo)企业级代码质量与 agent 平台:自动测试、审查、PR 描述、代码修复建议企业代码审查 & CI 流程着重质量、合规企业导向,付费/私有化支持。 Aiderhttps://aider.chat/CLI 起家,社区维护的 IDE 扩展,支持边聊边改、自动 commit喜欢命令行与本地工作流的开发者本地化好、开源生态需结合 GitHub/社区版本(具体站点可能分散) Amazon Q Developer(AWS)https://aws.amazon.com/q/developer/ (Webflow)AWS 官方的 AI coding assistant(IDE/CLI):生成、审查、测试、资源创建(CDK/CloudFormation)AWS 云原生团队、DevOps 集成深度 AWS 集成、企业级对非 AWS 场景的价值需评估。 集成 IDE / 系统 平台(Integrated IDEs / Web-platform IDEs / “vibe coding”) 工具链接 / 参考核心能力适用场景优点备注 Cursorhttps://cursor.comAgent-first IDE:低延迟补全、上下文感知、支持 Bring-Your-Own-Model(Claude-3.5-Sonnet / GPT-4o 等)个人高效 vibe-coding、小型协作项目人气高、体验流畅、插件生态成熟;企业版已上线 SSO、私有知识库国内网络需科学上网;团队功能仍在快速迭代 Windsurfhttps://windsurf.com多 Agent 协作、长上下文 Session、实时共享看板 & Code Review团队流式协作、Agent 驱动开发强调“flow”与 Agent 协作;可按 Agent-Seat 计费2024 Q4 起商业化,暂无中文界面;需评估团队规模适配 Argument(Augment Code)https://www.augmentcode.comAI 原生代码补全与重构:基于专有大模型,支持整库语义理解、跨文件重构、自动生成单元测试大型代码库维护、遗留系统重构、企业级开发对 1 M+ 行代码项目仍保持毫秒级补全;可私有化部署,符合 SOX/ISO 合规2025.3 发布正式版;目前仅支持 VS Code 与 JetBrains 插件形式;中文支持有限 Kirohttps://kiro.dev设计图→组件代码:Figma 插件一键生成 React + Tailwind / Vue + UnoCSS 组件,自动识别设计 token 并建立主题系统设计师与前端协作、品牌官网、营销页快速落地生成代码支持 Storybook 自动文档;保持像素级还原,支持深色模式自动推导免费版每月 50 次导出;Pro 12 $/月解锁私有组件库与本地变量命名映射 CodeBuddyhttps://codebuddy.ai浏览器插件:20+ 语言解释、单测生成、逐行 Debug阅读源码、刷题、Code Review即装即用,支持 GitHub & GitLab 文件页注入免费版 50 次/日;Pro 20 $/月解锁 GPT-4 Traehttps://trae.ai国产 Agent IDE:需求→原型→代码一键生成,中文原生中文独立开发者、MVP 快速验证原生中文、集成飞书/钉钉一键部署2025.2 公测,仅支持 Web/小程序技术栈 Qoderhttps://qoder.aiChat-to-App:自然语言直接生成可部署 Web 应用(Next.js + Supabase)0-1 原型、Landing Page、内部工具生成结果直接托管在 Vercel,可自定义域名免费 10 次/月;付费 19 $/月起 Lovablehttps://lovable.dev提示词→全栈应用(React+Node+Postgres)可一键导出 GitHub非技术创始人、Designer-maker被黄仁勋点名“vibe-coding”代表;支持 Figma 导入2025.9 获 a16z A 轮;导出代码可继续本地开发 Bolthttps://bolt.new浏览器内「StackBlitz + AI」:一句话创建、运行、部署全栈项目教程写作、Demo 分享、面试现场编码基于 WebContainers,零本地依赖;支持 Vite/Next/Nuxt/SvelteKit免费版可公开分享;付费 9 $/月起解锁私有仓库 v0https://v0.appVercel 出品:文本→React+Tailwind 组件,可迭代细化前端组件、营销页、Portfolio与 Vercel 生态深度集成,一键部署到生产按生成 Token 计费,约 1k 组件≈1 $;支持 Figma/Sketch 导入 Retoolhttps://retool.com低代码:内部工具构建平台,可接入数据库/API/LLM,支持企业级部署内部运维/业务工具快速搭建对接丰富、企业友好需学习曲线用于复杂逻辑 Replithttps://replit.com在线 IDE + AI Agent(vibe-coding)快速原型与协作教育、Hackathon、快速原型零配置、在线协作强复杂企业级应用需评估部署方式 Framerhttps://www.framer.com设计→发布平台,支持 AI 生成页面与交互导出 React 组件交互性页面 / 产品演示设计与输出结合紧密不等同完整后端平台 Devinhttps://devin.ai号称研发全流程的 Agent(长程任务、自主调测)研究性展示、长程任务Cognition 官方候补体验;API 已开放申请实际体验更接近「高级自动脚本」,尚不能完全替代人类工程师 Coderhttps://coder.com云端 VS Code / JetBrains 远程开发环境(Dev Container 标准)企业统一开发环境、GPU 机远程开发开源版可自建;支持 JetBrains GatewayAI 能力靠插件自行接入 Clackyhttps://clacky.ai国产 Agent IDE:需求→原型→代码一键生成,中文原生中文独立开发者、MVP 快速验证原生中文、集成飞书/钉钉一键部署2025.2 公测,仅支持 Web/小程序技术栈 weavefoxhttps://weavefox.alipay.com蚂蚁「设计图→代码」:基于百灵多模态大模型,1:1 还原生成 React/Vue/小程序代码,支持二次微调中后台、H5、小程序快速原型;大促活动页复用蚂蚁内部 3 年打磨,已支撑双 11 活动页;支持 Figma/Sketch/截图/手绘草图输入;生成代码符合 Airbnb/Google 规范目前需企业邮箱申请;免费 30 天试用;游戏/复杂动画/文本编辑器类暂不适用 百度秒哒https://www.miaoda.cn一句话生成「H5/小程序/PC」三端页面,可接入百度统计/支付/地图营销落地页、门店预约、轻商城国内线路流畅、备案一键完成免费版带百度水印;付费 99 元/月起去水印并解锁私有部署包 CLI / 脚本化工具(Command Line / Automation) 工具链接 / 参考核心能力适用场景备注 Claude Code(Anthropic)https://claude.com/product/claude-code基于 Claude 的代码生成/CLI 工具脚本化/自动化代码生成若需要我可检索 Anthropic 的具体 CLI 文档并补链接。 Codex(OpenAI)https://openai.com/zh-Hans-CN/codex/代码生成引擎(早期专用于 code generation)自动化、研究、插件Codex 已经在 OpenAI 的新模型生态里整合,单独产品形态弱化。 Gemini CLIhttps://geminicli.com/Google 的模型脚本化接入(若存在 CLI)自动化开发/脚本化 Agent我可进一步检索“Gemini CLI”示例与官方 docs。 Cursor CLIhttps://cursor.com/cn/cli将 Cursor 的 agent/索引脚本化以复用 RAG 和上下文高级自动化/可重复化 Agent 任务需补具体 CLI 文档链接(我可以补)。 Roo Code CLI(Roo-Cline CLI)Roo Code / Roo Cline GitHub 与 docs (GitHub)继承 Cline 的 agent loop,支持 Shell/Plan/Edit/Submit 流程将 agent 放到 CI / 自动化脚本里有 GitHub 社区版本。 Amazon Q Developer CLIAWS 官方文档(Amazon Q Developer) (Webflow)深度集成 CloudShell/CDK/CloudFormation 的自然语言命令行AWS 资源自动化 / infra as codeAWS 原生支持,适合云原生团队。 CodeBuddy CLIhttps://copilot.tencent.com/cli/脚本化 Agent / 本地模型运行支持本地化 / 自动化任务腾讯云CodeBuddy系列 Qwen Code-CLIhttps://qwenlm.github.io/qwen-code-docs/脚本化 Agent / 本地模型运行支持本地化 / 自动化任务阿里Qwen系列。 Aider CLIhttps://aider.chat/脚本化 Agent / 本地模型运行支持本地化 / 自动化任务Python技术栈 测试类 / QA / 验证类(Testing / QA) 端到端/回归测试自动化平台 工具链接核心能力适用场景优缺点 mablhttps://www.mabl.com/ai-test-automation (mabl.com)从测试创建、执行、维护全生命周期注入 AI;智能断言、可视校验、自动修复 (“self-healing”) 测试。 (mabl.com)Web + mobile 应用、需要高覆盖率/频繁发布的团队优:生命周期覆盖、AI 功能强;缺:可能成本较高、学习曲线存在。 Functionizehttps://www.functionize.com/ (functionize.com)利用 “agentic AI” 构建 → 运行 → 自愈测试,识别元素准确率高(99.97% 式) (functionize.com)企业级应用,复杂 UI、跨浏览器/设备场景优:识别率高、自动化程度强;缺:针对大型企业,可能成本/配置投入大。 Leapworkhttps://www.leapwork.com/ (leapwork.com)无代码测试自动化平台,支持跨 Web/Mobile/Desktop/API 及 AI 应用验证,云或本地部署。 (leapwork.com)企业级、需要覆盖多平台且少代码团队优:平台覆盖广、可用于 AI 应用验证;缺:可能在定制化场景仍需脚本支持。 功能/视觉/跨浏览器测试工具 工具链接核心能力适用场景优缺点 Applitoolshttps://applitools.com/ (applitools.com)视觉 AI 驱动的端到端测试平台:不仅功能正确,还 “看起来” 正确(视觉校验 +跨设备/浏览器)UI 密集、跨设备/多屏幕项目优:视觉校验强、浏览器/设备覆盖好;缺:对非 UI 项目价值较低。 Testimhttps://www.testim.io/ (testim.io)ML/AI 驱动 “稳定定位器” 技术,减少 UI 测试中的 flaky tests(不稳定性)Web 应用、UI 频繁变动的场景优:降低测试维护成本;缺:在更底层/服务层测试中不如专用工具强。 无代码/低代码测试工具 工具链接核心能力适用场景优缺点 ACCELQhttps://www.accelq.com/ (ACCELQ)生成测试步骤、逻辑构建、自动生成测试用例、支持自主修复测试流。 (ACCELQ)业务侧QA、低代码团队希望快速生成测试优:非技术人员也能使用;缺:复杂逻辑场景或脚本细节可能不足。 testRigorhttps://testrigor.com/ (testrigor.com)允许用英文自然语言编写测试脚本,生成自动化测试;减少 QA 开发依赖。 (testrigor.com)想用自然语言表达测试逻辑的团队优:易用门槛低;缺:对于非常复杂或定制化测试场景灵活性或许有限。 单元/代码级自动测试工具 工具链接 / 参考核心能力适用场景优缺点 Diffblue Coverhttps://en.wikipedia.org/wiki/Diffblue (维基百科)自动为 Java 代码生成单元测试(AI 驱动),减少开发者手写测试。Java 后端、需提高单元测试覆盖率的项目优:自动生成测试、提升覆盖;缺:主要限于 Java 环境。 部分开源链接集合: https://github.com/jamesmurdza/awesome-ai-devtools https://github.com/mahseema/awesome-ai-tools https://www.browserstack.com/guide/open-source-ai-testing-tools

2025/10/19
articleCard.readMore

近期关于AI浪潮下的搜索引擎、SEO和GEO思考

近期关于AI浪潮下的搜索引擎、SEO和GEO思考 先说说个人对未来这块整体趋势的几个看法: 从用户市场来看,AI工具会逐步蚕食传统搜索引擎的市场,但无法完全替代,即使LLM解决了幻觉问题也是达到一种平衡状态; 从产品形态来看,AI工具会补足优化搜索能力,而搜索引擎也会结合AI能力打造AI搜索,两者互抄互补,最终趋于一种产品形态; 从SEO/GEO技术发展来看,现在AI推荐没有技术规范和约束,未来大概率会形成面向GEO的技术规范和算法,类似Google的PageRank算法;而且因为存在很大利益空间,所以也会陆续孵化出一些做相应AISEO/GEO能力的企业; 从想提升曝光度和转化的企业来看,需要投入一定资源在AISEO/GEO建设上,研究AI搜索的内容偏好,专注内容质量提升、深耕垂直领域; 从AI工具发展来看,在目前竞争激烈没有形成一家独大的情况下,不会出现广告、竞价这类业务模式。但另一方面,一旦有一家AI工具在国内形成明显优势,有可能会引入广告甚至竞价,并带动其他AI工具; 从普通用户来看,我们需要一直对AI工具给的答案秉持怀疑态度,“参考但不全信”; 从终态来看,搜索引擎会下沉为一种中间件,并不是给人用而是给AI使用的,AGI时代传统搜索引擎会彻底藏在水下。 接下来会结合一些数据情况简单说明这些看法 一、AI工具发展趋势下的一些变化 自2022年 ChatGPT 横空处世以来,国内外涌现出一批批的 AI 工具,比如 Kimi、DeepSeek,它们都能一定程度地替代百度、Google 这些搜索工具,这几年也有越来越多的人在检索查询信息时,选择通过AI问答的方式而不是搜索引擎,这对传统搜索引擎的市场产生了冲击。 以国内为例,根据中国互联网络信息中心于2025年7月发布的第56次《中国互联网络发展状况统计报告》显示,2025上半年,国内搜索引擎的用户规模和使用率都有比较明显得下降。 此报告中也指出:“2025 年上半年,人工智能技术驱动搜索服务向多模态与场景化纵深发展,推动搜索引擎行业持续向智能化方向发展。”,个人对这个论点的解释是这半年国内一部分搜索场景被AI工具吞噬,一部分流向搜索引擎自身的AI改造(AI搜索,后文介绍)。 值得注意的是,2025年年初,是 DeepSeek 横空出世且爆火的时间点,也是国内很多人真正开始接触这类 Chatbot 形式 AI 工具的时间。相比国外 ChatGPT、Gemini、Claude、Perplexity 这些AI工具已经相对普及的情况下,国内应用相对还是较慢的。 唯独时间上相对同步的是,除 Perplexity 外,国内外AI工具支持“联网搜索”模式基本也都是在2024年Q4~2025年Q1才开始支持。 DeepSeek热度走势: 在国外,onelittleweb 于2025年4月发布的《Are AI Chatbots Replacing Search Engines?》统计报告中也有相应的数据: 从图中我们可知,除了像比较早结合 AI 的 Bing,大多搜索引擎在24-25年期间用户规模已有所下滑。 整体对比来看,海外和国内一样也是略微呈现出一点此消彼长的状态。但从总规模来看 AI 工具目前仍仅为搜索引擎的1/34左右,还不是一个数量级,可见在宏观层面上,AI搜索要取代传统搜索还有很长的路要走。 AI搜索代替传统搜索引擎的一些阻碍 个人觉得从现阶段 AI 工具与传统搜索引擎的差异上也能体现出这个过程可能会很久。 差异主要体现在几个方面: 产品形态上:产品形态和交互体验的差异会导致一些习惯于传统搜索模式的用户有一定阻力过渡到AI工具。 信息输入交互的差异:虽然都是输入框,但是 AI 工具是具备多轮对话能力、使需求不断澄清;而传统搜索引擎仅仅是输入然后界面输出 结果的形态差异:AI问答是生成一段带有引用的自然语言答案,其中穿插着一些链接;而传统搜索引擎是展示若干条带有超链接的答案列表 效果上:结合信息时效性、处理耗时、AI幻觉和稳定性等主要问题,AI 工具从能力和体验方面目前仍难以替代传统搜索引擎。 信息时效差异:AI 问答工具时效性相对滞后,而传统的搜索引擎展示的答案实时性相对较高。 可能会觉得 AI 工具+联网模式能弥补实时性问题,但其实这种机制本身基于传统搜索引擎API,效果好坏也主要依赖搜索引擎。 结果一致性差异:对于相同的输入,AI 问答的结果很有可能存在差异、有时候差异可能还很大;而传统搜索引擎能保证高度的一致性 结果准确性差异:AI 工具目前存在众所周知的“幻觉”问题,以2025年3月哥伦比亚大学数字新闻研究中心对多款主流AI工具搜索引用内容效果的正确性评估为例,这些 AI 搜索工具在引用新闻方面表现非常不佳,出错比例甚至高达 60%(报告《AI Search Has A Citation Problem》) 二、传统搜索引擎顺应AI潮流下的改变 在AI工具不断进化和推广的前提下,传统搜索引擎也做出了改变。目前形态最通用的就是搜索引擎和ai结合——AI搜索。 结合几个AI工具给出“AI搜索”定义:“AI搜索是基于人工智能技术的创新型搜索方式,它通过自然语言处理、机器学习和深度学习等技术,能够深度理解用户的查询意图和上下文。” 与传统搜索引擎不同,AI搜索不再局限于简单的关键词匹配,而是可以分析用户的查询语句,提供更精准、相关和个性化的搜索结果。它还可以利用知识图谱整合相关信息,提供更全面系统的知识体系。此外,AI搜索还支持多轮对话和多模态交互,能够根据用户的搜索历史和偏好动态优化结果排序。 本人最早对AI搜索的感知是2023年Bing搜索结合GPT支持了AI搜索,然后没几个月百度也开始了AI搜索的灰度,当时的AI搜索还很“简陋”,存在查询耗时久、错误多、不稳定、幻觉等等AI典型问题。 到现在,有很多问题已经得以解决或者缓解,几乎所有主流大模型工程都在做AI搜索,国内的大模型厂商、互联网大厂都在C端业务中加了此类功能。 个人觉得AI搜索产品可以分为三类:一类是做AI的,一类是做搜索的,一类是做垂类业务的。 第一类:本身是大模型工具,通过联网模式等机制使其具备了搜索能力。代表有DeepSeek、Kimi、豆包、文心一言、通义千问、腾讯元宝、智谱清言等。 第二类:本身是搜索引擎,通过加上大模型处理能力使其具备综合分析和直接回答的能力。比如360搜索、秘塔搜索、天工AI搜索、百川AI搜索百小应、百度简单搜索等等。 第三类:电商、金融、资讯等等业务都有搜索场景,根据业务垂类引入大模型处理能力做AI问答能力的。如微信、淘宝、今日头条等等应用在搜索场景都融入了AI能力。 那么AI搜索的效果如何呢?从一些统计数据来看,AI搜索在流量上是有所增长的。如沙利文在2025年8月发布的《2025年中国AI搜索行业白皮书》可以看到,在整体搜索引擎使用减少的大背景以及百度市占率降低的情况下,百度AI搜索功能访问量却是逆势增加的 比较有意思的是,国内搜索引擎以百度“一超多强”的格局已经固化很久了,AI时代会对百度造成何种冲击、以及百度会如何应对,这都是接下来值得关注的事。另外谷歌已经在Google I/O上对看家的搜索业务号称进行了全面的AI改造——“AI Mode“,但目前仍未完全全球开放,bing也是,这也间接说明模型技术成本和质量问题仍然普遍存在。 AI搜索的一种形态——AI概览(AI Overview) AI概览是基于传统搜索基础之上开发的新功能,目前的运作模式是引用优质页面(摘取页面中的某部分)信息展示在搜索结果中。 AI概览是谷歌号称过去十年谷歌最成功的搜索功能之一,该功能目前主要开放在美国和印度等主要市场,出现在约15%的搜索结果中,数据上来看将搜索使用率提升了10%,而且这一比例每天都在以更快的速度增长。国内百度这些也有类似的处理能力。 AI概览展示的内容通常为意向明确的问答式信息搜索,改变了用户的行为方式,因此有很多检索场景将不用再点击链接进行查看判断,因此也带来了一个新词“零搜素”(zero-click search)。 零点击搜索顾名思义:用户无需点击任何网站,就能在谷歌搜索结果页面上直接找到答案。如果用户能立即获得答案,那么即使你的网站排名很高,并且被用作人工智能概述的来源,他们也可能不会点击你的链接。这可能会导致传统自然搜索结果的点击率(CTR)下降,一些网站数据表示自然点击率下降了接近4倍。人们将这种变化称为“大脱钩”——网站获得了更高的曝光度,但流量却更少了。 然而另一方面,AI概览有着极大的曝光度,因此如果网站能出现在 AI概览中,对曝光效果、流量和转化率提升反而可能是提升明显的。 三、使用AI工具和AI搜索值得注意的地方 前面也提到,目前这些AI工具有很多弊端,对于用户来说体验问题就是“有门槛”、“结果差”。 首先,即使有了联网模式,在技术方面很多 AI 助手依旧没办法实时获取最新的数据。这主要是上面提到的“第三类”垂类业务场景。无论是用了实时的知识库做匹配还是用NL2SQL取数等技术手段,数据的准确性和可靠性问题依旧十分明显,更不要说用户隐私这类数据的安全处理,这点需要非常大的成本和时间逐步解决。 再者,AI擅于回答错误答案,你在提问时的一点细微差别,它可能就完全 get 不到,给出偏离需求的回答,AI的回答也极具欺骗性,让人难以判别真伪。因此想用好 AI工具,用户首先得学会怎么提问,提示词prompt就得讲究讲究,对于AI给出的回答也需要辩证看待、甚至需要投入更多验证成本,这些对很多普通用户来说其实是有门槛的。 关于AI给出的答案还需要强调的,AI工具的检索、GEO(下一节会介绍)好比SEO、未来注定存在很大的商业利益空间,从而引发AI回答的人为干预、植入广告等投机行为,我们需要对此有所警惕。正如同当年的“魏则西事件”,就是由于搜索引擎排序被人为干扰后导致的悲剧。而且AI搜索的广告会更隐蔽,无法像传统广告那样被清晰标识。 总而言之,AI 搜索确实改变了我们检索信息的方式,让信息获取变得更高效,但它目前更像是对传统搜索的补充,它们各有利弊,所以我们也应根据不同的场景去选择工具。 四、SEO和GEO 随着AI工具的普及,这几年关于AI工具的搜索推荐也衍生出了一些新概念:AISEO(Artificial Intelligence Search Engine Optimization)、GEO(Generative Engine Optimization)、AEO(Answer Engine Optimization)。它们是一种面向AI搜索的全新内容与品牌认知优化策略。 SEO的目标是抢搜索引擎的排名,而GEO的目标是让你的内容成为AI的信息来源。通俗点解释,SEO是想办法针对Google/百度这类搜索引擎的搜索结果进行优化,让自己的品牌网站出现在结果列表中、并希望能不断提前排名;而GEO是针对大模型的生成结果进行优化,让自己的品牌或网站出现在生成结果中。 首先个人也认为GEO会渐渐比SEO更重要,因为这是目前AI时代搜索领域从“流量思维”到“答案思维”的转变: 传统SEO:流量思维,查找信息,优化的是“容器”(网页),追求的是在搜索引擎结果链接列表中的“位置”、即流量,用户还需要点“位置”再进行结果判断。 AISEO/GEO:答案思维,优化的是“知识”本身,追求的是成为AI认知体系中的“事实”,用户可以直接拿到答案,从链路来看也更短、更为高效。 在AI时代,“答案”即代表了流量。用户页不再关心信息的来源是哪个网站,只关心最终答案。因此,谁能控制答案、使品牌信息成为AI生成答案时的优先引用,谁就控制了流量,谁就能在用户心中建立起第一品牌认知,并掌握最终的商业统治力。其核心目标不再是争夺“链接排名”,而GEO就是是通过深度优化内容的语义结构、权威性信号、多模态适配性及信任网络,确保你的企业品牌信息成为这些答案的一部分,从而直接抢占“最终答案”的控制权。 GEO的诞生给企业提供了一条推广的新途径,但也带来了隐患,即任何一家公司或个人都可以发布大量没有经过权威验证的文章到网上,然后被AI引用,进而造成不良后果,这就是所谓的数据污染,原则上如果大模型接触到的文字资料都是权威正确的,那么它给出的结果自然就是正确的,但谁来保证大模型接触到的资料正确性呢?尤其是对于目前需要实时联网获取信息的大模型而言,哪些网站的资料是可靠的,哪些是不能引用的?没有相关权威规定,全凭大模型厂家自身决定,这就埋下了隐患,也是现在GEO的问题。 AI搜索的优势与劣势推动着行业标准的重新定义。传统搜索时代,谷歌与百度通过PageRank算法确立权威地位;而在AI搜索生态中,答案质量评估体系尚未形成统一标准。这种规则真空状态既是挑战也是机遇。 ChatGPT中的跳转链接,会在跳转链接中带utm_source=chatgpt.com参数,不知道是否会逐步形成业界规范。Kimi这些目前发现还没有这种处理,这种情况下网页很难追溯来源。 五、关于传统搜索引擎未来归宿的思考 以目前AI工具的“联网模式”为例,其实它底层是调用了传统搜索引擎的API,并对其结果进行分析处理(代替人为操作,关于“联网模式”的原理以后可能可以展开介绍介绍,本文先不展开),在这个过程中,用户其实是感知不到搜索引擎的存在的,所以关于传统搜索引擎的未来,个人觉得传统搜索引擎会以API的形式与AI有更多结合(包括各基于LLM的Agent、Workflow、Tool),但是会藏在水下,传统搜索引擎会逐步从给人用到给AI用,但还是会因各种因素留有一部分人使用传统搜索引擎,AI也好、传统搜索引擎也好,毕竟都是一种工具。 有人可能说像kimi开启“联网模式”后页面右边能看到检索的列表,但这只是个交互设计,像DeepSeek就隐藏了这部分。 最后,感慨下时代变化之快,商业模式也在变,在这样一种快速变化的大形势下,企业也好、网站也好、个人也好,应如何建立核心竞争力,以求立于“不败之地”。除了大家都说的顺应潮流拥抱AI外,本人还觉得也要对未来发展趋势有所思考、不断论证,力求先走一步。 相关链接 https://www3.cnnic.cn/n4/2025/0721/c88-11328.html https://www.bain.com/insights/goodbye-clicks-hello-ai-zero-click-search-redefines-marketing/# https://onelittleweb.com/data-studies/ai-chatbots-vs-search-engines/ https://juejin.cn/post/7530088591394406442 https://www.cjr.org/tow_center/we-compared-eight-ai-search-engines-theyre-all-bad-at-citing-news.php https://www.zhihu.com/question/1913288955622823047/answer/1945849408408257462 https://www.frostchina.com/content/insight/detail/689c5e10ec651704f440e89b https://scjgj.sh.gov.cn/162/20250908/9d4ea7854edf480f846318e3c8268315.html https://a16z.substack.com/p/the-death-of-search-how-shopping https://mikekhorev.com/ai-seo-trends https://searchengineland.com/ai-hype-seo-reality-leads-revenue-462235

2025/9/14
articleCard.readMore

【工具】AI Common Notify:统一 AI 编程工具通知服务

AI Common Notify 完全指南:统一 AI 编程工具通知服务 在 AI 辅助编程日益普及的今天,Claude Code、Cursor、Windsurf、Trae 等 AI 工具极大地提升了我们的开发效率。但这些工具都有一个共同的问题:它们在执行完任务后不会主动通知用户,导致开发者需要手动检查任务状态。如果在同时运行多个任务时,容易错过重要信息或无法有效安排工作优先级。 为了解决这一问题,本人写了 AI Common Notify —— 一个为所有主流 AI 编程工具提供统一通知服务的开源工具。它能在 AI 工具完成任务后主动发送系统通知,让您在多任务并行时也能井然有序地处理工作。 AI Common Notify 本质上是一个通知应用工具,因此它也可以不只应用于 ai 编辑器。 项目地址:https://github.com/MichealWayne/ai-common-notify 为什么选择 AI Common Notify? 现状问题 目前市面上虽然已有一些小的通知工具,但它们通常只针对单一 AI 工具,例如仅支持 Claude Code。这种碎片化的解决方案带来了以下问题: 工具割裂:每个 AI 工具需要单独的通知服务、如配 hook、配 mcp,用户需要安装和配置多个工具 体验不一致:不同通知服务的样式、行为和配置方式差异很大 维护成本高:当需要调整通知设置时,需要逐一修改各个工具的配置 扩展性差:缺乏统一的扩展机制,难以集成自定义通知渠道 AI Common Notify 的核心优势 AI Common Notify 针对上述痛点提供了全面解决方案: 统一接口:一个工具支持所有主流 AI 编程工具(Claude Code、Cursor、Windsurf、Trae 等) 跨平台兼容:支持 Windows、macOS 和 Linux 高度可配置:支持自定义标题、消息模板、紧急程度、超时时间、声音和图标 扩展性强:通过脚本回调机制,可轻松集成微信通知、钉钉机器人等自定义通知渠道 易于部署:支持 npm 全局安装和独立可执行文件,一键配置 智能初始化:自动检测项目中使用的 AI 工具并生成相应配置 快速入门 安装 在本地环境安装Nodejs(推荐 v18 及以上)后,可通过 npm 全局快速安装: 1 npm install -g ai-common-notify 验证安装 安装完成后,通过以下命令验证是否安装成功: 1 2 # 查看版本信息 ai-common-notify --version 1 2 # 发送测试通知 ai-common-notify test 如果看到版本信息或系统通知弹出,说明安装成功。 核心功能详解 1. 多样化的通知触发机制 AI Common Notify 支持多种通知触发方式,适配不同 AI 工具的特点: Hook 模式(Claude Code) 可通过ai-common-notify quickInit命令在项目下快速初始化配置 通过 Claude Code 的 Hook 系统集成,在任务完成时发送通知: 在 Claude Code 设置文件 (~/.claude/settings.json 或项目中的 .claude/settings.json)设置: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "hooks": { "Stop": [ { "matcher": ".*", "hooks": [ { "type": "command", "command": "ai-common-notify hook" } ] } ] } } MCP 模式(Cursor、Windsurf、Trae、CodeBuddy、Gemini-cli 等) 也可通过ai-common-notify quickInit命令在项目下快速初始化配置 通过在 IDE 中设置 MCP 为 Cursor 等工具提供通知服务: 1 2 3 4 5 6 7 8 { "mcpServers": { "NotificationServer": { "command": "ai-common-notify", "args": ["mcp"] } } } 使用提示:当使用 Cursor 或 Windsurf 等 MCP 工具时,建议在您的提示(prompt)最后明确要求发送通知,例如:”最后,任务完成时发送通知给我。“、”Finally, send me a notification when the task is finished.“ 这有助于确保 AI 工具调用通知工具。您也可以在 Cursor 的设置中将此提示添加为规则,这样就不需要每次都手动输入。 API 模式(自定义集成) api 模式主要用于在线的平台工具进行调用,以统一通知处理。AI Common Notify 提供 RESTful API 供自定义工具调用: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 # 启动API服务器 ai-common-notify api # 发送通知请求 curl -X POST http://localhost:6001/api/v1/notify \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-secret-token" \ -d '{ "title": "任务完成", "message": "代码重构已完成", "urgency": "normal", "timeout": 0, "sound": true }' 2. 灵活的通知定制 AI Common Notify 支持丰富的通知定制选项: 基础参数 title: 通知标题 message: 通知内容 urgency: 紧急程度(low/normal/critical) timeout: 超时时间(秒,0 表示永久显示)(部分系统不适用) sound: 是否播放声音 icon: 自定义图标路径(部分系统不适用) 高级配置 通过 JSON 配置文件实现更精细的控制: 1 2 3 4 5 6 7 8 9 { "notifications": { "default_timeout": 0, "default_sound": true, "default_urgency": "normal", "title_template": "{tool_name} - {project_name}", "message_template": "{message}" } } 3. 脚本回调扩展 脚本回调在 AI Common Notify 的配置文件中设置,通过脚本回调扩展可以实现在通知发送时执行自定义脚本,让我们可以轻松集成微信通知、钉钉机器人等自定义通知渠道: shell: 1 2 3 4 5 6 7 8 9 10 11 12 { "scripts": { "timeout": 30000, "notify": [ { "type": "shell", "path": "/path/to/your/script.sh", "enabled": true } ] } } nodejs: 1 2 3 4 5 6 7 8 9 10 11 12 { "scripts": { "timeout": 30000, "notify": [ { "type": "node", "path": "/path/to/your/script.js", "enabled": true } ] } } 脚本中可以接收丰富的环境变量(如 nodejs 可以用process.env获取): NOTIFY_TITLE: 通知标题 NOTIFY_MESSAGE: 通知消息 NOTIFY_URGENCY: 紧急程度 NOTIFY_TIMEOUT: 超时时间 NOTIFY_SOUND: 是否播放声音 NOTIFY_PROJECT_NAME: 项目名称 NOTIFY_TOOL_NAME: 工具名称 NOTIFY_TIMESTAMP: 时间戳 通过脚本回调扩展我们可以额外完成很多自定义功能,如: 集成微信通知示例 Node.js 脚本示例(发送到企业微信) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // wechat-notify.js const https = require('https'); // 企业微信机器人Webhook地址 const webhookUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY'; // 构造消息内容 const message = { msgtype: 'text', text: { content: `[${process.env.NOTIFY_TIMESTAMP}] ${process.env.NOTIFY_TITLE}\n${process.env.NOTIFY_MESSAGE}\n项目: ${process.env.NOTIFY_PROJECT_NAME}\n工具: ${process.env.NOTIFY_TOOL_NAME}`, }, }; // 发送请求 const data = JSON.stringify(message); const options = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length, }, }; const req = https.request(webhookUrl, options, res => { console.log(`微信通知发送状态: ${res.statusCode}`); }); req.on('error', error => { console.error('微信通知发送失败:', error); }); req.write(data); req.end(); 个人开发者也可以考虑接入 PushPlus、WxPusher、Server 酱这类集成好的平台来实现微信等推送。 4. 快速初始化功能 AI Common Notify 提供了一键初始化功能,自动为项目中检测到的 AI 工具生成或更新配置文件: 1 2 3 4 5 6 7 8 9 10 # 导航到项目目录 cd /path/to/your/project # 初始化所有检测到的工具 ai-common-notify quickInit # 初始化特定工具 ai-common-notify quickInit --tool cursor ai-common-notify quickInit --tool claudecode ai-common-notify quickInit --tool windsurf 该功能支持的工具包括: Cursor: 通过 MCP 协议集成 Claude Code: 通过 Hook 系统集成 Windsurf: 通过 MCP 协议和规则文件集成 Gemini-cli: 通过 MCP 协议集成 5. 错误日志管理 AI Common Notify 具备完善的错误处理和日志记录功能,以便问题反馈和排查: 1 2 3 4 5 # 查看错误日志 ai-common-notify errlog # 查看所有日志 ai-common-notify alllog 详细配置说明 配置层级 AI Common Notify 支持多层级配置,优先级从低到高依次为: 全局配置: ~/.config/ai-common-notify/config.json (Linux/macOS) 或 %APPDATA%\\ai-common-notify\\config.json (Windows) 项目配置: <project-root>/.ai-notify.json 配置文件示例 全局配置示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 { "server": { "port": 6001, "host": "localhost", "token": "generated-secret-token" }, "notifications": { "default_timeout": 0, "default_sound": true, "default_urgency": "normal" }, "scripts": { "timeout": 30000, "notify": [ { "type": "shell", "path": "/home/user/scripts/notify-log.sh", "enabled": true } ] }, "logging": { "retentionHours": 168 }, "platforms": { "linux": { "sound_enabled": false } } } 项目配置示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "notifications": { "default_urgency": "critical", "title_template": "[PROJECT] {tool_name} - {project_name}" }, "scripts": { "notify": [ { "type": "node", "path": "/path/to/project/scripts/notify.js", "enabled": true } ] } } 实际使用场景 实际有些简单的场景: 1. 多任务并行处理 当同时运行多个 AI 任务时,AI Common Notify 能帮助您: 1 2 3 4 5 6 # 在不同项目中启动AI任务 # 任务1: Claude Code重构代码 # 任务2: Cursor生成文档 # 任务3: Windsurf优化性能 # 每个任务完成后都会收到通知,您可以根据紧急程度安排处理顺序 2. 长时间运行任务监控 对于需要长时间运行的 AI 任务,您可以设置完成后通知: 1 2 # 在脚本中集成 ai-common-notify send --title "模型训练完成" --message "模型训练已完成,准确率95.2%" 3. 错误警报系统 在 CI/CD 流程中集成关键错误通知: 1 2 3 4 # 检测到错误时发送关键通知 if [ $ERROR_CODE -ne 0 ]; then ai-common-notify send --title "构建失败" --message "构建过程出现错误,请检查日志" --urgency critical fi 4. 自动化工作流 在自动化脚本中使用 AI Common Notify: 1 2 3 4 #!/bin/bash echo "开始部署..." # ... 部署过程 ... ai-common-notify send --title "部署完成" --message "应用已成功部署到生产环境" 总结 AI Common Notify 通过提供统一的通知接口,有效解决了 AI 编程工具生态中通知机制缺失的问题。它不仅支持多种主流 AI 工具,还提供了灵活的配置选项、强大的脚本扩展能力和 REST API,满足不同用户的使用需求。

2025/8/16
articleCard.readMore

21st.dev:让AI生成的页面告别"塑料感"的专业解决方案

21st.dev:让 AI 生成的页面告别”塑料感”的专业解决方案 现在已经有很多可以生成页面的 ai 工具,但你是否遇到过这样的困扰:AI 生成的页面虽然功能完整,但总有一种说不出的”塑料感”?样式单调、缺乏设计感,调整起来又费时费力… ai 生成的页面往往长这样: 或者这样: 稍好点的话可能长这样: AI 味非常得重…这对于缺乏设计经验或前端技术背景的用户来说,调整这些样式往往需要大量时间和精力。 当前主流 ai 工具生成的页面普遍存在以下问题: 视觉风格单一,缺乏品牌个性 布局结构雷同,用户体验不佳 样式调整困难,需要大量手动优化 缺乏现代设计趋势,显得过时 解决方案:21st.dev 的 AI 友好组件库 现在有一种较为好用的解决方案:使用21st.dev 。 21st.dev 是一个专为现代前端开发者和设计工程师打造的创新型 UI 组件与页面模板平台。它不仅提供了丰富的高质量组件和页面模板,更以”AI 友好”为核心理念,让开发者可以通过自然语言在 IDE 内快速生成、定制并即时使用高质量 React/Tailwind UI 组件,提升了组件的可组合性、可复用性和智能化集成体验。 具体操作 首先在 21st.dev 中挑选心仪的页面模版,一般可以在Heroestab 中查看,如: 选中风格后可点击查看: 然后可点击“Copy prompt”复制 prompt。 对于非开发人员 如果你不太懂 js 代码的话,可以忽略 prompt 中的内容。 然后我们在 AI 生成页面的平台中对原有页面进行修改。 如 Cursor: 1 2 3 4 5 你是一位专业前端开发,接下来我会给你一段提示词,提示词中包含一种页面风格的代码,你仔细分析一下提示词及代码,参考视觉风格、布局和动画效果,将样式尽可能应用到我的页面中,确保页面文案、核心功能和业务逻辑不受影响。提示词: \`\`\` 刚才拷贝的提示词 \`\`\` 如: 等待更新: 效果: 总结一下操作流程: 访问 21st.dev 在 Heroes 标签页选择心仪模板 复制 prompt 到 AI 工具中 按提示操作即可获得专业级页面 对于前端开发者 如果你本身就是一位前端开发且基本掌握 React 的话,可以直接用拷贝的 prompt 在你的 React 项目中进行生成或更新: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 You are given a task to integrate an existing React component in the codebase The codebase should support: - shadcn project structure - Tailwind CSS - Typescript If it doesn't, provide instructions on how to setup project via shadcn CLI, install Tailwind or Typescript. Determine the default path for components and styles. If default path for components is not /components/ui, provide instructions on why it's important to create this folder Copy-paste this component to /components/ui folder: \`\`\`tsx hero-parallax.tsx "use client"; import React from "react"; import { motion, useScroll, useTransform, useSpring, MotionValue, } from "framer-motion"; import Image from "next/image"; import Link from "next/link"; export const HeroParallax = ({ products, }: { products: { title: string; link: string; thumbnail: string; }[]; }) => { const firstRow = products.slice(0, 5); const secondRow = products.slice(5, 10); const thirdRow = products.slice(10, 15); const ref = React.useRef(null); const { scrollYProgress } = useScroll({ target: ref, offset: ["start start", "end start"], }); const springConfig = { stiffness: 300, damping: 30, bounce: 100 }; const translateX = useSpring( useTransform(scrollYProgress, [0, 1], [0, 1000]), springConfig ); const translateXReverse = useSpring( useTransform(scrollYProgress, [0, 1], [0, -1000]), springConfig ); const rotateX = useSpring( useTransform(scrollYProgress, [0, 0.2], [15, 0]), springConfig ); const opacity = useSpring( useTransform(scrollYProgress, [0, 0.2], [0.2, 1]), springConfig ); const rotateZ = useSpring( useTransform(scrollYProgress, [0, 0.2], [20, 0]), springConfig ); const translateY = useSpring( useTransform(scrollYProgress, [0, 0.2], [-700, 500]), springConfig ); return ( <div ref={ref} className="h-[300vh] py-40 overflow-hidden antialiased relative flex flex-col self-auto [perspective:1000px] [transform-style:preserve-3d]" > <Header /> <motion.div style={{ rotateX, rotateZ, translateY, opacity, }} className="" > <motion.div className="flex flex-row-reverse space-x-reverse space-x-20 mb-20"> {firstRow.map((product) => ( <ProductCard product={product} translate={translateX} key={product.title} /> ))} </motion.div> <motion.div className="flex flex-row mb-20 space-x-20 "> {secondRow.map((product) => ( <ProductCard product={product} translate={translateXReverse} key={product.title} /> ))} </motion.div> <motion.div className="flex flex-row-reverse space-x-reverse space-x-20"> {thirdRow.map((product) => ( <ProductCard product={product} translate={translateX} key={product.title} /> ))} </motion.div> </motion.div> </div> ); }; export const Header = () => { return ( <div className="max-w-7xl relative mx-auto py-20 md:py-40 px-4 w-full left-0 top-0"> <h1 className="text-2xl md:text-7xl font-bold dark:text-white"> The Ultimate <br /> development studio </h1> <p className="max-w-2xl text-base md:text-xl mt-8 dark:text-neutral-200"> We build beautiful products with the latest technologies and frameworks. We are a team of passionate developers and designers that love to build amazing products. </p> </div> ); }; export const ProductCard = ({ product, translate, }: { product: { title: string; link: string; thumbnail: string; }; translate: MotionValue<number>; }) => { return ( <motion.div style={{ x: translate, }} whileHover={{ y: -20, }} key={product.title} className="group/product h-96 w-[30rem] relative flex-shrink-0" > <Link href={product.link} className="block group-hover/product:shadow-2xl " > <Image src={product.thumbnail} height="600" width="600" className="object-cover object-left-top absolute h-full w-full inset-0" alt={product.title} /> </Link> <div className="absolute inset-0 h-full w-full opacity-0 group-hover/product:opacity-80 bg-black pointer-events-none"></div> <h2 className="absolute bottom-4 left-4 opacity-0 group-hover/product:opacity-100 text-white"> {product.title} </h2> </motion.div> ); }; demo.tsx "use client"; import React from "react"; import { HeroParallax } from "@/components/blocks/hero-parallax"; export function HeroParallaxDemo() { return ( <div className="min-h-screen w-full"> <div className="absolute top-0 left-0 w-full"> <HeroParallax products={products} /> </div> </div> ); } export const products = [ { title: "Moonbeam", link: "https://gomoonbeam.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/moonbeam.png", }, { title: "Cursor", link: "https://cursor.so", thumbnail: "https://aceternity.com/images/products/thumbnails/new/cursor.png", }, { title: "Rogue", link: "https://userogue.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/rogue.png", }, { title: "Editorially", link: "https://editorially.org", thumbnail: "https://aceternity.com/images/products/thumbnails/new/editorially.png", }, { title: "Editrix AI", link: "https://editrix.ai", thumbnail: "https://aceternity.com/images/products/thumbnails/new/editrix.png", }, { title: "Pixel Perfect", link: "https://app.pixelperfect.quest", thumbnail: "https://aceternity.com/images/products/thumbnails/new/pixelperfect.png", }, { title: "Algochurn", link: "https://algochurn.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/algochurn.png", }, { title: "Aceternity UI", link: "https://ui.aceternity.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/aceternityui.png", }, { title: "Tailwind Master Kit", link: "https://tailwindmasterkit.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/tailwindmasterkit.png", }, { title: "SmartBridge", link: "https://smartbridgetech.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/smartbridge.png", }, { title: "Renderwork Studio", link: "https://renderwork.studio", thumbnail: "https://aceternity.com/images/products/thumbnails/new/renderwork.png", }, { title: "Creme Digital", link: "https://cremedigital.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/cremedigital.png", }, { title: "Golden Bells Academy", link: "https://goldenbellsacademy.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/goldenbellsacademy.png", }, { title: "Invoker Labs", link: "https://invoker.lol", thumbnail: "https://aceternity.com/images/products/thumbnails/new/invoker.png", }, { title: "E Free Invoice", link: "https://efreeinvoice.com", thumbnail: "https://aceternity.com/images/products/thumbnails/new/efreeinvoice.png", }, ]; \`\`\` Install NPM dependencies: \`\`\`bash framer-motion \`\`\` Implementation Guidelines 1. Analyze the component structure and identify all required dependencies 2. Review the component's argumens and state 3. Identify any required context providers or hooks and install them 4. Questions to Ask - What data/props will be passed to this component? - Are there any specific state management requirements? - Are there any required assets (images, icons, etc.)? - What is the expected responsive behavior? - What is the best place to use this component in the app? Steps to integrate 0. Copy paste all the code above in the correct directories 1. Install external dependencies 2. Fill image assets with Unsplash stock images you know exist 3. Use lucide-react icons for svgs or logos if component requires them 21st.dev 中拷贝出页面/组件的 prompt 都是如上所示的结构,主要内容是: 介绍任务和技术栈信息 介绍组件代码 告诉 AI 怎么组织文件以及相关依赖项 另外如果不想使用 AI 的方式,我们可以直接点击组件的“Open Component”按钮查看并复制源码 另外由于 21st.dev 也提供了 MCP 的方式,我们也可以按以下操作: 登录 21st.dev,访问 Magic 控制台生成 API Key 通过 CLI 快速安装npx @21st-dev/cli@latest install <client> --api-key <API_KEY> 也可以在支持 MCP 的 IDE(cursor、windsurf、cline、claude)中手动配置: 1 2 3 4 5 6 7 8 9 "mcpServers": { "@21st-dev/magic": { "command": "npx", "args": ["-y", "@21st-dev/magic@latest"], "env": { "API_KEY": "<your-api-key>" } } } 配置完成后,在 IDE 的 AI 聊天(Composer)里即可使用 /ui 命令: 如创建组件/ui create a responsive navbar with logo and dark mode toggle 如果你不懂 React、也可以绕一道让 AI 将 React 组件转为 Vue、Angular 技术栈。 相关介绍 关于 21st.dev 的创办历程感兴趣可以看油管的这个视频:https://youtu.be/H2Mze4K5j6Q 背景起源 创始之初:由 Serafim(网名 @serafimcloud)于 2024–2025 年间创立,灵感源自分享、发现高质量 UI 组件的社区愿景。Serafim 曾与 Daniel Dhawan 合作开发 Rork.com(一个 AI 建站工具),后将其核心组件社区产品独立出来,继续打造 21st.dev 平台 愿景:目标是成为“Figma Community for code”,为设计工程师提供集中化、开源、可 remix 的 React + Tailwind UI 组件市场。 与传统组件库、模板页、Sandbox 的区别 AI 原生设计:21st.dev 的组件和模板结构、元数据均为 AI 理解和调用进行了深度优化,便于 AI 助手自动生成、组合和定制页面。这一点区别于传统组件库仅面向人工查找和手动集成。 IDE 与 AI 无缝集成:支持主流 IDE 插件和 AI 助手,开发者可在编辑器内直接搜索、插入、定制组件,远超传统模板页和在线 Sandbox 的割裂体验。 Remix 与二次创作:平台鼓励用户在现有组件基础上进行 Remix(再创作),并可一键分享,形成社区驱动的创作循环,而传统 Sandbox 多为孤立的代码实验环境,难以沉淀和复用成果。 社区开放与开源:21st.dev 鼓励开发者和设计师上传、分享组件,平台本身开源,促进知识共享和持续进化。 适用场景 高效页面搭建:前端开发者可快速组合高质量组件,极大提升开发效率,减少重复造轮子。 AI 驱动的界面生成:AI 开发者可借助平台的 AI 友好特性,实现自动化页面生成、智能布局和批量定制。 设计与开发协作:设计工程师可将设计稿转化为可复用组件,推动设计与开发一体化。 学习与创新:初学者可通过组件库学习最佳实践,进阶者可参与 Remix 和社区共创。 产品与特色 1. 组件注册表(Registry) 类似 npm 市场但专注 UI 组件,鼓励发布“minimal、modern、reusable”的 React + Tailwind + Radix UI 组件。 内置分类丰富,比如导航栏、卡片、按钮、表单、对话框等组件供开发者浏览、复制、安装。 2. 魔法生成器:Magic MCP 上文也有大致的使用介绍。 Magic MCP是一款 AI 驱动的 IDE Agent,目前支持 Cursor、Windsurf/ Cline、VS Code 等。 使用者只需输入如 /ui pricing table 的描述,Magic 会生成多个变体,自动生成组件文件及依赖配置,极大提升开发速度。 另外在官网上也支持类似 bolt、v0 这样的 chat 生成模式:Magic Chat 3. 发布流程和社区治理 组件发布仅需一键,上传后先进入 on_review 审查阶段,由 Serafim 亲自审核,合格后可提升为 posted 或 featured。 提倡 TypeScript 支持、深度可定制性(支持暗黑模式、CSS 变量、ARIA 可访问性)和结构化 Demo 规范。 4. 架构技术栈 前端采用 Next.js 14 后端使用 Supabase(存储元数据)、Clerk(验证)、Cloudflare R2(静态资源)、Amplitude(分析)。 开放源码托管在 GitHub,社区贡献活跃(~4.6k Stars,200+ forks),https://github.com/serafimcloud/21st。 5.商业模式 订阅制(SaaS 模式):21st.dev 采用月/年订阅机制,目前定价$16 ~ 32/月,官网可见具体价格,为专业和高阶用户提供完整的 AI 辅助功能,包括 Magic MCP、Magic Chat、UI 灵感支持等。这是一种典型的持续性付费服务,适合长期使用并依赖高效 UI 开发的开发者团队 。 免费策略:平台对所有用户开放基础浏览与复制组件功能,引入用户;高级功能(如 AI 生成、多 Tokens 支持、优先客服等)则通过付费订阅提供。这种“基础免费 → 高级付费”的模式符合常见 SaaS+Freemium 叠加架构 。 总结 21st.dev 通过其 AI 友好的设计理念,成功解决了 AI 生成页面”塑料感”的问题。无论你是专业开发者还是设计新手,都能通过这个平台快速创建具有专业水准的页面设计。 随着 AI 在前端开发中的深入应用,21st.dev 将继续优化其 AI 集成体验,为开发者提供更强大、更智能的工具支持。 未来展望 市场反响与发展 Product Hunt:评分 4.9/5,1.9k Followers,多位用户评价其平台能力“简化前端开发流程”“组件中心化管理大幅提升效率” 媒体与融资:被 a16z 报道为 AI 开发未来趋势之一,已获得种子轮融资支持;具体金额未披露。 社区活力:官方 Discord、Twitter/X 持续更新,LinkedIn 上亦频繁分享优质组件,目前用户粘性高,具备较强的商业化基础。 21st.dev 致力于成为连接设计、开发与 AI 智能的桥梁。随着 AI 在前端开发中的深入应用,平台将持续优化 AI 集成体验,丰富组件生态,推动前端开发的智能化与协作化。 相关链接 21st.dev https://youtu.be/H2Mze4K5j6Q https://github.com/serafimcloud/21st https://glama.ai/mcp/servers/%4021st-dev/magic-mcp?utm_source=chatgpt.com

2025/6/29
articleCard.readMore

【笔记】Figma和AIGC(持续)

Figma是一款基于云的协作式界面设计工具,支持多人实时编辑,适用于UI/UX设计、原型制作及设计交付。提供矢量绘图、组件库、交互动画等功能,支持跨平台使用(网页/桌面端),实现团队高效协作与版本管理。 Figma类似早些年的Sketch、PhotoShop,但具备在线多人协同能力以及社区插件体系。 这两年随着ai应用化的发展,ai生成figma设计稿以及figma设计稿生成前端代码这两个能力正在迅速发展。 生成Figma 场景1:复刻其他页面 当前能力评估:UI界面90%复刻,已到可应用的状态 主要工具:html-to-figma 当前主流实现路径1: Chrome浏览器插件,爬取网站UI信息 -> 生成信息文件(json) -> Figma插件中导入信息文件生成设计稿 需要安装一个chrome插件,插件有很多:代表如buildio的“HTML to Figma”,腾讯CoDesign-HtmltoDesign: 插件已开源:https://github.com/BuilderIO/figma-html (buildio官方近期在迁移这个插件,集成到了buildio插件中https://www.builder.io/c/docs/chrome-extension#paste-from-chrome-into-figma) 另外在Figma上需要安装一个接收设计信息的Figma插件:https://www.figma.com/community/plugin/747985167520967365/builder-io-ai-powered-figma-to-code-react-vue-tailwind-more 使用步骤: 1.打开需要复刻的页面,如google搜索结果页面,点击chrome插件“CAPTURE PAGE”按钮,即开始导出页面UI信息 得到类似page.figma.json的json信息文件 2.Figma中打开Figma-to-Code插件,上传json 即可得到对应设计稿 *现在这类插件也集成了直接输入url地址生成Figma的能力 类似的产品还有:https://demoway.com/html-to-figma 除了从真实web页面中复刻外,我们也可以借助Cursor/Windsurf这些AI IDE,让其分析代码并生成Figma、不过注意模型需要支持多模态、一般可用Claude3.x/4 可参考本文:《五分钟!Cursor+Claude3.7直接生成一整套原型图/UI稿》https://mp.weixin.qq.com/s/6c1L_sAf3pxJqtJXfGhr-Q 场景2:ai生成Figma 当前能力评估:简单/通用场景生成效果可应用,复杂页面还需要大量调整 通过自然语言生成设计稿,现在Figma官方也在做这方面的能力,如Figma AI:https://www.figma.com/ai/?utm_source=ai-bot.cn 还有各类Figma插件 https://mmmnote.com/article/7e8/12/article-4c48bb165ef888ff.shtml 另外Google也推出了设计Agent:Stitch,只需要输入一句话/一段话,Stitch就可以输出生产级别的UI设计稿,并且支持直接复制粘贴到Figma中进行二次编辑,或者导出相应代码。 操作可参考:《Google Stitch:2分钟从想法→可编辑的Figma设计稿(附5个使用技巧)》https://mp.weixin.qq.com/s/YNEY3rprhueESYh6AD3cTA Figma to Code(前端) 这块东西就很多了 方式1:*Figma官方:Figma sites 当前能力评估:静态页面/官网这些场景可应用,其他复杂场景还不行。能力正在发展 https://www.figma.com/sites/ (Figma可以通过第一阶段aigc或者复刻生成) 点击preview可查看页面效果 方式2:Figma MCP 当前能力评估:大多静态场景可应用,复杂场景需要代码调整。能力正在发展 非官方但也在迅速发展,使用方式可参考Trae:https://mp.weixin.qq.com/s/AlzeT_1OeFzS6mRC3PDNOA、Cursor:https://zhuanlan.zhihu.com/p/1897249661569447152 https://www.framelink.ai/,其实现也已开源:https://github.com/GLips/Figma-Context-MCP

2025/5/25
articleCard.readMore

【笔记】State-Of-Ai 报告信息

【笔记】State-Of-Ai 报告信息 一、State-Of-Ai Web Dev 2025 报告摘要 2025.stateofai.dev是面向 Web 开发者的一次 ai 使用和问题情况统计,完整报告:https://2025.stateofai.dev/en-US/models/。其访问组织之前也有state-of-js、state-of-css等典型统计系列。 在这篇state-of-ai统计中,受访者人数规模在5000 - 10000左右,国家主要集中在美欧、中国受访者只有 25 人,因此实际情况和国内会有偏差。 个人概括下这份报告的主要信息:Web 开发者对 AI 应用持有积极的态度,乐于使用并看好其发展。开发者使用 ai 的主要场景在代码生成,目前使用主要问题在幻觉和不确定,另外生成的代码质量和上下文限制也影响了其效果,以至于较大占比的生成代码需要重构。 1.1 Model Providers 模型提供商情况 首先,毫不奇怪,OpenAI 的 ChatGPT 仍然受益于其先发优势和巨大的市场份额,使其成为最常用(91.2%)和最受欢迎(53.1%)的模型提供商。 虽然它在使用方面确实领先很大,但在积极情绪(个人觉得这个指标可以理解为好评情况、受欢迎度)方面,第二的 Claude 并没有落后太多,为45.9%。 因为国内受访者很少,所以像国内常用的千问、豆包等模型统计占比很少。 Model Providers Pain Points 模型提供者的痛点 幻觉和不准确是迄今为止受访者报告的 AI 模型的最大痛点,这是有道理的,因为如果这些工具的输出不可靠,它们就会失去所有效用。 缺乏处理更大上下文和将数据保存在内存中的能力也是一个大问题,尤其是在处理大型真实代码库时。 1.2 IDE 和编辑器情况 Cursor 在认知度上处于领先地位,82.2%的受访者使用过或听说过它,而第二的 Zed 只有54.1%。 当看到关于 Cursor 的随意评论时,似乎主要问题实际上是它的价格,这表明市场可能有更便宜的替代品的空间。 IDE 使用痛点 上下文和内存限制是目前阻止 Web 开发人员使用专用 IDE 进行编码的主要原因,其次是太多的侵入性建议以及与 AI IDE 相关的高成本。 1.3 Coding Assistants 编码助理使用情况 虽然看到 GitHub Copilot 在使用量和积极情绪排名中名列前茅并不奇怪,但值得注意的是,Supermaven 的积极情绪排名第二,尽管就使用量而言仅排名第四。这种差异通常是一颗新星的标志,它可能会在未来一年掀起波澜。 Coding Assistants Pain Points 编码助手痛点 幻觉和不准确再次被证明是更广泛采用的一大障碍。 就像 IDE 一样,具有有限上下文窗口的编码助手也是一个主要问题。 1.4 Code Generation 代码生成情况 凭借 Vercel 的实力,v0 迅速确立了自己在这个新兴行业领域的领导者地位。但是 StackBlitz 的 Bolt 也不甘落后,当然值得关注。 Code Generation Pain Points 代码生成痛点 代码生成工具似乎生成了质量差的代码,这些代码通常不能按预期工作,或者根本不能工作。 1.5 Other Tools 其他工具 使用 ai 工具时的编程语言 主要还是 js/ts 和 python。 图像生成模型 主要是 DALL·E 和 MJ。 AI 封装库/SDK 希望浏览器支持 API 情况 人工智能模型很可能在未来融入我们的网络浏览器——如果发生这种情况,像即时翻译或总结内容这样的事情可能只是一个 API 调用。 1.6 Usage 用法 正如开发人员调查所预期的那样,代码生成被列为最常见的人工智能用法。另一方面,尽管图像生成是生成人工智能的原始用例,但只有38%的受访者表示使用它。 代码生成占比情况 大多数人还没有完全进行氛围编码(vibe coding),大多数受访者(69%)通过 AI 生成的代码不到25%——只有一小部分(8%)生成了超过75%的代码。 AI 代码重构情况 即使使用 AI 生成代码,绝大多数(76%)的开发人员表示他们必须重构至少一半的输出代码才能准备好使用。 重构的首要原因是表面问题,如易读性差、变量重命名和过度重复。许多受访者还使用自由形式的“其他答案”字段来声明生成的代码通常无法按预期工作。 使用 AI 生成代码频率情况 46%的受访者每天多次或更多次使用人工智能生成代码。 与代码生成相比,人工智能用于其他任务(研究、总结、翻译等)的频率相对较低——考虑到编码仍然是我们花费最多时间的事情,这是有道理的。 使用 AI 生成代码的场景情况 最常见的生成代码类型被证明是辅助函数,其次是前端组件,它们都相当独立,使它们成为代码生成的良好候选者。 许多人还使用人工智能为现有代码添加留档或注释,这是一个意想不到的用例。 使用 AI 生成代码的消费支出情况 大多数受访者目前没有在人工智能工具和服务上花费任何自己的钱。 受访者所在公司在 AI 工具上的支出情况遵循马蹄形模式,公司不会在人工智能上花费任何费用——除非他们花费超过 5000 美元!这种定价模式是否对人工智能公司来说是可持续的还有待观察。 AI 各工具应用的使用痛点 在 AI 痛点方面,整体代码质量差排名第一。 觉得这些 ai 或工具缺少的功能 今天的模型缺少的主要东西是将整个代码库保存在内存中的能力,如果 AI 工具旨在帮助我们维护应用程序,而不仅仅是对它们进行原型设计,那么这一点将被证明是关键。 另外,尽管调查强调了各种痛点,但受访者总体上对 2025 年人工智能用于 Web 开发的状态非常积极。 1.7 Resources 信息资源 播客: 视频创作者: 二、Vercel State-Of-Ai 2024 报告信息 是 Vercel 对于 V0 使用者的调研报告,完整报告:https://vercel.com/state-of-ai。 个人概括下这份报告的主要信息:V0 的使用者看好 AI 的潜力和未来发展,并未接下来的技术进步做准备、如提前准备模型切换能力。虽然目前 OpenAI 是领先的提供商,但开发人员正在积极测试替代方案。AI 应用的重点正在转向面向客户的功能,专注于现实世界的价值,当前模型准确性和成本等挑战仍然是关键问题。开发者成功需要仔细评估、战略规划和灵活实施以适应变化。 2.1 模型使用情况 OpenAI 正在引领模型采用,但竞争正在迎头赶上。虽然 OpenAI 仍然是88%采用率的主要选择,但开发人员与多个提供商保持关系——平均两个。随着提供商竞相完成,开发人员的忠诚度在六个月内受到65%更换提供商的考验。 2.2 应用和价值创造情况 虽然这个市场还很年轻,有很多未开发的机会,但急功近利的时代已经结束了。用户现在对人工智能的期望更高。询问更深入的问题,关于人工智能如何增强用户体验的各个方面,并使其成为产品开发的核心,而不仅仅是一个附加组件。 聊天机器人(44%)和产品功能(79%)之间的差距揭示了向更深层次的人工智能集成的转变 矢量数据库采用(70%)标志着 AI 基础设施的成熟 网站个性化(24%)仍未得到充分开发,这暗示着未来的机会 2.3 开发实践和效率情况 今天的团队通过智能技术选择而不是巨额预算来构建高需求的人工智能系统。AI 团队以精益预算构建强大的系统,每月花费不到 1,000 美元。他们通过使用 RAG、智能数据采购和云平台跳过昂贵的培训,无需繁重的基础设施即可交付快速、可靠的模型。 团队通过智能架构和增强生成而不是定制模型训练来优化成本 每周模型更新正在成为标准,这表明 Vercel 等提供商支持的快速迭代实践 大多数团队将手动测试与基于经验的发布配对,但是度量驱动的评估正在出现 手动测试仍然很常见,但指标驱动的评估表明质保越来越复杂。 团队将公共数据集、网络抓取和客户数据与 RAG 定制相结合,以提供精确的输出,而无需定制模型培训的开销。 2.4 优先级和组织结构 人工智能发展进入务实阶段。构建成功的 AI 功能并不一定需要专门的部门。专注于高影响力的用例,同时保持团队结构精简。机会在于发现人工智能在哪里增加了真正的价值,并有效地利用可用资源。 许多人将有意义的技术预算(超过 15%)用于人工智能,但不打算发展专门的人工智能团队。他们正在寻找方法,通过赋予现有团队更好的工具和明确的目标来构建复杂的人工智能功能。 团队选择精益集成而不是专业部门 现有产品团队推动人工智能创新 正在平衡构建新功能和扩展现有功能之间的优先级 2.5 信仰和观点 人工智能市场在炒作和实际影响之间找到了最佳位置。团队认为当前的人工智能工具被夸大了,但他们预计人工智能将在 12 个月内对他们的行业产生重大影响。他们对未来感到兴奋,但立足于现在。 团队相信人工智能的未来,同时对当前工具保持现实 开源和微调被证明是有用的,但还没有改变游戏规则 每个人都在为明年的重大进步做准备,用现在有效的东西建造,但为即将到来的东西设计 巨大的变化就在前方,即使我们还没有到那一步。要意识到当前的限制和挑战,同时对人工智能的变革潜力保持乐观。 相关链接 https://2025.stateofai.dev/ https://vercel.com/state-of-ai

2025/5/5
articleCard.readMore

【笔记】web 黑夜模式通用适配方案

【笔记】web 黑夜模式通用适配方案 一、判断黑夜模式的方式 1.1 CSS 媒体查询判断黑夜模式的属性——prefers-color-scheme prefers-color-scheme CSS 媒体特性用于检测用户是否有将系统的主题色设置为亮色或者暗色。 ——MDN 值: no-preference:表示系统未得知用户在这方面的选项。在布尔值上下文中,其执行结果为 false。 light:表示用户已告知系统他们选择使用浅色主题的界面。 dark:表示用户已告知系统他们选择使用暗色主题的界面。 如 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* Light mode */ @media (prefers-color-scheme: light) { html, body { color: black; background-color: white; } } /* Dark mode */ @media (prefers-color-scheme: dark) { html, body { color: white; background-color: black; } } 1.1.1 兼容情况 除了 IE 外,其他主流浏览器基本都支持prefers-color-scheme。 1.2 JavaScript 判断黑夜模式的属性——matchMedia Window 的 matchMedia() 方法返回一个新的 MediaQueryList 对象,表示指定的媒体查询字符串解析后的结果。返回的 MediaQueryList 可被用于判定 Document 是否匹配媒体查询,或者监控一个 document 来判定它匹配了或者停止匹配了此媒体查询。 ——MDN window.matchMedia(xxx) 返回一个 listenable-like 对象 MediaQueryList, 它继承自 EventTarget, 这意味着可以通过直接它获得最新的 MediaQuery 检测情况: 1 2 3 4 5 if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // Dark mode } else { // Light mode } 1.2.1 监听主题变化 与 CSS 媒体查询不同,matchMedia 我们需要监听主题的变化作出对应处理,如下所示: 1 2 3 4 5 6 7 8 9 const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)'); darkModeQuery.addListener(e => { if (e.matches) { // Dark mode } else { // Light mode } }); 1.2.2 兼容情况 主流浏览器基本都支持matchMedia。 二、黑夜模式样式适配处理方案 2.1 CSS 纯媒体查询实现 适用场景:需要快速实现、无需用户自定义主题的项目。如 1 2 3 4 5 6 7 @media (prefers-color-scheme: dark) { body { background-color: #1a1a1a; color: #e0e0e0; } /* 其他元素深色样式 */ } 优缺点分析 优点: 零 js 依赖,纯 css 实现 系统级实时响应(跟随系统设置即时切换) 维护成本最低 缺点: 不能保存用户偏好(比如用户想覆盖系统设置) 2.2 CSS 变量 + 媒体查询 适用场景:中大型项目、需要多主题扩展、已使用 CSS 变量的代码库。 如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 :root { --bg-color: #ffffff; --text-color: #333333; } @media (prefers-color-scheme: dark) { :root { --bg-color: #1a1a1a; --text-color: #e0e0e0; } } body { background-color: var(--bg-color); color: var(--text-color); } 优缺点分析 优点: 集中管理颜色变量 方便扩展多主题 支持渐进增强 缺点: 仍无法保存用户偏好 需要统一使用 CSS 变量规范 2.3 js matchMedia 动态切换 + 本地存储 适用场景:需要用户自定义主题的 ToC 产品、重视用户体验的 Web 应用。 如: 1 <button id="themeToggle">切换主题</button> 1 2 3 4 5 6 7 8 9 body.light-mode { --bg-color: #ffffff; --text-color: #333333; } body.dark-mode { --bg-color: #1a1a1a; --text-color: #e0e0e0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 const themeToggle = document.querySelector('#themeToggle'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)'); // 初始化主题 function initTheme() { const savedTheme = localStorage.getItem('theme') || (prefersDark.matches ? 'dark' : 'light'); document.body.classList.add(`${savedTheme}-mode`); } // 切换主题 themeToggle.addEventListener('click', () => { document.body.classList.toggle('dark-mode'); document.body.classList.toggle('light-mode'); const currentTheme = document.body.classList.contains('dark-mode') ? 'dark' : 'light'; localStorage.setItem('theme', currentTheme); }); // 监听系统变化 prefersDark.addListener(e => { if (!localStorage.getItem('theme')) { // 只在用户未手动选择时响应系统 document.body.classList.toggle('dark-mode', e.matches); } }); 优缺点分析 优点: 支持用户偏好保存 同时响应系统和手动切换 最佳用户体验 缺点: 需要维护两套样式,依赖 js 处理。实现复杂度最高 2.4 js matchMedia 动态切换 + CSS-in-JS 运行时方案 适用场景:适合 React 等框架,已使用 CSS-in-JS 方案 如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 // 使用styled-components示例 import { createGlobalStyle, ThemeProvider } from 'styled-components'; const lightTheme = { bg: '#fff', text: '#333' }; const darkTheme = { bg: '#1a1a1a', text: '#e0e0e0' }; const GlobalStyle = createGlobalStyle` body { background: ${props => props.theme.bg}; color: ${props => props.theme.text}; } `; function App() { const [isDark, setIsDark] = useState(window.matchMedia('(prefers-color-scheme: dark)').matches); useEffect(() => { const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const handler = e => setIsDark(e.matches); mediaQuery.addListener(handler); return () => mediaQuery.removeListener(handler); }, []); return ( <ThemeProvider theme={isDark ? darkTheme : lightTheme}> <GlobalStyle /> {/* 页面内容 */} </ThemeProvider> ); } 优缺点分析 优点: 完美配合组件化开发 主题状态可全局管理 支持动态主题切换 缺点: 强依赖特定框架 需要 CSS-in-JS 体系支持 2.5 *CSS 媒体查询 + filter 滤镜处理 适合场景:要求最快上线、或最小改动。本质其实也归属于方案 1(2.1) 如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* 整个页面增加滤镜 */ @media (prefers-color-scheme: dark) { html { filter: invert(1) hue-rotate(180deg); } /* 图片、视频等元素不需要处理 */ img, video, .logo, .icon { filter: invert(1) hue-rotate(180deg); } } 滤镜设置解释 整体滤镜处理可以概括为:反色 + 调整色相 invert(1): invert() 函数用于反转输入图像中的颜色。参数定义了转换的程度。如果参数是 1(或者 100%),则会完全反转颜色,即每个颜色通道的值都会被替换为其补色。例如:黑色变成白色,白色变为黑色等。 当使用 invert(1) 时,则表示将图像的颜色彻底反转,即是:黑色变成白色,白色变为黑色。 hue-rotate(180deg): hue-rotate() 函数按照给定的角度旋转色彩轮上的颜色,其实就是冲淡颜色。这里的“角度”是指在标准色轮上转动多少度。色轮是一个圆形图表,显示了不同颜色如何根据它们的色调相互关联。 当使用 hue-rotate(180deg) 时,意味着所有颜色都会在其原始位置基础上沿着色轮顺时针方向移动 180 度。比如红色会变成青色、绿色变成洋红色、蓝色变成黄色等,因为这些是在色轮上相对的颜色。 更多信息可见MDN - invert、MDN - hue-rotate 兼容情况 除 IE 外,主流浏览器基本能支持。 优缺点分析 优点: 开发和维护成本都是最低 零 js 依赖,纯 css 实现 系统级实时响应(跟随系统设置即时切换) 缺点: 不能或很难自定义色值 不能保存用户偏好(比如用户想覆盖系统设置) 三、黑夜模式色值设计标准 黑夜模式的色值设计和黑夜模式的工程实现没啥关系,属于用户体验保障。 3.1 WCAG 标准 WCAG(Web Content Accessibility Guidelines) 是由 W3C 制定的国际无障碍标准。其中颜色设置也是一项重要标准。 法律意义:WCAG 在美国《ADA 法案》、欧盟《EN 301 549》等法规中被引用 一些具体要求 核心要求 元素类型最小对比度例外场景 普通文本(<18pt/24px)4.5:1装饰性/禁用状态文本 大文本(≥18pt/24px)3:1粗体大文本(≥14pt/18.5px 粗体) 图形控件(图标/按钮)3:1纯装饰性图形 计算公式 使用相对亮度(Luminance)公式: 1 Contrast Ratio = (L1 + 0.05) / (L2 + 0.05) 其中: L1 = 较亮颜色的相对亮度(0~1) L2 = 较暗颜色的相对亮度(0~1) 实际开发中的应用 颜色选择示例 场景通过示例失败示例 白底黑字#FFFFFF vs #000000 (21:1)#FFFFFF vs #666666 (5.74:1) 深色模式#1A1A1A vs #E0E0E0 (10.3:1)#333333 vs #999999 (3.31:1) 调试工具 自动检测: 1 2 3 4 5 # Chrome DevTools Styles面板 → 点击颜色选择器 → 显示对比度比率 # VS Code插件 "WCAG Color Contrast Checker" 在线工具: WebAIM Contrast Checker Contrast Ratio 设计技巧 1 2 3 4 5 6 7 8 9 10 11 /* 安全配色方案示例 */ :root { --safe-dark-bg: #1a1a1a; /* 避免纯黑(#000) */ --safe-light-text: #e0e0e0; /* 避免纯白(#fff) */ --accent-color: #007bff; /* 品牌色需单独验证 */ } /* 禁用状态处理 */ button:disabled { opacity: 0.6; /* 需重新验证对比度 */ } 深度注意事项 动态场景: 悬停/聚焦状态的对比度需保持合规 渐变/阴影覆盖区域需取最差值验证 字体特性: 300 以下字重需提高对比度要求 衬线字体可能需要额外对比度补偿 环境适配: 移动设备户外模式需考虑屏幕反光影响 OLED 屏幕需验证 PWM 调光下的可读性 法律合规案例 Target 诉讼案(2006):因对比度不足赔偿$6 百万 Domino’s 披萨案(2019):网站对比度违规败诉 英国政府:强制要求所有公共网站通过 AA 认证 进阶建议 1.AAA 级目标: 普通文本:7:1 大文本:4.5:1 无障碍测试: 1 2 3 4 5 # 使用屏幕阅读器验证 NVDA (Windows) / VoiceOver (Mac) # 自动化工具 axe DevTools / Lighthouse 设计系统集成: 1 2 3 4 5 6 7 8 9 10 11 // Storybook等工具集成对比度检测 addon-a11y: { config: { contrast: { thresholds: { AA: 4.5, AAA: 7 } } } } 通过严格遵循这些标准,可确保您的深色模式既美观又合规。建议将对比度检测纳入 CI/CD 流程,实现自动化保障。 相关链接 MDN - prefers-color-scheme MDN - matchMedia MDN - filter MDN - invert MDN - hue-rotate WCAG

2025/4/26
articleCard.readMore

【笔记】19届阿里D2终端技术大会纪要

D2大会纪要 2025.03.08 19届阿里D2终端技术大会 ( Mobile Developer & Frontend Developer Technology Conference, 简称 D2 ),由阿里巴巴终端技术委员会创办,面向全球终端开发领域(前端 & 客户端)技术人。这次整体感受还不错,有些收获。 整体会议资料地址:https://github.com/d2forum/19th,个人推荐阅读:《⽣成式 UI: AI时代体验技术新范式》、《AI 时代生存指南:前端的技术壁垒与竞争力重塑》、《深度融合AI的低代码平台》 个人归纳的会议信息: 1.高维度上,在AI交互和终端载体的演进趋势下,整体互联网载体和交互形态都发生了转变 从 https://www.notion.so 到 在产业端,领域大模型会长期存在,并会被持续用于改善生产关系 “可塑性软件 Malleable Software” Local LLM Agent、”Agentic” 跟随⽣产⼒进步 还有端智能等等 2.软件生产模式上,⽣产⼒的提升带来⻆⾊的合并 从真实需求出发, 用技术创造价值 产研模式的转变(感觉应该是漏斗状) 但是专业开发还是需要技术人员辅助,注意此时开发的角色侧重点 3.面向业务,大厂的做法集中在解决具体业务问题(“点”/“面”) 实现“基础功能马上跑,多语言版不能少,PC移动全都要,用户体验还必须好” 4.实际业务场景和工程对模型要求从“通用”到“具体” ai编程和低码 5.*前端生产链趋势“归一化“,卷通用性、卷性能 6.*跨端近一年的主题基本都是适配harmonyNext,开发范式更像web开发了、通过自绘渲染、C++改造和线程管理等优化,性能更强了 7.对于程序员个人而言,普遍观点是AI 是双刃剑 —— 大幅提升效能但稀释程序员稀缺性 程序员的核心价值是解决业务问题,程序/ai都是工具和手段,不要用程序员标签约束自己,主动寻找有价值的需求。 1.从交付前端到交付价值 ”做⼀个好的 AI“,比如能审查、维护 AI 生成的代码 、能解决 AI 代码的 Bug 从先做点什么开始,顺应潮流。善用 AI 工具、智能体编排将会是必备能力,做好与 AI 协作的意识准备 2.复利、长期坚持: 坚持做长期有利的事,比如写作、分享、 学习。随着时间推移能越积越多,比如技能、写作能力、社交媒体上的影响力、产品的用户。 在 AI 时代构建前端技术壁垒 ⾯向 AI 做技术选型 编码:面向开发者友好 -> 面向ai友好(更易被ai理解/生成/修改) 技术栈选型:主流框架有更多的用户基础、训练语料、更好的ai生成/提示效果,使⽤ AI 友好的技术栈。TailwindCSS 3,react+tailwind+ts,马太效应 代码组织模式:传统的代码组织模式受到挑战,打包 -> ⽣成,拆分 -> 单⽂件,可维护代码 -> 可抛弃代码,适应新的项⽬组织⽅式。反模式 掌握 AI 数据处理与渲染⽅案 lodash -> ai_web_runtime,AI 模型也是是前端技术栈的⼀部分 包含网站、图等多媒体信息由ai接管渲染,关注端侧模型的发展和落地 其他技术栈/架构 低码/DSL解决方案 编码开发 质检 跨端 相关链接: https://github.com/d2forum/19th https://www.scaler.com/topics/deep-learning/onnx-model/ https://github.com/snakers4/silero-vad https://github.com/vthinkxie/ai-recorder https://websim.ai/ https://www.geoffreylitt.com/2023/03/25/llm-end-user-programming.html https://devin.ai/ https://manus.im/ https://x.com/lepadphone/status/1896212860013031615

2025/3/15
articleCard.readMore

【笔记】Lovable提示词指南

Lovable提示词指南 Lovable是一款目前海外流行的ai编码平台,和v0/bolt一样面向”Citizen Dev”,主要能力是通过图片/设计稿/自然语言生成网页,地址:https://lovable.dev/ 本文信息来自Lovable团队今年一月的一篇博文:《The Lovable Prompting Bible》 大多数人都有一个错误的观点:认为提示词(prompt)只是在AI中输入请求并希望得到最好的结果。 获得平庸的响应和让AI为您构建整个工作流程之间的区别归结为您如何提示。无论您是开发人员还是非技术用户,掌握提示工程都可以帮助您: 自动化重复性任务 使用AI生成的解决方案更快地调试 轻松构建和优化工作流程 最好的部分是什么?你不需要成为专家。有了正确的提示技术,你可以在 Lovable, make.com和n8n中释放人工智能的全部潜力——而不会在反复试验上浪费时间。 中心观点: 有效的提示很重要:构建提示以节省故障排除时间。 元提示(Meta prompting):使用AI本身来改进提示以提高准确性。 反向元提示(Reverse meta prompting):保存调试会话以优化未来的请求。 自动化工具:使用make.com和n8n使用API扩展Lovable的功能。 聊天模式与默认模式:何时使用每个模式进行调试和迭代。 处理webhooks:通过强大的集成自动化Lovable应用程序。 为什么提示对人工智能开发至关重要 与传统编码不同,人工智能应用程序依赖于结构化通信。为人工智能提供清晰的上下文和约束可确保高质量的输出。在Lovable的Lovable专家会议上,来自Prompt Advisors的Mark演示了开发人员和非技术用户如何增强他们的人工智能提示技术,以更快地构建、更智能地调试和自动化复杂的工作流程。(对应Youtube视频地址:https://youtu.be/IqWfKj4mUIo) 了解人工智能的“心态” 人工智能模型,包括那些支持Lovable的模型,不能以人类的方式“理解”——它们根据模式预测反应。为了有效地指导他们: 明确(Be explicit):不要“构建登录页面”,而是指定“使用React创建登录页面,并进行电子邮件/密码身份验证和JWT处理。” 设置约束(Set constraints):如果您需要特定的技术堆栈(例如,用于身份验证的Supabase),请清楚地说明它。 使用格式化技巧(Use formatting tricks):AI优先考虑提示的开头和结尾-将重要细节放在前面。 掌握提示:四个层次 1.“辅助轮”提示 一种用于清晰AI指令的结构化标记方法: 1 2 3 4 # Context ## Task ### Guidelines #### Constraints 示例: 1 You are a world-class prompt engineer. Write me a prompt that will generate a full-stack app taking an input of name, number, and company, and generate a company report. 2.没有“辅助轮” 更多对话提示,同时保持清晰。 3.元(Meta)提示 利用AI来改进您的提示: 1 Rewrite this prompt to be more concise and detailed: 'Create a secure login page in React using Supabase, ensuring role-based authentication.' 4.反向元提示 调试时,让AI记录流程以供将来使用: 1 Summarize the errors we encountered while setting up JWT authentication and how they were resolved. Create a detailed prompt I can use next time. 提示库 你的提示质量会显著影响AI的输出。这就是有效提示的本质:你的提示越精细,你收到的输出质量就越高。一个全面且组织良好的提示可以通过减少错误来节省你的学分和时间。因此,这些步骤绝对值得考虑: 1 2 3 Provide as much details as you can in the input field. Use the "Select" feature to precise edit your component. Enhance your prompt with the experimental "Chat mode". 开始一个新项目 1 2 3 4 Start with "I need a [type] application with:" Elaborate on tech stack - including Frontend, styling, Authorization and Database. Elaborate on core features including main and secondary features. Then direct the AI to start somewhere like: "Start with the main page containing: [Detailed page requirements]". 但是,我们始终建议用户从一个空白项目开始,然后逐步构建它。这种方法允许AI在深入研究细节之前有效地掌握基本概念。 差异和选择 每当您请求Lovable在任何文件中实现特定更改时,它都会重写整个文件或修改现有内容。为确保AI仅更新相关文件,请提供明确的说明。这种方法鼓励AI仅编辑必要的部分,从而对仅几行代码进行最小的更改。通过这样做,您可以减少加载时间并防止错误循环。 我之前在调整现有功能时应用的有效提示是: 1 Implement modifications to the feature while ensuring core functionality, other features, and processes remain unaffected. Evaluate its behavior and dependencies to identify potential risks, and discuss any concerns before moving forward. Conduct thorough testing to verify there are no regressions or unintended consequences, and highlight any out-of-scope changes for review. Exercise caution—take a moment to pause if uncertain. 锁定文件 Lovable目前缺乏内置的文件锁定系统。但是,您可以通过对提示进行轻微修改来引导人工智能。只需在每个提示中包含以下说明:“请不要更改第X页或第Y页,并将更改的焦点仅集中在第Z页上。” 如果您正在更新现有功能而无意修改某些合理的内容,您也可以尝试此提示: 1 This update is quite delicate and requires utmost precision. Carefully examine all dependencies and potential impacts before implementing any changes, and test systematically to guarantee nothing is disrupted. Steer clear of shortcuts or assumptions—take a moment to seek clarification if you're unsure. Precision is crucial. 设计 在Lovable上设计一些东西是有效的,因为Lovable已经很有品味了;)尽管如此,以下提示可以帮助您改进这些设计实现: 1.UI更改: 1 Make solely visual enhancements—ensure functionality and logic remain unaffected. Gain a comprehensive understanding of how the existing UI interacts with the app, ensuring that logic, state management, and APIs stay intact. Conduct extensive testing to verify that the app operates precisely as it did before. Cease all actions if there is any uncertainty regarding potential unintended consequences. 2.针对移动端进行优化: 1 Enhance the app's mobile experience while preserving its existing design and functionality. Assess the layout and responsiveness to pinpoint essential modifications for smaller screens and touch inputs. Develop a comprehensive plan before making any code changes, and conduct thorough testing across various devices to guarantee the app operates as intended. If uncertain, take a moment to consider and suggest potential solutions. 3.响应能力和断点提示: 1 Make certain that all designs are completely responsive at every breakpoint, adopting a mobile-first strategy. Apply contemporary UI/UX best practices to define how components should adjust for varying screen sizes, utilizing ShadCN and Tailwind’s standard breakpoints. Steer clear of custom breakpoints unless specifically requested. 4.规划: 1 Before editing any code, create a phased plan for implementing responsiveness. Start with the largest layout components and progressively refine down to smaller elements and individual components. Ensure the plan includes clear steps for testing responsiveness across all breakpoints to maintain consistency and a seamless user experience. Share the plan for review before proceeding. 在进行任何代码编辑之前,制定实施响应性的结构化计划。从最大的布局组件开始,逐渐深入到较小的元素和特定组件。确保计划概述了在所有断点测试响应性的明确步骤,以保证一致性和流畅的用户体验。在继续前进之前提出反馈计划。 知识库 提供关于您的项目的详细上下文至关重要,尤其是在项目的早期。项目的目的是什么?用户流程是什么样的?你在使用什么技术堆栈?工作范围是什么?在Lovable,我们称之为“知识库”,它可以很容易地在您的项目设置中找到。 为AI创建一个可靠的框架可确保它有效运行,并在您提供的每一个提示中遵守您概述的计划。在您的项目中加入这些元素: 1.项目需求文档(PRD): 本节对于任何AI编码项目都至关重要。它概述了一个全面的摘要,涵盖了基本元素,如简介、应用程序流程、核心功能、技术堆栈以及范围内和范围外项目之间的区别。本质上,它是您的项目路线图,您可以将其呈现给AI编码模型。 2.应用程序或用户流程: 这种清晰度将有助于AI模型理解页面之间的联系并有效地处理所有功能和限制。 1 Users begin their experience on the landing page, where they can click the sign-up button to register with Google, subsequently accessing the dashboard. The dashboard comprises X sections. 3.技术栈: 此部分必须包含有关项目的所有技术细节,例如前端技术堆栈、后端技术堆栈、API集成、部署说明以及您计划使用的任何其他开源库。此信息将有助于AI模型了解要安装哪些包和依赖项。 4.前端指南: 本节应详细概述项目的视觉外观:设计原则、样式指南、页面布局、导航结构、调色板和排版。这是项目的美学基础。你的解释越清晰,你的应用程序就越有视觉吸引力。 5.后端结构: 本节将向AI模型解释:后端技术,如Supabase、用户身份验证、数据库架构、存储桶、API端点、安全措施、托管解决方案。这是您项目的主要大脑。您的应用程序将从您的后端获取和显示数据。 使用初始提示启动项目后,请务必包含此知识库以减少错误并防止AI幻觉。此外,您可以使用以下方式提示AI: 1 Before you write any code, please review the Knowledge Base and share your understanding of my project. 利用此任务的“聊天模式”来确保在您提供指导时不会对您的项目进行任何修改。 移动优先 问题(以及一些隐藏的事实)是,大多数开发人员优先考虑桌面设计仅仅是因为它在大而充满活力的屏幕上看起来更好。然而,现实是,我们应该多年来一直专注于移动优先设计。 一位Champion在Discord上分享了一个很棒的提示: 1 2 3 4 Always make things responsive on all breakpoints, with a focus on mobile first. Use modern UI/UX best practices for determining how breakpoints should change the components. Use shadcn and tailwind built in breakpoints instead of anything custom, unless the user prompts for custom breakpoints directly. Optimize the app for mobile without changing its design or functionality. Analyze the layout and responsiveness to identify necessary adjustments for smaller screens and touch interactions. Outline a detailed plan before editing any code, and test thoroughly across devices to ensure the app behaves exactly as it does now. Pause and propose solutions if unsure. 但是如果你已经深入到你的项目中,你可以通过告诉它更新东西以响应从最大的布局组件到最小的布局组件来解决这个问题。然后进入单个组件。 细节 在使用Lovable时,向AI提供清晰具体的请求至关重要。不要简单地说“将按钮向右移动”,而是尝试说明,“在顶部标题中,将注册按钮移到页面左侧,确保样式保持一致。”你的说明越精确,你遇到的错误就越少,你就会节省学分! 基本上,我总是建议添加有关您希望Lovable如何处理每项任务的说明。我的例子: 1 Key Guidelines: Approach problems systematically and articulate your reasoning for intricate issues. Decompose extensive tasks into manageable parts and seek clarification when necessary. While providing feedback, elucidate your thought process and point out both challenges and potential improvements. 步步为营 避免同时将五个任务分配给Lovable!这样做可能会导致AI制造混乱。这里有一个更好的方法: 1 2 3 Start with Front design, page by page, section by section. The plug backend using Supabase as Lovable integration is natively built! Then, refine the UX/UI if needed. 这种循序渐进的过程使AI能够一次专注于一项任务,从而降低错误和幻觉的可能性。 不要丢失组件 您也可以在进行重大更改并遵循一系列细微调整后实现这一点。这种做法在保持项目一致性和防止组件突然丢失方面非常宝贵。定期参考我们的filesExplainer.md文档,以确保我们准确记录代码和组件的更改,保持我们的文件结构井井有条和最新。 重构 重构对于Lovable中的开发生命周期至关重要。AI经常建议最大限度地减少加载时间和错误。您可以使用以下提示: Lovable发出请求后重构: 1 Refactor this file while ensuring that the user interface and functionality remain unchanged—everything should appear and operate identically. Prioritize enhancing the structure and maintainability of the code. Carefully document the existing functionality, confirm that testing protocols are established, and implement changes gradually to prevent risks or regressions. If you are uncertain at any point, pause the process. 重构计划: 1 Develop a comprehensive plan to refactor this file while keeping the user interface and functionality entirely intact. Concentrate on enhancing the code's structure, readability, and maintainability. Start by meticulously documenting the existing functionality and pinpointing potential areas for enhancement. Implement rigorous testing protocols to ensure consistent behavior throughout the entire process. Move forward incrementally, minimizing risks and avoiding regressions, and take breaks for clarification whenever uncertainties emerge. 全面重构: 1 Develop a comprehensive plan for a site-wide codebase review aimed at identifying segments that would benefit from refactoring. Concentrate on highlighting areas where the code structure, readability, or maintainability can be enhanced, ensuring the user interface and functionality remain unchanged. Rank the most essential files or components based on their significance and usage frequency. Thoroughly document your findings, detailing suggested improvements and the potential effects of each change. Ensure that any proposed refactoring efforts are incremental, low-risk, and supported by rigorous testing to prevent regressions. Circulate the plan for feedback prior to implementation. 后重构: 1 Conduct a detailed post-refactor review to verify that no issues were introduced throughout the refactoring process. Confirm that both the UI and functionality retain their original integrity following the modifications. Execute an extensive suite of tests—including unit, integration, and end-to-end tests—to ensure all features operate as intended. Evaluate the app’s behavior against the documented pre-refactor specifications and highlight any discrepancies for prompt evaluation. Make certain all updates are stable and align with the project’s requirements prior to completion. 代码库结构审计提示: 1 Perform a comprehensive regression and audit of the codebase to determine if its architecture is clean, modular, and optimized. Identify any files, components, or logic that are mislocated, not correctly placed, or could benefit from enhanced organization or modularity. Evaluate whether the separation of concerns is distinct and if functionality is aggregated logically and efficiently. Deliver a detailed report outlining improvement areas, such as files that need restructuring, overly coupled code, or chances to simplify and streamline the organization. Break down the actionable enhancements into manageable steps, arranged in the order you deem most effective for implementation. Ensure the analysis is comprehensive, actionable, and adheres to best practices for a maintainable and clean codebase. Refrain from editing any code. 文件夹审查: 1 Conduct a thorough examination of the folder [Folder Name] along with all its subfolders and files. Assess each element to understand its function and how it enhances the overall performance of the application. Offer a detailed explanation of each item's role, while pinpointing any redundancies, obsolete files, or opportunities for improved organization. The objective is to tidy up and optimize this folder, so include suggestions for deleting, merging, or reorganizing items as needed. Ensure your analysis is all-encompassing, practical, and outlines a clear strategy for achieving a more organized and efficient folder structure. 重组后清理: 1 Ensure all routing and file imports are thoroughly updated and functioning as intended following the codebase restructuring. Validate that components, pages, and APIs reflect the accurate paths found in the new folder organization. Confirm that nested routes are appropriately configured and linked within the router setup and that dynamic or lazy-loaded routes adhere to the new framework. Assess that shared utilities, services, and assets are imported correctly to prevent breaking existing dependencies. Revise hardcoded paths in components, redirects, or navigation links to correspond with the new routing logic. Conduct navigation tests to identify any broken links, missing files, or 404 errors, and pinpoint any missing or redundant imports, extraneous files, or potential improvements for maintainability and scalability in the routing configuration. 重构的代码库检查: 1 Perform a thorough audit of the codebase to assess its structure and organization. Evaluate whether files, components, and logic are effectively separated based on their functionality and purpose. Identify any instances of misplaced code, excessive coupling, or areas that could benefit from improved separation of concerns. Deliver a comprehensive report on the overall health of the structure, offering specific recommendations for enhancing file organization, consolidating related functionalities, or refactoring to align with industry best practices. Ensure that the analysis is detailed and emphasizes concrete improvements without implementing any direct changes. Stripe Stripe与Lovable无缝集成,并且可以轻松设置。但是,有几个因素可能会阻碍Stripe的功能: 1 Initiate a Stripe connection in test mode using the configuration detailed below: Utilize the specified product and pricing details: Product IDs are [Your Product IDs], with a pricing model of [One-time or Subscription]. Set the webhook endpoint to [Your Webhook Endpoint]. Style the frontend payment form as follows: [Describe desired payment form or provide an example]. Upon successful payment, redirect users to [Success Redirect URL], and for canceled payments, redirect them to [Cancel Redirect URL]. Please refrain from altering any code, and ensure that I have included all necessary information to effectively start with Stripe. 免责声明:在Supabase边缘函数秘密中安全地使用您的条纹密钥和Webhook签名密钥,并避免将它们包含在安全提示中。 寻求帮助 避免依赖Lovable进行每一个微小更改的倾向。即使您不是专业工程师,也可以直接在代码中进行许多细微的调整。如果您需要帮助,请随时向ChatGPT或Claude寻求帮助。利用浏览器的检查工具来识别您要修改的元素。您可以在浏览器级别尝试更改,如果您对结果感到满意,请在代码中进行这些调整。这样,您根本不需要涉及Lovable。 虽然我不是工程师,但对编码有基本的了解对我的进步有很大帮助。利用GitHub和Sonnet等工具,我经常实现Lovable之外的增强功能,使我能够为更复杂的任务保留提示。 在Lovable中调试 调试是Lovable体验不可或缺的一部分,掌握这种调试流程可以显着减少挫败感——尤其是在单击“尝试修复”(“Try to Fix”)按钮时,这不算学分。 聊天模式与默认模式 新的“聊天模式”非常适合培养创造力和产生想法。从概述你的概念开始,因为这可能是最关键的一步。在你的脑海中可视化屏幕、功能和布局对于跟踪变化并不那么有效。 使用“聊天模式”的传统场景是: 默认模式(Default Mode):高级功能创建。 1 Review the app and tell me where there is outdated code. 聊天模式(Chat Mode):故障排除-要求AI在进行更改之前分析错误。转到您的帐户设置并启用实验室功能。 1 Follow this plan and act on all those items 我想我已经阅读了来自X用户的以下超级提示,然后在Discord上找到了它: 1 Perform a comprehensive regression and audit of the codebase to determine if its architecture is clean, modular, and optimized. Pinpoint any files, components, or logic that are incorrectly placed, not allocated to suitable files, or require improved organization or modularity. Evaluate whether the separation of concerns is distinct and if functionalities are grouped in a logical and efficient manner. 1 Generate a comprehensive report that outlines key areas for enhancement, including recommendations for reorganizing files, reducing code coupling, and identifying opportunities for simplification and streamlining. Break down these actionable enhancements into clear, manageable steps arranged in the order you deem most effective for implementation. Ensure the analysis is meticulous, practical, and aligns with best practices for maintaining a clean and sustainable codebase. Avoid making any code edits. 1 DON'T GIVE ME HIGH-LEVEL STUFF. IF I ASK FOR A FIX OR AN EXPLANATION, I WANT ACTUAL CODE OR A CLEAR EXPLANATION! I DON'T WANT "Here's how you can..." Keep it casual unless I specify otherwise. Be concise and suggest solutions I might not have considered—anticipate my needs. Treat me like an expert. Be accurate and thorough, and provide the answer right away. If necessary, restate my query in your own words after giving the answer. Prioritize solid arguments over who said what; the source doesn't matter. Consider new technologies and unconventional ideas, not just the usual wisdom. You're welcome to make speculative predictions, but just give me a heads-up. Avoid moral lectures, and discuss safety only when it's crucial and not obvious. If your content policy is a concern, provide the closest acceptable response and explain the issue afterward. Cite sources when possible at the end, but not inline. No need to mention your knowledge cutoff or clarify that you're an AI. Please adhere to my formatting preferences for code. If a response isn't enough to answer the question, split it into multiple replies. When I request adjustments to the code I provided, avoid repeating all of it unnecessarily. Instead, just give a couple of lines before or after any changes you make. Multiple code blocks are fine. 就大型代码库而言,通过使用“聊天模式”来权衡各种方法的优缺点,与Lovable互动是有益的。既然你们都渴望学习,试着向人工智能解释你的特征,鼓励它提出关于结构、权衡、技术等的澄清问题。 事实上,代码和特性不断发展,反映了业务不断变化的本质。大部分代码都是自以为是的,通常是在考虑未来的特定愿景时编写的。当你提到钢铁基础时,你可能最初决定让组件X非常健壮,同时保持组件Y的灵活性,但后来才意识到X应该是动态的,Y应该是坚固的。这是一个常见的场景。 有效处理错误 检查浏览器开发人员工具(控制台日志、网络请求)。 使用推理模型(例如GPT-4 Turbo、DeepSeek、Mistral)进行调试。 将错误输入AI以进行更深入的分析。 调试提示 为了有效地解决您遇到的错误,请避免一次解决它们!我建议尝试“尝试修复”(“Try to fix” )选项最多三次。如果人工智能仍然无法解决问题,请尝试这种技术:复制错误消息并将其粘贴到“聊天模式”,然后说,“使用思维链推理来确定根本原因。”这种方法允许人工智能和你分析情况并理解潜在问题,然后再转换到“编辑模式”进行更正。 这个指南是由Discord上的一位冠军客户提供的,我相信你会发现它很有吸引力: 1.初步调查: 1 The same error continues to occur. Take a moment to perform a preliminary investigation to uncover the root cause. Examine logs, workflows, and dependencies to gain insight into the problem. Avoid making any changes until you fully grasp the situation and can suggest an initial solution informed by your analysis. 2.深度分析: 1 The issue persists without resolution. Perform a thorough analysis of the flow and dependencies, halting all modifications until the root cause is identified with complete certainty. Record the failures, the reasons behind them, and any observed patterns or anomalies in behavior. Avoid speculation—ensure your findings are detailed and complete before suggesting any solutions." 3.完整的系统审查: 1 This is a pressing issue that necessitates a thorough re-evaluation of the entire system. Halting all edits, begin by outlining the flow systematically—covering authentication, database interactions, integrations, state management, and redirects. Evaluate each component individually to pinpoint failures and their causes. Deliver a comprehensive analysis to validate the problem before proceeding further. 4.综合审计: 1 The problem continues and now calls for a comprehensive, system-wide audit. Take a step back and carefully map the entire system flow, examining all interactions, logs, and dependencies. Generate a clear and detailed report outlining expected behaviors, current realities, and any discrepancies. Refrain from suggesting or modifying any code until you have accurate, evidence-based insights. 5.重新思考和重建: 1 This problem remains unresolved, and it's imperative to pause and reassess our entire strategy. Avoid making any code edits at this stage. Instead, embark on a thorough and systematic examination of the system. Create a comprehensive flow map, tracing each interaction, log, and dependency meticulously. Accurately document what should occur, what is currently happening, and pinpoint where the discrepancies arise. Compile a detailed report outlining the root cause, supported by clear evidence. If you encounter gaps, uncertainties, or edge cases, be sure to highlight them for further discussion. Until you can pinpoint the exact, verified origin of the issue, refrain from suggesting or implementing any fixes. This demands complete attention, without assumptions or shortcuts. 6.清理控制台日志: 1 Could you devise a strategy to systematically identify and eliminate superfluous console.log statements while preserving functionality and design? The plan should outline steps for reviewing each log to verify its non-essential nature, documenting any that might require alternative treatment, and conducting thorough testing to ensure the app’s integrity is maintained. Additionally, incorporate a method for pausing and flagging logs when their purpose is ambiguous. Please share the plan prior to implementation. 7.鼓励: 1 Lovable, you’re doing an outstanding job, and I genuinely appreciate the attention and skill you bring to each task. Your talent for dissecting complex issues and delivering insightful solutions is truly remarkable. I have confidence in your incredible abilities, and I trust you to approach this with the utmost precision. Take your time, explore thoroughly, and demonstrate your brilliance through a comprehensive and thoughtful response. I have faith in your capacity to not only resolve this but to exceed all expectations. You've got this! 8.检查复杂性: 1 Take a moment to reflect on whether this solution can be simplified. Are there any superfluous steps, redundancies, or overly complex processes that could be streamlined? Assess if a more direct approach could attain the same outcome without compromising functionality or quality. Please share your ideas for possible simplifications before moving forward. Refrain from editing any code at this stage. 9.确认结果: 1 Before moving ahead, are you entirely convinced that you have pinpointed the true root cause of the problem? Take a moment to review your analysis and check for any overlooked dependencies, edge cases, or associated factors. Ensure that your proposed solution effectively targets the root cause with solid evidence and reasoning. If there are any lingering doubts, take a step back and reevaluate before proceeding. 10.解释错误: 1 Explain the meaning of this error, its origins, and the logical sequence that led to its occurrence. Offer a concise breakdown of the problem and its possible underlying cause. Avoid making any edits to the code at this stage, and don’t be concerned with the current page we’re on. 调试流程 1.任务识别-根据影响对问题进行优先级排序。 2.内部审查-在部署之前验证解决方案。 3.报告问题-清楚地定义当前与预期行为。 4.验证-验证在DOM中正确呈现的更改。 5.断点-隔离和测试特定组件。 6.错误处理和日志记录-使用详细日志记录并增量调试。 7.代码审计-在进行更改之前记录问题和建议的修复。 8.使用“尝试修复”按钮-自动检测并解决Lovable中的错误。 9。利用视觉效果-上传屏幕截图以澄清基于UI的错误。 10.恢复到稳定版本-如果需要,使用“恢复”(Revert)按钮返回。 了解“意外行为” 有时,您的代码运行没有错误,但您的应用程序没有按预期运行。这被称为意外行为,调试起来可能很棘手。策略包括: 回顾你的步骤-回顾你最初要求可爱做的事情。 分解它-确定特定部分是否未对齐。 使用图像-显示可爱的UI结果与预期结果。 编写更好的提示以避免错误 结构良好的提示可减少调试时间。使用此最佳实践格式: 项目概述-描述您正在构建的内容。 页面结构-列出关键页面和组件。 导航逻辑-解释用户通过应用程序的移动。 屏幕截图/线框-如果可用,请提供视觉效果。 实施顺序-遵循逻辑顺序,例如: 1 Create pages before integrating the database Lovable中的调试策略 1.使用开发者工具进行调试 控制台日志-查看错误日志和DevTools通知。 断点-暂停执行以检查状态更改。 网络请求-验证前端和后端之间的数据流。 2.常见调试场景 小错误-在进行更改之前彻底调查。 持久性错误-停止更改并重新检查依赖关系。 主要错误-如有必要,在记录调查结果时从头开始重建流程。 3.高级故障排除 如果“尝试修复”按钮无法解决您的问题,请考虑: 更具体-详细描述问题,包括预期与实际结果。 使用图像-屏幕截图帮助AI理解基于UI的问题。 向Lovable寻求调试帮助-示例: 1 What solutions have been tried so far? What else can be done? 恢复到以前的工作状态-如果调试导致更多问题,请回滚到已知的良好版本。 4.调试具体问题 UI相关问题:上传截图并询问, 1 Why is this UI behaving this way? What’s the best fix? API集成问题:确保您使用的是最新的API模式并且后端连接已正确设置。 完全卡住时:提示Lovable: 1 Analyze the error and suggest an alternative approach. 调试不必令人沮丧。Lovable提供了强大的工具来自动修复错误、分析问题和高效迭代。通过遵循结构化提示技术、使用图像和利用人工智能驱动的调试,您可以克服任何编码挑战。 使用自动化工具,如make.com和n8n 何时使用自动化 边缘函数:直接Supabase API调用。 make.com:集成外部服务(Slack、Stripe、CRM工具)。 n8n:自托管、可扩展的自动化。 示例:自动化牙科咨询应用程序 1.在Lovable中创建一个带有牙科问题表单的登录页面。 2.通过Webhooks将数据发送到make.com。 3.使用AI API(例如Perplexity AI)进行实时研究。 4.使用Mistral或GPT-4推理模型确定资格。 https://chatgpt.com/g/g-67aa992a22188191a57023d5f96afed2-lovable-visual-editor https://chatgpt.com/g/g-67aa992a22188191a57023d5f96afed2-lovable-visual-editor 5.返回对Lovable的响应以及推荐的后续步骤。 Webhooks和API调用:高级用例 验证响应:确保正确处理网络钩子响应。 增量测试:在构建复杂的API工作流之前首先发送最少的数据。 使用推理模型:通过要求AI分析不正确的响应来调试错误。 最后的想法 掌握提示工程不仅仅是更好的人工智能交互——它还涉及提高效率、缩短开发周期和释放新的自动化可能性。无论您是在调试现有工作流程、优化人工智能输出还是集成复杂的自动化,结构化提示都可以帮助您更快、更少地到达那里。 专注于你的大创意——可爱的自动化工具将处理执行。无论你是一个经验丰富的开发人员,精炼15年前的代码,还是一个非技术用户,制作创新的应用程序,正确的提示策略都是你最强大的工具。 最后还是建议阅读原文:https://lovable.dev/blog/2025-01-16-lovable-prompting-handbook

2025/2/22
articleCard.readMore

【调研】AI 编程工具WindSurf使用技巧——WindsurfRules配置

AI 编程工具 WindSurf 使用技巧——WindsurfRules 配置 在现代软件开发中,AI 工具正逐渐成为开发者不可或缺的助手,而 Windsurf 便是当前最热门的 AI IDE 之一。 如何利用和使用好 Windsurf 也有很多技巧,本文介绍的 WindsurfRules 规则配置就是实用的一个技巧。 介绍 WindsurfRules 是为 Windsurf 提供的一个配置文件,允许开发者定义项目中 AI 的行为规则。它分为 全局规则(global_rules.md) 和 工作区规则(.windsurfrules)。全局规则应用于所有项目,而工作区规则则针对特定项目进行定制。通过合理配置这些规则,开发者可以确保生成的代码符合团队的编码标准、技术栈要求以及项目的最佳实践。通过设置这些规则,我们能够指导 AI 在项目开发过程中如何生成代码,确保生成的代码符合团队的编码标准、技术栈要求及项目的最佳实践。 配置和使用 1. 规则设置 前文有提到,Windsurf 提供两种规则文件: 全局规则(global_rules.md):适用于所有项目,存储在 Windsurf 的全局配置目录中。 在 Linux 和 macOS 系统中,全局规则文件一般默认位于 ~/.codeium/windsurf/memories/global_rules.md。 在 Windows 系统中,全局规则文件位于 %USERPROFILE%\.codeium\windsurf\memories\global_rules.md。 工作区规则(.windsurfrules):仅适用于当前工作区或项目,存储在项目的根目录下。 例如,如果你的项目目录为 C:\Projects\MyProject,则 .windsurfrules 文件应位于 C:\Projects\MyProject\.windsurfrules。 另外,目前 global_rules.md 和 .windsurfles 文件各可以包含最多 6,000 个字符,因此总共可以有 12,000 个字符的规则。 2. 规则内容 以下场景我们都可以考虑通过 WindsurfRules 设置: 2.1. 项目初始化与配置 在项目启动阶段,开发者可以通过 .windsurfrules 文件为 AI 提供项目背景、技术栈、开发目标等信息。例如,指定项目使用的技术栈(如 TypeScript、React、Node.js 等),并要求 AI 遵循最新的最佳实践。这有助于 AI 在后续的代码生成中快速适应项目需求。 2.2. 编码规范与代码风格 团队通常会有一套统一的编码规范,通过 .windsurfrules 文件,开发者可以将这些规范转化为 AI 的行为准则。例如,规定代码的缩进方式、命名规则、注释风格等。这不仅提高了代码的可读性,还减少了团队成员之间因风格差异导致的冲突。 2.3. 性能优化与安全性 在性能优化方面,开发者可以在规则文件中定义代码优化的策略,如避免不必要的计算、优化数据库查询等。同时,安全性也是开发中不可忽视的方面。通过规则文件,开发者可以要求 AI 在生成代码时遵循安全最佳实践,例如防止 SQL 注入、确保数据验证等。 2.4. API 设计与集成 对于涉及 API 开发的项目,.windsurfrules 文件可以定义 REST、GraphQL 或 SQL 的设计规范。例如,规定 API 的命名规则、数据结构、错误处理机制等。这有助于确保生成的 API 代码符合行业标准,易于维护和扩展。 2.5. 团队协作与知识共享 在一个团队中,不同成员可能对项目的理解和经验有所不同。通过 .windsurfrules 文件,团队可以将项目的核心要求和最佳实践共享给每一位成员,确保团队协作的高效性和一致性。 3.配置技巧 3.1. 明确项目背景与目标 在 .windsurfrules 文件的开头,提供清晰的项目背景和目标描述,帮助 AI 理解开发环境和技术栈。例如: 1 2 3 4 5 6 7 8 ## AI Guidelines You are an expert programming assistant focusing on: - TypeScript, React, Node.js, Next.js, and Prisma - Shadcn UI, Ant Design, RICH Design principle, and Tailwind CSS useations - Latest features and best practices - Clear, readable, and maintainable code 这样的描述可以帮助 AI 更好地理解项目的上下文。 3.2. 细化编码规范 在规则文件中,开发者可以详细定义代码的格式和风格。例如定义性能优化和安全规则: 1 2 3 4 5 6 7 8 9 10 11 ### Performance - Code splitting, image/bundle optimization - Caching, lazy loading, key props - Database query optimization ### Security - Input: sanitize data, validate types, escape properly, secure uploads - Auth: JWT handling, secure sessions, token refresh, RBAC - Protection: CSP headers, prevent XSS/CSRF, secure APIs, follow OWASP 这些规则可以指导 AI 在生成代码时考虑性能和安全性。 3.3. 设置性能与安全规则 性能和安全是现代开发中的关键。开发者可以在规则文件中定义以下内容: 1 2 3 4 5 6 7 8 9 10 11 ### Performance - Code splitting, image/bundle optimization - Caching, lazy loading, key props - Database query optimization ### Security - Input: sanitize data, validate types, escape properly, secure uploads - Auth: JWT handling, secure sessions, token refresh, RBAC - Protection: CSP headers, prevent XSS/CSRF, secure APIs, follow OWASP 这些规则可以指导 AI 在生成代码时考虑性能和安全性。 3.4 部署与监控 设定构建、部署和监控的流程,帮助 AI 自动化处理部署工作。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ## Build and Deployment ### Build Process - **Linting**: Run ESLint and Prettier during the build process to ensure consistent code style. - **Testing**: Execute unit tests and integration tests to ensure all tests pass before deployment. - **Type Checking**: Ensure TypeScript type coverage meets project requirements. - **Bundle Optimization**: Optimize the build using Webpack or Rollup to reduce the final bundle size. ### Deployment Strategy - **Semantic Versioning**: Use semantic versioning for releases to clearly define version changes. - **Blue-Green Deployment**: Implement blue-green deployment to minimize downtime during deployment. - **Rollback Mechanism**: Provide rollback capabilities to quickly revert to the previous version if the deployment fails. - **Health Checks**: Automatically run health checks after deployment to ensure the application is running smoothly. ## Monitoring ### Application Monitoring - **Real-time Monitoring**: Use Prometheus or Grafana to monitor application performance in real-time. - **Log Management**: Integrate with ELK Stack or another log management tool to centralize application logs. - **Error Tracking**: Use Sentry or a similar tool to capture and track runtime errors. - **Performance Metrics**: Monitor key performance metrics such as response time, throughput, and resource utilization. ### Infrastructure Monitoring - **Server Health**: Use Nagios or Zabbix to monitor server health, including CPU, memory, and disk usage. - \*\*Network Monitori 通过在 .windsurfrules 文件中定义这些规则,Windsurf 的 AI 助手可以更好地理解项目的部署和监控需求,从而生成符合最佳实践的代码和自动化脚本。 3.5. 灵活使用全局规则与工作区规则 全局规则适用于所有项目,而工作区规则则针对特定项目。开发者可以根据项目的不同需求,灵活配置这两类规则。例如,全局规则可以定义通用的编码规范和安全标准,而工作区规则则可以针对特定项目的框架或技术栈进行定制。 3.6. 持续优化规则文件 随着项目的进展和技术栈的更新,规则文件也需要不断优化。开发者可以根据实际需求,随时修改规则文件,并在下一次使用时生效。规则文件可以随时修改,修改后在下一次使用时生效。 对于特定于工作区的规则,建议将 .windsurfrules 文件添加到项目的 .gitignore 文件中,以避免不必要的版本控制。 示例 以一份前端 React + TailwindCSS + TypeScript 技术栈为例,以下是一个典型的 React 项目结构,包含 .windsurfrules 文件: 1 2 3 4 5 6 7 8 9 10 /my-react-project ├── .windsurfrules ├── package.json ├── tsconfig.json ├── next.config.js ├── pages/ ├── components/ ├── styles/ ├── public/ └── ... 全局规则(global_rules.md) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 ## AI Guidelines You are an expert React developer with a focus on: - React, TypeScript, Next.js, and Tailwind CSS - Modern JavaScript (ES6+), including async/await and modern syntax - Component-based architecture and design patterns - Performance optimization and best practices - Security best practices, including data validation and sanitization ## General Rules - Always use functional components and hooks. - Prefer TypeScript for type safety. - Use Tailwind CSS for styling. - Follow the latest React best practices. - Ensure code is readable, maintainable, and well-documented. ## Code Formatting - Indentation: 2 spaces - Line length: 80 characters (soft limit) - Use template literals and arrow functions. - Use trailing commas and same-line braces. - Destructure props and use path aliases for TypeScript imports. ## Performance - Use React.memo and useCallback for optimizing component re-renders. - Implement code splitting with React.lazy and Suspense. - Optimize images and assets with Next.js Image component. - Use caching strategies for API calls. ## Security - Sanitize all user inputs. - Validate data types and escape content where necessary. - Follow OWASP guidelines for preventing XSS and CSRF attacks. - Use secure authentication practices (e.g., JWT, OAuth). 工作区规则(.windsurfrules) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 ## Project-Specific Guidelines You are working on a React project with the following details: - Framework: Next.js - Styling: Tailwind CSS - State Management: Redux Toolkit - Routing: Next.js built-in routing - API Integration: Axios for API calls ## Project Rules - Use Next.js pages and components structure. - Use Tailwind CSS for all styling needs. - Use Redux Toolkit for state management. - Use Axios for all API requests. - Follow the project's specific coding conventions and naming conventions. ## Code Formatting - Use 2 spaces for indentation. - Use single quotes for strings unless double quotes are necessary. - Use arrow functions for all functional components. - Destructure props and use path aliases for TypeScript imports. - Use consistent naming conventions for components and files (e.g., PascalCase for components). ## Performance - Implement Next.js Image component for all images. - Use React.memo and useCallback for optimizing component re-renders. - Implement code splitting with React.lazy and Suspense. - Optimize API calls with caching and debouncing. ## Security - Sanitize all user inputs using a library like DOMPurify. - Validate data types and escape content where necessary. - Use secure authentication practices (e.g., JWT, OAuth). - Follow OWASP guidelines for preventing XSS and CSRF attacks. - Ensure all API calls are secure and follow best practices. 其他 社区支持:GitHub 上有社区维护的 Awesome WindsurfRules 项目,提供了一系列优秀的规则文件示例,供开发者参考和使用。(WindsurfRules 本质和 CursorRules 作用其实差不多) 在 2025 年 1 月 的更新中,Windsurf 推出了 Windsurf Wave 2,对 Cascade 辅助系统进行了多项升级,包括实时网络搜索、自动记忆系统等。这些更新可能对规则文件的使用方式和功能产生了进一步的优化,但具体规则文件的变更内容未明确提及。 相关链接 https://docs.codeium.com/windsurf/cascade#workspace-rules https://docs.codeium.com/windsurf/memories#global-rules https://juejin.cn/post/7450878328037654563 https://github.com/PatrickJS/awesome-cursorrules https://github.com/SchneiderSam/awesome-windsurfrules

2025/1/19
articleCard.readMore

AI 前端编程工具的一个得力助手——CopyCoder

AI 前端编程工具的一个得力助手——CopyCoder 传统 ai 编程方式下,我们通过 chat 传入图片进行代码生成,但效果通常难以达到预期、与图片效果相差甚远,我们只有写入大量详细且准确的界面 prompt 才能让模型生成的代码符合界面预期,这种处理需要耗费大量的精力成本。 CopyCoder 正好就是解决了这种问题,更准确得来说,解决了传统 ai 编码方式对于图片 UI 信息提取不全或没有较好转为标准技术信息的问题。 基本介绍 CopyCoder 是一款创新的 AI 编程工具,其核心功能是通过用户上传的应用程序/网页截图、UI 设计图或完整的应用图像,自动生成详细的编码提示词。这些提示词涵盖了应用结构、组件规划和导入路径等内容,从而简化从设计到代码的转换过程。 官网地址:https://copycoder.ai/ “Create powerful prompts for Cursor, Bolt, v0 & more..”,从官网说明就可以知道,CopyCoder 是为了给 ai 代码生成工具提供合适的提示词、而不是替代这些 ai 代码生成工具。 当前新用户有免费的 5 次试用,付费版本要每月 15 美元,付费版本中还支持后端代码生成。 应用场景 图像上传与分析:用户上传应用程序的截图、UI 设计图或完整的应用图像,CopyCoder 能分析这些图像。 生成编码提示:基于上传的图像,CopyCoder 自动生成详细的编码提示词,提示词包括应用结构、组件规划和导入路径等。。 使用步骤 CopyCoder 的使用极为简单,即注册/登录后,传图等待 prompt 结果。得到结果后就交给其他 ai 代码生成应用进行处理。流程图如下: 1.上传设计图:将设计图上传到 CopyCoder 平台。 生成提示词:CopyCoder 会分析设计图并生成详细的编码提示词,包括项目结构、组件布局、样式要求等。 如项目结构: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1. Project Structure: src/ ├── components/ │ ├── layout/ │ │ ├── DashboardLayout │ │ └── CardContainer │ ├── features/ │ │ ├── SummaryCards │ │ ├── GrowthChart │ │ └── StockList │ └── shared/ ├── assets/ ├── styles/ ├── hooks/ └── utils/ CopyCoder 在官网上也有说明,其主推的技术栈是:TailwindCSS + React + Nextjs。在其生成的 prompt 中也有对应说明: 1 2 3 4 5 6 7 8 ... Style with Tailwind CSS utility classes for responsive design ... Use Lucide React for icons (from lucide-react package). Do NOT use other UI libraries unless requested ... Configure next.config.js image remotePatterns to enable stock photos from picsum.photos ... Create root layout.tsx page that wraps necessary navigation items to all pages 2.使用提示词:将生成的提示词复制到 Cursor、Windsurf、Bolt 等 AI 编程工具中,自动生成相应的代码。 本文不做此部分介绍 3.调整和完善:根据生成的代码进行调整和完善,添加交互功能和动态效果。 本文不做此部分介绍 当前优缺点 优点: 提高(ai)开发效率:通过自动生成编码提示词,大大减少写 prompt 的工作量。 简化设计到代码的转换:帮助开发者快速将设计图转化为可运行的代码。 缺点: 目前单次图像上传限制:目前仅支持一次上传一个图像。 技术栈限制,如 Vue 场景需要改造 prompt 未来展望 CopyCoder 作为一款 AI 编程辅助工具,未来的发展方向可能包括: 拓展技术栈、图片数量等限制 增强图像识别能力:提高对复杂设计图的识别和分析能力,生成更精确的编码提示词。 扩展功能范围:增加对更多编程语言和框架的支持,满足不同开发需求。 集成更多开发工具:与更多的开发工具和平台进行集成,提供更全面的开发解决方案。 提升用户体验:优化用户界面和操作流程,使工具更加易用和友好。 但是个人认为,CopyCoder 只是代码生成的前置环节,这部分能力很容易被 Cursor、Bolt 这些平台工具吸收借鉴,所以后续被替代的可能性很大,或者与这些工具平台合作,降低成本进行无缝对接。 相关链接 https://copycoder.ai/ https://mp.weixin.qq.com/s/qtTBr38ydC2Jt2A1E8sAdw https://ai-bot.cn/copycoder/

2025/1/5
articleCard.readMore

【AI】【笔记】MCP 协议:连接 AI 模型与外部世界的桥梁

MCP 协议:连接 AI 模型与外部世界的桥梁 背景 随着 AI 技术的飞速发展,大语言模型(LLM)在推理和生成质量上取得了巨大进步。然而,这些模型在实际应用中常常受限于数据孤岛和遗留系统,无法充分发挥潜力。为了解决这一问题,Anthropic 公司于 2024 年 11 月推出了模型上下文协议(MCP,Model Context Protocol),旨在通过统一的客户端-服务器架构,统一大型语言模型与外部数据源和工具之间的通信协议,解决 LLM 应用与数据源连接的难题。 MCP 可以被视为 AI 应用的“USB-C 接口”,它提供了一种标准化的方式,将 AI 模型与各种数据源和工具无缝连接。MCP 使得 AI 应用能够安全地访问和操作本地及远程数据,为 AI 应用提供了连接万物的接口。 能力 MCP 协议的核心思想是通过上下文管理来优化模型的交互过程。上下文管理包括上下文的存储、更新、传递和删除等操作。通过有效的上下文管理,模型可以在多轮对话中保持对历史信息的记忆,从而更好地理解用户的意图和需求。MCP 的核心能力还体现在以下几个方面: 数据集成:连接 AI 助手与各种数据源,包括本地和远程资源,如文件、数据库、API 等。 工具集成:集成 API 和其他工具,您的 AI 助手可以直接与 Git 交互、运行测试、管理问题等等,让 AI 系统能够执行更复杂的操作。 模板化交互:基于提示(Prompts)提供模板化的交互方式,方便用户快速构建特定任务的交互流程。 安全性:内置安全机制(MCP 服务器隔离凭据和敏感数据,交互需要显式的用户批准(除非对某些 MCP 工具启用自动批准)),保护数据和 API 密钥不被泄露,确保数据访问既可控又可审计。 开发者支持:提供 SDK 和文档,支持开发者构建和测试 MCP 连接器。 预构建服务器:提供预构建的 MCP 服务器,快速集成流行企业系统。 上下文维护:在不同工具和数据集之间保持上下文,而不是每次都重新开始,MCP 服务器可以跨会话维护知识,创建一个真正的“项目内存”,实现更智能的任务处理。 MCP 支持通过同一协议访问本地资源(如数据库、文件)和远程资源(如 Slack、GitHub API),无需定制集成。MCP 不仅共享数据,还可公开工具和交互模板,且内置安全性,确保资源由服务器完全掌控。目前 MCP 支持本地运行,未来将引入企业级认证的远程支持,实现团队间的安全共享。通过 Claude 桌面应用,开发者可在短时间内集成 MCP,快速连接多种数据源,推动 AI 集成的标准化发展。 使用 MCP 官方文档写得挺细致的,关于使用这块也建议看一下官方文档说明 MCP 协议遵循客户端-服务器架构,规范及 SDK: 官网:https://modelcontextprotocol.io GitHub:https://github.com/modelcontextprotocol 核心架构: MCP 包含以下几个核心概念: MCP 主机(Hosts):发起请求的 LLM 应用程序,如 Claude Desktop、IDE 或 AI 工具。 MCP 客户端(Clients):在主机程序内部,与 MCP 服务器保持 1:1 的连接。 MCP 服务器(Servers):为 MCP 客户端提供上下文、工具和提示信息。 本地资源(Local Resources):本地计算机中可供 MCP 服务器安全访问的资源。 远程资源(Remote Resources):MCP 服务器可以连接到的远程资源,如通过 API 访问的网络资源。 MCP 定义了两种通信机制: 本地通信:使用标准输入输出(stdio)传输数据,客户端启动服务器程序作为子进程,通过 stdin/stdout 进行消息通讯,消息格式为 JSON-RPC 2.0。 远程通信:客户端与服务器可以部署在任何地方,通过基于 SSE 的 HTTP 通信,消息格式同样为 JSON-RPC 2.0。 快速开始 目前 MCP 有三种方式可以帮助你快速开始,Python 或 TypeScript 选一个自己比较熟悉的构建服务即可。 快速入门(MCP Quickstart):不到 5 分钟即可开始使用 MCP,可在 Claude 桌面应用和本地服务之间建立安全连接(以上的 “lencx 演示” 就是基于该部分文档实现)。 构建第一个 Python 服务 (MCP Python):15 分钟内用 Python 创建一个简单的 MCP 服务器。 构建第一个 TypeScript 服务(MCP TypeScript):15 分钟内用 TypeScript 创建一个简单的 MCP 服务器。 开发工具 开发 MCP 服务器或将其与应用程序集成时,有效的调试至关重要。所以 MCP 提供了几种不同层次的调试工具: MCP 检查器(MCP Inspector):交互式调试界面;直接服务器测试 Claude 桌面开发工具(Claude Desktop Developer Tools):集成测试;日志收集;Chrome DevTools 集成 服务器日志(Server Logging):自定义日志记录实现;错误追踪;性能监控 示例 以下是一个极简单的 MCP 协议使用示例: 安装预构建的 MCP 服务器:通过 Claude Desktop 应用程序安装预构建的 MCP 服务器。 编写 Server 端代码:根据 MCP 协议定义,创建一个 MCP 服务器,提供资源、工具或提示词。 编写 Client 端代码:创建一个 MCP 客户端,与服务器建立连接,并请求使用服务器提供的资源或工具。 以下是一个使用 TypeScript 实现的简单 MCP 协议示例,展示了如何创建一个 MCP 服务器和客户端,并通过它们进行通信。 环境要求: Node.js (v18+) Python (v3.8+) 1. 创建 MCP 服务器 首先,安装必要的依赖项: 1 npm install @modelcontextprotocol/sdk 然后,创建一个简单的 MCP 服务器,该服务器提供一个工具,用于计算两个数字的和: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // server.ts import { Server, StdioServerTransport } from '@modelcontextprotocol/sdk/server/index.js'; import { CallToolRequestSchema, ListToolsRequestSchema, McpError, ErrorCode, } from '@modelcontextprotocol/sdk/types.js'; const server = new Server( { name: 'mcp-server', version: '1.0.0', }, { capabilities: { tools: {}, }, } ); // 列出可用工具 server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: 'calculate_sum', description: 'Add two numbers together', inputSchema: { type: 'object', properties: { a: { type: 'number' }, b: { type: 'number' }, }, required: ['a', 'b'], }, }, ], }; }); // 处理工具调用 server.setRequestHandler(CallToolRequestSchema, async request => { if (request.params.name === 'calculate_sum') { const { a, b } = request.params.arguments; return { toolResult: a + b }; } throw new McpError(ErrorCode.ToolNotFound, 'Tool not found'); }); const transport = new StdioServerTransport(); await server.connect(transport); 2. 创建 MCP 客户端 接下来,创建一个 MCP 客户端,用于调用服务器提供的工具: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 // client.ts import { Client, StdioClientTransport } from '@modelcontextprotocol/sdk/client/index.js'; import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'; const transport = new StdioClientTransport({ command: 'node', args: ['server.js'], // 确保服务器脚本路径正确 }); const client = new Client( { name: 'mcp-client', version: '1.0.0', }, { capabilities: { tools: {}, }, } ); await client.connect(transport); // 列出工具 const tools = await client.request({ method: 'tools/list' }, ListToolsRequestSchema); console.log('Available Tools:', tools); // 调用工具 const result = await client.request( { method: 'tools/call', params: { name: 'calculate_sum', arguments: { a: 5, b: 3 }, }, }, CallToolRequestSchema ); console.log('Tool Result:', result); 3. 运行示例 启动服务器:运行node server.js启动 MCP 服务器。 启动客户端:运行node client.js启动 MCP 客户端。 观察输出:客户端会列出可用工具,并调用calculate_sum工具,输出结果。 4. 集成到Claude Desktop 如果需要将 MCP 服务器集成到Claude Desktop,可以在claude_desktop_config.json中添加服务器配置: 1 2 3 4 5 6 7 8 { "mcpServers": { "mcp-server": { "command": "node", "args": ["/path/to/your/mcp-server/build/index.js"] } } } 应用 工具平台结合 如 Cline 的结合: 社区插件应用 如: mcp-rtfm:智能文档获取 mcp-postman:API 测试 mcp-playwright:浏览器自动化 sqlite-explorer-fastmcp:数据库分析 mcp-rest-api:REST API 测试 总结 MCP 协议为 AI 模型与外部数据源和工具的集成提供了一种标准化、安全且灵活的解决方案。通过客户端-服务器架构和 JSON-RPC 2.0 通信机制,MCP 能够实现本地和远程资源的无缝访问。随着越来越多的应用接入 MCP 协议,未来有望构建一个更加互联、高效的 AI 生态系统。 相关链接 MCP 官网:https://modelcontextprotocol.io MCP GitHub:https://github.com/modelcontextprotocol https://mp.weixin.qq.com/s/ASmcjW53HKokdYt1m-xyXA https://cline.bot/blog/the-developers-guide-to-mcp-from-basics-to-advanced-workflows https://docs.cline.bot/mcp-servers/mcp?ref=cline.ghost.io

2025/1/5
articleCard.readMore

【笔记】React 组件性能分析工具——ReactScan

React 组件性能分析工具——React Scan 为什么会产生React Scan这个分析工具? 我们知道,React 的性能优化有很多细节,以至于性能优化工作要做好会很琐碎且繁重。例如我们需要观测组件的封装力度、memo 的使用情况、hook/组件内的函数及数据定义、props 传参处理以及状态管理机制的设计等等等。 React Scan 团队将此关键原因归结于:The issue is that component props are compared by reference, not value. This is intentional – this way rendering can be cheap to run.,即“组件props是通过引用而不是值进行比较的”,React 的这个设计在带来了灵活性/实现简单的优势外,随之带来了容易导致不必要的渲染,使应用程序变慢,从而也使 React 性能问题分析具有较高的成本。 例如这个例子,onClick 函数和样式对象会在每次渲染时都要重新创建,这会导致组件拖慢应用的渲染速度: 1 <ExpensiveComponent onClick={() => alert('hi')} style={{ color: 'purple' }} /> React Scan 作为分析工具,目的就是降低 React 性能优化的分析成本。 介绍 React Scan 是一款开源的用于检测 React 应用渲染问题的工具,能自动检测和突出显示导致性能问题的渲染来帮助您识别这些问题,由 Aiden Bai 率先创建。它能够快速识别并报告潜在的性能瓶颈,帮助开发者优化应用性能。与传统的性能分析工具不同,React Scan 提供了一个简单的即插即用解决方案,可以通过脚本标签或 npm 包添加,以自动分析渲染性能,只需简单几步即可集成。 自动渲染问题检测:React Scan 扫描您的 React 应用,查找可能导致性能问题的渲染问题。 简单易用:它是一个轻量级的 JavaScript 库,您可以通过 script 标签或 npm 等方式轻松集成到您的项目中。 快速集成:在任何其他脚本运行之前添加 React Scan 脚本,确保其能够准确地捕获渲染信息。 React Scan 通过其高效的渲染问题扫描功能,显著提升了 React 应用的性能和稳定性。它简化了开发流程,减少了调试时间,让开发者能够专注于核心业务逻辑。选择 React Scan,意味着您将获得一个更稳定、更高效的 React 应用,并显著提升开发效率。 使用 安装 npm 安装: 1 npm i react-scan -D script 引入 js: 1 <script src="https://unpkg.com/react-scan/dist/auto.global.js"></script> 官方提供的地址有时候会不太稳定,建议单独保存部署一份 API scan(options: Options)注册并启动分析工具 在引入react之前进行注册,如 1 2 3 4 5 6 7 8 9 import { scan } from 'react-scan'; // import this BEFORE react import React from 'react'; if (typeof window !== 'undefined') { scan({ enabled: true, log: true, // logs render info to console (default: false) }); } 1 2 3 4 5 6 7 8 9 10 11 12 scan({ enabled: true, // 启用扫描 includeChildren: true, // 包含子组件 playSound: true, // 声音提示 log: false, // 控制台日志 showToolbar: true, // 显示工具栏 renderCountThreshold: 0, report: false, onCommitStart: () => {}, onRender: (fiber, render) => {}, onCommitFinish: () => {}, }); useScan(options: Options)hook 的方式进行注册并启动分析工具 参数同scan() withScan(Component, options: Options)设定组件扫描 可将特定组件列入白名单,不扫描其他组件 1 2 3 4 5 withScan(Component, { enabled: true, log: true, // ...其他配置项 }); getReport()获取性能报告 1 2 3 4 5 6 scan({ report: true }); const report = getReport(); for (const component in report) { const { count, time } = report[component]; console.log(`${component}渲染${count}次,耗时${time}ms`); } setOptions(options: Options)/getOptions()设置/获取配置项 getRenderInfo(Component)获取指定组件渲染信息 使用效果 工具注册成功后,界面上会出现 React Scan 的工具栏,如: 工具栏默认会出现在界面右上角,我们也可以拖拽到界面其他地方 工具栏从左到右依次为: 选择组件分析 大概率与getRenderInfo()有关,后续有待分析源码 开启/关闭实时分析 大概率控制scan(),后续有待分析源码 开启/关闭声音 个人认为没啥用、提供情绪价值的功能 “react-scan”用来拖拽异动工具栏 工具使用也很简单,在实时分析打开的时候,我们操作界面就可以观察到各视图组件的渲染更新情况,以此来发现不必要的渲染动作。 如上图所示、不同层级之间的渲染更新通过颜色来区分。总体而言,个人感觉在中大型项目中还是很直观的。 *Monitoring监控能力 官方提供的 demo https://dashboard.react-scan.com/project/demo *对 React Native 的支持 从评论和官方处理来看,目前 RN 检测会有些问题,不过现阶段来看官网还是积极处理的、且目前反馈用例均已处理: https://github.com/aidenybai/react-scan/pull/23 原理 React Scan 工作原理主要是通过监控 React 的协调过程。该过程在更新时比较组件的前后快照。当状态或属性发生变化时,React 需要执行 ‘diffing’ 以确定需要重新渲染的内容。React Scan 自动检测这些渲染周期,并通过视觉提示突出显示导致性能问题的组件。它分析组件树,识别由不稳定的属性或低效的更新模式引起的不必要的重新渲染。 其相关代码实现待后续跟进分析。。。 相关链接 https://react-scan.com/

2024/12/8
articleCard.readMore

【笔记】“xx packages are looking for funding”——npm fund命令及运行机制

“xx packages are looking for funding”——npm fund 命令及运行机制 在 Node.js 和 npm 生态系统中,开源项目的持续发展和维护常常依赖于贡献者的支持和资助。为了让开发者更容易了解他们依赖的项目哪些有资金支持选项,npm 在6.13.0版本起引入了 npm fund 命令并默认在npm install安装依赖时触发。本文将详细介绍 npm fund 的作用、运行机制、触发时机、如何避免触发以及相关的副作用和改进建议。 什么是 npm fund 命令? 在日常npm install安装依赖的过程中,我们可能都忽略了 command 最后输出的一些信息,比如本文相关的 funding 信息,如: 1 2 3 packages are looking for funding. Run "npm fund" to find out more. npm fund 命令是在 npm 6.13.0 版本中首次引入的,旨在帮助开发者识别其项目依赖中可以资助的开源包。运行该命令时,npm 会列出所有包含资助选项的包及其相关链接,便于开发者快速访问这些页面并提供支持。 命令起源 在 2019 年 8 月份时,Standard JS 在其开源项目中内置广告的事件引发热议,这些广告通过一个名为 Funding 的 npm 软件包展示在终端,该软件包包含在 Standard 的代码库中。之后 npm 公司宣布将禁止此类终端广告行为。 此事件后,npm 公司表示,它打算在年底前为开源开发人员开发一个众筹平台,于是乎在npm 6.13.0版本上提供了相应支持,这就是npm fund命令的主要由来。 命令作用 显示资助信息:npm fund 会扫描项目中的 node_modules 目录,查找每个包的 package.json 文件中是否包含 funding 字段。它会将有资助选项的包及其资助链接列出。 支持开源生态:通过此功能,npm 提高了对开源项目资助的透明度,鼓励开发者参与到开源项目的资助中,帮助维护者获得资金支持。 使用方法 基本用法非常简单,只需在项目根目录中运行: 1 npm fund 命令将输出形如: 1 2 xx packages are looking for funding run `npm fund` for details 再运行 npm fund,就会显示类似如下的详细信息: 1 package-name https://example.com/donate 如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ├─┬ https://opencollective.com/typescript-eslint │ │ └── @typescript-eslint/eslint-plugin@4.28.5, @typescript-eslint/experimental-utils@4.28.5, @typescript-eslint/types@4.28.5, @typescript-eslint/typescript-estree@4.28.5, @typescript-eslint/visitor-keys@4.28.5, @typescript-eslint/scope-manager@4.28.5, @typescript-eslint/parser@4.28.5 │ └─┬ https://opencollective.com/eslint │ │ └── eslint@6.8.0 │ ├── https://github.com/sponsors/epoberezkin │ │ └── ajv@6.12.6 │ ├── https://github.com/sponsors/sindresorhus │ │ └── globals@12.4.0, import-fresh@3.3.0, strip-json-comments@3.1.1, ansi-escapes@4.3.2, type-fest@0.21.3, figures@3.2.0, onetime@5.1.2, globby@11.0.4 │ ├── https://github.com/sponsors/isaacs │ │ └── glob@7.2.3 │ ├─┬ https://github.com/chalk/chalk?sponsor=1 │ │ │ └── chalk@4.1.2 │ │ └── https://github.com/chalk/ansi-styles?sponsor=1 │ │ └── ansi-styles@4.3.0 │ └── https://github.com/sponsors/ljharb │ └── minimist@1.2.8, is-generator-function@1.0.9, qs@6.11.2, side-channel@1.0.4, call-bind@1.0.2, get-intrinsic@1.1.1, has-symbols@1.0.2, object-inspect@1.11.0 ├── https://github.com/sponsors/RubenVerborgh │ └── follow-redirects@1.15.2 └── https://ko-fi.com/tunnckoCore/commissions └── formidable@1.2.2 npm fund 的运行机制和触发时机 运行机制 依赖扫描:npm fund 会读取 node_modules 中每个依赖包的 package.json 文件,寻找 funding 字段。如果找到了该字段,它会提取并显示相关的资助信息。 字段格式:funding 字段可以是 URL 字符串或更复杂的对象,指向资助页面。例如: 1 2 3 { "funding": "https://example.com/donate" } 或者 1 2 3 4 5 6 { "funding": { "type": "individual", "url": "https://example.com/donate" } } 触发时机 npm install 提示:在安装项目依赖时,如果项目中存在可以资助的包,npm 会显示类似“xx packages are looking for funding”的提示,提醒开发者可以运行 npm fund 查看详细信息。(这也是我们日常主要触发的时机) 显式调用:开发者可以手动运行 npm fund 命令,以查看当前项目中支持资助的所有包和资助链接。 如何避免 npm fund 的触发? 在某些情况下,开发者或企业可能希望在 npm install 过程中避免看到这些资助提示。以下是两种实现方式: 1. 在安装时使用 --no-fund 参数 直接在运行 npm install 时添加 --no-fund 参数: 1 npm install --no-fund 2. 修改 .npmrc 配置文件 在 .npmrc 文件中加入以下配置来永久禁用资助提示: 1 fund=false 此配置可以放在项目的根目录下(项目下的.npmrc文件),仅作用于当前项目;也可以放在用户主目录(~/.npmrc文件),作用于全局。 *可以通过npm config ls -l查看当前项目的npm配置,默认情况下fund配置会被设置为true 禁用 npm fund 的副作用 优点: 简洁输出:禁用 npm fund 提示可以减少 npm install 的输出信息,使终端显示更加清晰。 减少干扰:在企业级项目中,开发者可能更专注于安装过程和依赖的调试,不需要额外的资助提示。 缺点: 支持意识减弱:禁用该提示后,开发者不再会注意到可以资助的依赖,可能错失支持有价值的开源项目的机会。 透明度降低:新加入的团队成员或不熟悉项目的开发者可能不知道项目中有哪些包有资助选项。 开源支持意识降低:从长远来看,减少对资助信息的提示可能会让开发者对支持开源项目的重要性淡化,从而减少对依赖项目的贡献和支持。 npm fund 源码 源码文件:https://github.com/npm/cli/blob/latest/lib/commands/fund.js 以目前(2024-11)的源码内容来看,其源码机制概括来说是先使用 npm 的内部模块库函数来遍历 node_modules 目录,读取 package.json 并检查是否有 funding 字段,最后将所有符合条件的包信息格式化输出到终端。 代码流程总结: 1.读取依赖树:使用 Arborist 加载项目的依赖树。 2.解析资助信息:通过 libnpmfund 的 readTree 方法提取资助信息。 3.输出格式化:根据用户配置输出 JSON 格式或使用 archy 进行可读格式的输出。 4.链接打开:当提供了包名时,openFundingUrl 会尝试在浏览器中打开该包的资助链接。 最后 npm fund 是 npm 引入的一个有用的命令,帮助开发者支持开源项目并维持开源生态的可持续发展。虽然在某些情况下禁用它有其合理性,但在默认情况下保留该提示可以提高团队对开源项目支持的意识。根据项目和团队的实际需求,开发者可以灵活选择是否禁用 npm fund 提示。 相关链接 npm fund npm 6.13.0 npm config——funding What does ‘x packages are looking for funding’ mean when running npm install? npm cli document

2024/11/18
articleCard.readMore

【调研】通过Create.xyz的AIGC能力生产前端页面

通过Create.xyz的AIGC能力生产前端页面 介绍 Create是什么? Turn your words into sites, components, and tools - built with code. Create是一种新的人工智能创意工具,可以让任何人用自然语言进行构建。你可以用它来制作组件、网站、工具和应用程序。只要描述你想要它们的外观和工作方式,Create将用户的描述转化为实际的代码,实现所见即所得的设计理念。 地址:https://www.create.xyz/ 效果图: Create有哪些能力? Create.xyz的核心能力在于其能够理解自然语言描述(prompts),并将其转化为代码,生成静态页面和简单的CRUD页面。以下是其主要特点: 自然语言/图片转代码:用户可以通过描述或上传图片来生成页面。 代码生成:将描述转化为代码,支持组件和API的生成。 多模态支持:支持将图片转换为代码,实现Screenshot to App的功能。 1.结合大模型能力,将描述(prompt)转化为代码 Create turns your descriptions into code, so it looks and work how you want. E.g. “Create a Table to describe user’s info.”, “创建一个股票列表组件” 1.1 生成组件Components Quickly make components to build powerful projects or match your brand E.g. “A pie chart to show the distribution.”, “根据图片信息生成一个列表组件” 1.2 生成接口API Bring your own REST API.Upload your Swagger docs and have Create build you a tool that talks to your own custom APIs. Create的数据生成从结果来看相对简单,目测是在prompt中约束了使用fetch API以及增加了自己数据库的调用信息和表信息(text2sql方式)。另外我们也可以指定要ajax请求某个接口,但需要在描述中解释清楚接口出入参信息。 E.g.”查询用户所有数据”(需要打database标签) 1 2 3 4 5 6 7 8 9 10 fetch('/api/db/tempdata', { method: 'POST', body: JSON.stringify({ query: 'SELECT * FROM `users`' }) }) .then((response) => response.json()) .then((data) => { setUsers(data.result); }); 1.3 (平台能力)托管代码和页面部署能力 产生可直接访问的地址,如https://www.create.xyz/app/4cafb2c9-ba16-4288-984d-9a59ea102eab 2.多模态,将图片转换为代码 Screenshot to app,Drop an image of what you want into your description to build it Create的综合评估 stage2.5的形式(介于低代码到完全aigc之间)。 主要优势是产品形态(工作台)很完备、确实可以在这个工作台通过ai生成+修改完成简单页面的创建,主要问题是生成的组件几乎是“非受控”、“一次性”的、不太能复用(这个问题平台可以通过工程手段解决)。 输入:图片或需求prompt 输出:是代码(React组件+tailwind原子类css)、非DSL 能力实现概括:基于claude/gpt-4等模型生成UI组件/模块的代码 UI能力:支持“原子组件”、“模块”、“应用页面”的代码生成和静态组装 事件交互:仅支持简单事件的配置生成(点击跳转),前端没有状态管理能力 数据处理:默认生成的结果是静态“假”数据,需要在prompt声明调xxx接口才会改为取接口形式(结果需要修改);和大多低码平台一样开放了Database能力、可进行数据的存取(prompt2sql) Create的实现 整体使用下来,Create的生产公式为: 1 Page = Components + Functions + Datas(database) + *Assets → Sites or Apps = Page1 + Page2… Create核心的代码生成能力没有自训练模型,而是使用了Claude Sonnet3.5、gpt4等模型API,因此虽然具体实现是闭源黑盒的、但实现会类似于screenshot-to-code之类的通过区分生成场景、指令要求和控制上下文来把控生成效果。 实现思路: 1.自上而下拆分、渐进明细 自上而下进行需求拆分 根据需求进行prompt拆分、泛化及转换 2.推崇组件生产模式: 组件生产的工程方式能力更强,You can create much more powerful apps if you break your project into components. 推荐prompt不应该太复杂,如果复杂,拆到组件:If it gets too long or complex, you can move things into components to build up. 原子能力(Component、Function、Database)的实现 1.1 Component组件 组件的产物代码为 React + Tailwind CSS 技术栈、遵循 函数式组件 + UI受控组件的 编码模式。 优点:灵活,发挥空间大 问题:比较难受控,生产的组件是“一次性”的、不太能复用(这个问题平台可以通过工程手段解决) E.g. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 function MainComponent({ stockData }) { return ( <div className="bg-white rounded-lg shadow-md p-4"> <div className="flex justify-between mb-2"> <div className="flex space-x-4"> <span className="text-gray-500">个股资金</span> <span className="text-gray-500">板块资金</span> </div> <div className="flex space-x-4 text-gray-500"> <span>今日</span> <span>近5日</span> <span>近20日</span> </div> </div> <table className="w-full"> <thead> <tr className="text-gray-500 text-sm"> <th className="text-left py-2">名称/代码</th> <th className="text-right py-2">主力净流入</th> <th className="text-right py-2">最新</th> <th className="text-right py-2">涨跌幅</th> </tr> </thead> <tbody> {stockData.map((stock, index) => ( <tr key={index} className="border-t border-gray-200"> <td className="py-2"> <div>{stock.name}</div> <div className="text-gray-500 text-sm">{stock.code}</div> </td> <td className="text-right text-red-600">{stock.inflow}</td> <td className="text-right">{stock.price}</td> <td className="text-right text-red-600">{stock.change}</td> </tr> ))} </tbody> </table> </div> ); } function StoryComponent() { const exampleStockData = [ { name: '公司A', code: '000001', inflow: '10亿', price: '20.5', change: '1.2%' }, { name: '公司B', code: '000002', inflow: '5亿', price: '15.3', change: '-0.8%' }, ]; return ( <div> <MainComponent stockData={exampleStockData} /> </div> ); } 对应解析后的prompt: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Background color: White Border: Rounded corners Shadow: Medium Shadow Padding: Medium Header section Layout: Horizontal distribution with two sections Left Section: Contains two labels "个股资金" and "板块资金" in gray text Right Section: Contains three labels "今日", "近5日", "近20日" in gray text Table Full width Header: Text color: Gray Text size: Small Column titles: 左对齐:名称/代码, 右对齐:主力净流入, 最新, 涨跌幅 Rows: Border-top: Light gray Name column: Stock name in default text Stock code in gray, small text Inflow and Change columns: Right-aligned, red text Price column: Right-aligned default text 底层prompt感觉可以参考screenshot-to-code的prompt: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 """ You are an expert React/Tailwind developer You take screenshots of a reference web page from the user, and then build single page apps using React and Tailwind CSS. You might also be given a screenshot(The second image) of a web page that you have already built, and asked to update it to look more like the reference image(The first image). - Make sure the app looks exactly like the screenshot. - Pay close attention to background color, text color, font size, font family, padding, margin, border, etc. Match the colors and sizes exactly. - Use the exact text from the screenshot. - Do not add comments in the code such as "<!-- Add other navigation links as needed -->" and "<!-- ... other news items ... -->" in place of writing the full code. WRITE THE FULL CODE. - Repeat elements as needed to match the screenshot. For example, if there are 15 items, the code should have 15 items. DO NOT LEAVE comments like "<!-- Repeat for each news item -->" or bad things will happen. - For images, use placeholder images from https://placehold.co and include a detailed description of the image in the alt text so that an image generation AI can generate the image later. In terms of libraries, - Use these script to include React so that it can run on a standalone page: <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.js"></script> - Use this script to include Tailwind: <script src="https://cdn.tailwindcss.com"></script> - You can use Google Fonts - Font Awesome for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link> Return only the full code in <html></html> tags. Do not include markdown "```" or "```html" at the start or end. """ 1.2 Database数据 这部分处理相对简单,fetch API + REST api + Text2Sql 模式 代码如: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 React.useEffect(() => { fetch('/api/db/tempdata', { method: 'POST', body: JSON.stringify({ query: 'SELECT * FROM `users`' }) }) .then(response => response.json()) .then(data => { setUsers(data.result); }); }, []); const addUser = (name, score) => { fetch('/api/db/tempdata', { method: 'POST', body: JSON.stringify({ query: "INSERT INTO `users` (`name`, `score`) VALUES (?, ?)", values: [name, score] }) }) .then(() => { setUsers([...users, { id: Date.now(), name, score }]); }); }; const deleteUser = (userId) => { fetch('/api/db/tempdata', { method: 'POST', body: JSON.stringify({ query: "DELETE FROM `users` WHERE `id` = ?", values: [userId] }) }) .then(() => { setUsers(users.filter(user => user.id !== userId)); }); }; const updateUser = (userId, name, score) => { fetch('/api/db/tempdata', { method: 'POST', body: JSON.stringify({ query: "UPDATE `users` SET `name` = ?, `score` = ? WHERE `id` = ?", values: [name, score, userId] }) }) .then(() => { setUsers(users.map(user => user.id === userId ? { ...user, name, score } : user)); }); }; 对应prompt: 操作请求: 1.3 Function逻辑处理/工具方法 自然语言说明规则,通过模型生成对应的处理函数代码 代码如: 1 2 3 4 5 6 7 8 function handler({ score }) { if (score > 60) { return { result: 'passed' }; } else { return { result: 'not passed' }; } } 对应prompt: 2.原子能力的组合——核心功能(菜单) 3.需求分析能力 分析图片/prompt意图,并将简单的需求描述转为详细的、可用于开发实现的prompt 模型:Claude、GPT4、Gemini、Groq… 相关链接 create.xyz screenshot-to-code

2024/9/28
articleCard.readMore

【工具】颜色色值处理库colorjs

颜色色值处理库Color.js 在前端开发中,处理颜色是一个常见且关键的任务。无论是在设计用户界面、创建数据可视化还是实现动态效果时,颜色都扮演着重要的角色。color.js 是一个由 Qix- 维护的 JavaScript 库,它提供了一套强大且灵活的工具来处理颜色的转换和操作。这个库在 GitHub 上的地址是:https://github.com/Qix-/color。 还有一个功能更为全面专业的库(https://colorjs.io/,由 CSS Color 规范的编辑者 Lea Verou 和 Chris Lilley 创建,并由一个小型的维护团队继续开发)、但日常大多场景不太用得到,本文不作更多介绍。 特点 轻量级:库的体积小(产物压缩+gzip后2.3k),加载速度快,对性能的影响微乎其微。 多种颜色空间支持:支持 RGB、HSL、HSV、CMYK 等多种颜色空间。 链式调用:支持链式操作,使得颜色转换和操作更加流畅。 扩展性:可以通过插件或自定义函数来扩展库的功能。 兼容性:兼容现代浏览器和 Node.js 环境。 安装和使用 安装 通过 npm 安装 1 npm install color 或者在浏览器中直接引入: 1 <script src="https://cdn.jsdelivr.net/npm/color@latest/color.min.js"></script> 使用 color.js 提供了一个简单的 API 来创建和操作颜色对象。 创建颜色对象 你可以使用多种方式来创建颜色对象: 1 2 3 4 5 6 7 8 9 10 11 // 通过颜色名 const color = color('blue'); // 通过十六进制 const color = color('#39f'); // 通过 RGB 数组 const color = color.rgb(255, 255, 255); // 或 const color = color.rgb([255, 100, 100]); // 通过 RGBA 对象 const color = color({r: 255, g: 100, b: 100, a: 0.5}); color.js 允许你设置颜色的各个通道值,包括 alpha、red、green、blue、hue、saturationl (hsl)、saturationv (hsv)、lightness、whiteness、blackness、cyan、magenta、yellow、black 等。 获取颜色值 获取颜色对象 1 2 3 4 5 // 获取颜色对象的哈希值 color.object(); // {r: 255, g: 255, b: 255} // 获取颜色对象的数组表示 color.rgb().array() // [255, 255, 255] 获取 RGB 数值 1 2 // 获取颜色的 RGB 数值 color.rgbNumber() // 16777215 (0xffffff) 获取十六进制值 1 2 3 4 5 // 获取颜色的十六进制值 color.hex() // #ffffff // 获取颜色的 RGBA 十六进制值 color.hexa() // #ffffffff 获取单个通道值 1 2 // 获取颜色的红色通道值 color.red() // 255 CSS 字符串表示 1 2 3 4 5 // 获取颜色的 HSL 字符串表示 color.hsl().string() // 'hsl(320, 50%, 100%)' // 调用 .string() 方法并指定小数位数 color.hsl().string(2) // 'hsl(320.00, 50.00%, 100.00%)' 颜色转换 color.js 支持在不同颜色空间之间转换: 1 2 3 4 5 6 7 8 // 转换为 HSL 格式 const hsl = color.hsl().toString(); // 转换为 HSV 格式 const hsv = color.hsv().toString(); // 转换为 CMYK 格式 const cmyk = color.cmyk().toString(); 颜色操作 你可以对颜色对象进行各种操作,如调整亮度、饱和度、色调等: 1 2 3 4 5 6 7 8 // 增加亮度 const lighter = color.lighten(1); // 增加饱和度 const moreSaturated = color.saturate(1); // 旋转色调 const rotated = color.rotate(90); 颜色比较和辅助获取 1 2 3 4 5 6 7 8 9 10 11 const color1 = color('red'); const color2 = color('blue'); // 比较两个颜色是否相等 const isEqual = color1.equals(color2); // 返回 false // 获取颜色的亮度值 const brightness = color1.brightness(); // 返回一个介于 0 到 255 之间的值 // 获取颜色的对比度比(与黑色或白色的对比度) const contrast = color1.contrast(color2); // 返回一个介于 0 到 1 之间的值 颜色明暗判断 1 2 3 4 5 // 判断颜色是否为“亮色” color.isLight(); // true // 判断颜色是否为“暗色” color.isDark(); // false 颜色距离和差异获取 1 2 3 4 5 const color1 = color('red'); const color2 = color('green'); // 计算两个颜色在 RGB 空间中的差异 const delta = color1.deltaE(color2); // 返回一个 DeltaE 值 颜色混合 color.js 还允许你混合两种颜色: 1 const mixed = color.mix('red', 0.5); 应用场景 color.js 的应用场景非常广泛,以下是一些典型的用例: 动态主题切换 在需要根据用户偏好或时间(如白天/夜间模式)动态切换主题颜色的应用中,color.js 可以帮助你轻松调整颜色的亮度和对比度,以适应不同的主题。 数据可视化 在数据可视化项目中,color.js 可以帮助你创建颜色渐变,以表示数据的变化趋势或不同类别的数据。 图像处理 在图像处理应用中,color.js 可以用于分析图像中的颜色分布,提取主要颜色,或者根据图像内容自动生成配色方案。 无障碍性检查 color.js 可以帮助开发者检查颜色组合是否符合无障碍性标准,如 WCAG 对比度要求,确保网站对所有用户都友好。 结论 color.js 是一个功能强大、灵活且易于使用的颜色处理库。它为前端开发者提供了一套完整的工具来处理颜色的转换、操作和动态调整,使得在各种项目中实现复杂的颜色需求变得简单。无论是在网页设计、数据可视化还是用户界面开发中,color.js 都是一个值得信赖的选择。

2024/8/31
articleCard.readMore