- AI Agent
- 代码智能体
- 人工智能
- 大模型
- CLI
【免费下载链接】kimi-code
Kimi Code CLI — The Starting Point for Next-Gen Agents
Kimi Code(仓库路径gh_mirrors/ki/kimi-code)内置了/init斜杠指令,用于让 Agent 分析当前代码库并自动生成AGENTS.md。本文以该功能的核心提示词模板 init.md 为主线,结合其上层服务、上下文加载逻辑与测试用例,完整还原这一能力的设计意图、触发链路与落地细节。读完本文,你将理解/init从"派生子 Agent"到"回填 AGENTS.md"的完整机制,并掌握在实际项目中使用与验证该功能的方法。
一、init.md 是什么:一份写给 Agent 的任务说明书
在 Kimi Code 的源码中,init.md 并不是给人阅读的开发文档,而是一份系统提示词模板(prompt template)——它是/init指令运行时注入给 Agent 的核心指令文本,通过构建工具以?raw方式被原样加载为字符串。
该提示词全文如下(共 18 行,实际运行时逐字注入):
You are a software engineering expert with many years of programming experience. Please explore the current project directory to understand the project's architecture and main details. Task requirements: 1. Analyze the project structure and identify key configuration files (such as pyproject.toml, package.json, Cargo.toml, etc.). 2. Understand the project's technology stack, build process and runtime architecture. 3. Identify how the code is organized and main module divisions. 4. Discover project-specific development conventions, testing strategies, and deployment processes. After the exploration, do a thorough summary of your findings and write it to the `AGENTS.md` file in the project root, replacing the file's previous content. If the file already exists, read it first and carry forward whatever is still accurate — the result should be one coherent, up-to-date file, not an append. For your information, `AGENTS.md` is a file intended to be read by AI coding agents. Expect the reader of this file to know nothing about the project. You should compose this file according to the actual project content. Do not make any assumptions or generalizations. Ensure the information is accurate and useful. You must use the natural language that is mainly used in the project's comments and documentation. Popular sections that people usually write in `AGENTS.md` are: - Project overview - Build and test commands - Code style guidelines - Testing instructions - Security considerations从这份提示词可以看出它的设计要点:
- 角色设定:Agent 被赋予"多年经验的软件工程专家"身份,任务是先"探索"再"总结",而不是凭空生成;
- 四个探索维度:项目结构、关键技术配置文件(
pyproject.toml、package.json、Cargo.toml等)、技术栈与构建/运行时架构、代码组织与模块划分、项目特有的开发约定/测试策略/部署流程; - 写入规则:结果必须写入项目根目录的
AGENTS.md;若文件已存在,必须先读取,并保留仍然准确的内容,整体重写为一份连贯的最新文件,而不是追加; - 读者定位:明确
AGENTS.md的读者是"对项目一无所知的 AI 编码 Agent",因此要求内容准确、有用、基于实际项目,不得臆测或泛化,且必须使用项目注释与文档中使用的主要自然语言(即"项目语言优先"); - 推荐章节:给出了常见的
AGENTS.md章节骨架(项目概览、构建与测试命令、代码风格、测试说明、安全考量)。
二、提示词在源码中的挂载点:profile/init.ts
packages/agent-core-v2/src/features/sessionInit/profile/init.ts 是整个 sessionInit 功能的"提示词仓库":
import initMd from './init.md?raw'; export const DEFAULT_INIT_PROMPT = initMd; export function initCompletionReminder(agentsMd: string): string { const latest = agentsMd.trim().length === 0 ? 'No AGENTS.md content was found after `/init` completed.' : agentsMd; return [ 'The user just ran `/init` slash command.', 'The system has analyzed the codebase and generated an `AGENTS.md` file.', '', 'Latest AGENTS.md file content:', latest, ].join('\n'); }这里有两个关键导出:
DEFAULT_INIT_PROMPT:即 init.md 的原样内容,作为/init运行时派生子 Agent 的提示词;initCompletionReminder(agentsMd):在/init完成后构造一条"完成提醒",通知主 Agent"用户刚刚执行了/init、系统已生成AGENTS.md",并把最新文件内容附上;若生成的AGENTS.md为空,则提醒内容会替换为No AGENTS.md content was found after \/init` completed.`,避免空内容误导后续对话。
该文件通过 packages/agent-core-v2/src/index.ts 的export * from '#/features/sessionInit/profile/init';对外导出,是整个功能对外的公共 API 之一。
三、/init的完整触发链路:SessionInitService 做了什么
在用户侧,/init是一个会话级斜杠指令,官方文档 docs/zh/reference/slash-commands.md 的说明为"分析当前代码库并生成AGENTS.md"。指令背后的核心实现位于 packages/agent-core-v2/src/features/sessionInit/sessionInitService.ts,其generateAgentsMd()方法(第 44 行起)完整串联了以下步骤:
const INIT_PROFILE_NAME = 'coder'; const INIT_PARENT_TOOL_CALL_ID = 'generate-agents-md'; const INIT_DESCRIPTION = 'Initialize AGENTS.md'; const INIT_LABELS: Readonly<Record<string, string>> = { sessionInit: 'agents-md' };- 获取主 Agent:通过
agentLifecycle.handleOf(MAIN_AGENT_ID)拿到主 Agent,若不存在则抛出AGENT_NOT_FOUND; - 校验模型绑定:读取主 Agent 的 profile 数据,若
modelAlias === undefined,抛出SESSION_INIT_FAILED('Main agent has no model bound'),即主 Agent 未绑定模型时/init无法运行; - 创建子 Agent:以
coderprofile 为模板创建子 Agent,绑定主 Agent 的modelAlias与thinkingLevel,并打上{ sessionInit: 'agents-md' }标签;同时把主 Agent 当前的权限模式(permission mode)同步给子 Agent; - 派发 spawn 事件:通过
emitAgentRunSpawned广播subagent.spawned事件,parentToolCallId为generate-agents-md; - 运行子 Agent:调用
subagents.run,请求类型为{ kind: 'prompt', prompt: DEFAULT_INIT_PROMPT }——init.md 正是在这里作为提示词被注入;同时通过mirrorAgentRun把子 Agent 的运行镜像到主 Agent 的会话中,让用户可以实时看到探索过程; - 取消支持:整个流程受
AbortController控制,cancelInit()(第 40-42 行)可随时中止进行中的初始化,且用户取消会以UserCancellationError原样向上传播、不会被包装成失败(测试第 234-253 行专门验证了这一点); - 重新加载 AGENTS.md:子 Agent 运行结束后,调用
loadAgentsMdDetailed从当前工作目录重新读取AGENTS.md; - 回填与提醒:通过
IAgentAgentsMdReminderService.seedInjected(agentsMdPaths, cwd)把生成的AGENTS.md路径注入主 Agent 的提醒状态,再通过IAgentReminderService.notify(initCompletionReminder(agentsMd), { variant: 'init' })发送完成提醒; - 冲刷事件:
await main.accessor.get(IEventDispatcher).flush()确保所有事件在返回前落库/广播。
错误处理(第 102-113 行)值得一提:用户取消(isUserCancellation/isAbortError)与已知的SESSION_INIT_FAILED直接透传;其余任何子 Agent 失败都会被包装为ErrorCodes.SESSION_INIT_FAILED并保留原始错误消息作为 cause。
服务注册与接口契约
- packages/agent-core-v2/src/features/sessionInit/sessionInitFeature.ts 将
SessionInitService注册为LifecycleScope.Session作用域的会话级服务(Feature.name = 'sessionInit'); - packages/agent-core-v2/src/features/sessionInit/sessionInit.ts 定义了
ISessionInitService接口,仅暴露两个方法:generateAgentsMd(): Promise<void>与cancelInit(): void——这恰好对应/init的"执行"与"中断"两种交互。
四、AGENTS.md 的读取规则:它会被放在哪里
子 Agent 完成任务后,系统通过 packages/agent-core-v2/src/agent/profile/context.ts 中的loadAgentsMdDetailed(第 65-71 行)重新定位AGENTS.md。该文件定义了几个重要的查找规则:
- 候选文件名(第 79-87 行):
AGENTS_MD_PLAIN_NAMES = ['AGENTS.md', 'agents.md'],此外每个目录下还会优先检查.kimi-code/AGENTS.md(dotKimiAgentsMdPath返回join(dir, '.kimi-code', 'AGENTS.md')),最终候选路径依次为.kimi-code/AGENTS.md、AGENTS.md、agents.md; - 目录搜索方向:从工作目录沿目录树自叶向根(
dirsRootToLeaf)逐层查找,并结合 Git 工作树(findGitWorkTree)定位项目根; - 大小建议(第 8 行):
AGENTS_MD_RECOMMENDED_MAX_BYTES = 32 * 1024,即推荐AGENTS.md不超过 32KB;文档 docs/zh/reference/server-api.md 也确认会话级告警agents-md-oversized正由"AGENTS.md 过大检查"产生; - 系统提示注入:
AGENTS.md内容还会通过<!-- From: <path> -->注释标记被提取进系统提示(第 89-100 行),使主 Agent 在后续对话中始终感知到项目约定。
在数据层面,AGENTS.md还遵循两层约定(见 docs/en/configuration/data-locations.md):项目根目录的AGENTS.md是/init的默认写入目标;$KIMI_CODE_HOME/AGENTS.md(默认~/.kimi-code/AGENTS.md)则存放全局性的 Kimi 专属 Agent 指令。同时 docs/en/configuration/config-files.md 指出,文件系统 watcher 会监听AGENTS.md的变更并热重载(默认开启,可通过watch.enabled = false关闭)。
五、测试如何验证这条链路
packages/agent-core-v2/test/features/sessionInit/sessionInit.test.ts 用一组单元测试锁定了上述全部行为,可以作为阅读源码时的"对照实验":
- 主流程测试(第 158-206 行):模拟
coderprofile 子 Agent 的创建与运行,断言:create的 binding 为{ profile: 'coder', model: 'mock-model', thinking: 'off' },labels 为{ sessionInit: 'agents-md' };- 注入的 prompt 内容包含
'Task requirements:'(即 init.md 的正文片段); - 完成提醒内容包含
'The user just ran \/init` slash command.'与'Latest AGENTS.md file content:',并携带最新AGENTS.md` 内容; seedInjected被以([AGENTS_MD_PATH], WORK_DIR)调用;- 事件序列中依次出现
subagent.spawned→agent.status.updated→subagent.completed;
- 失败包装(第 208-220 行):子 Agent 抛错时,外层错误 code 为
SESSION_INIT_FAILED,且保留原始消息'coder exploded'; - 主 Agent 缺失(第 222-232 行):抛出
AGENT_NOT_FOUND; - 取消语义(第 234-253 行):
cancelInit()中止在途运行,错误类型为UserCancellationError且不会产生subagent.failed事件; - 空转保护(第 255-258 行):无在途初始化时调用
cancelInit()是无害的 no-op。
六、实际使用与二次开发建议
在项目中使用/init:进入项目目录启动 Kimi Code 会话,输入/init即可。系统会自动派生子 Agent 探索代码库并把结果写入项目根目录的AGENTS.md(若存在.kimi-code/AGENTS.md则写入该处)。生成后可立即在对话中看到"已完成初始化"的提醒及文件内容摘要;文件后续变更会被 watcher 热加载,无需重启会话。
理解其边界:/init需要主 Agent 已绑定模型(否则报Main agent has no model bound);生成的AGENTS.md应控制在 32KB 以内,避免触发agents-md-oversized告警;文件语言遵循"项目注释与文档的主要语言"原则,中文项目会得到中文的AGENTS.md。
定制提示词:DEFAULT_INIT_PROMPT是硬编码的默认值,若需在 fork 中调整探索维度(例如增加"API 面盘点"或"性能敏感路径"章节),可在 init.md 基础上扩展提示词文本,再通过?raw导入后替换DEFAULT_INIT_PROMPT的取值;上层generateAgentsMd()对提示词内容无格式依赖,只需保持"探索 → 写入 → 替换式重写"的指令语义即可。
小结
/init之所以能稳定地产出高质量AGENTS.md,关键在于 init.md 这份提示词对"探索目标、写入规则、读者定位、语言要求、章节骨架"做了完整而克制的约束,再由 sessionInitService.ts 以"独立coder子 Agent + 镜像运行 + 结果回填提醒"的架构执行。理解这层机制,既能帮你更准确地预期/init的行为,也能为定制或扩展项目初始化能力提供清晰的切入点——相关实现、测试与文档均已在本仓库可查证。
- AI Agent
- 代码智能体
- 人工智能
- 大模型
- CLI
【免费下载链接】kimi-code
Kimi Code CLI — The Starting Point for Next-Gen Agents
相关推荐
Kimi Code CLI 的 `/init` 命令深度解析:从 init.md 提示词到 AGENTS.md 自动生成机制
Kimi Code CLI 的 /init 命令深度解析:从 init.md 提示词到 AGENTS.md 自动生成机制 本文以仓库内 init.md http
人工智能AI Agent代码智能体交互助手CLI工具调用Open Interpreter 的 /init 命令解析:一条提示词如何自动生成 AGENTS.md 项目指南
Open Interpreter 的 /init 命令解析:一条提示词如何自动生成 AGENTS.md 项目指南 本文解析 Open Interpreter(c
人工智能大模型AI Agent代码智能体AI 应用CLINotepad-- 跨平台文本编辑器:Windows、Linux、macOS 三端完整上手指南
Notepad 跨平台文本编辑器:Windows、Linux、macOS 三端完整上手指南 Notepad 是一款国产跨平台文本编辑器,基于 Scintilla
桌面应用
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考