AI 编程助手的能力边界,正在从「单文件补全」走向「全项目级任务交付」。当任务规模从单个函数扩展到数十个文件的重构、批量代码审查、多模块并行开发时,传统单 Agent 串行执行的瓶颈愈发明显:上下文长度受限、执行效率随任务规模线性下降、长链路下注意力漂移导致任务完成率降低。
Kimi Code 推出的 Swarm 模式,给出了一套「主从式多 Agent 并行」的工程解法:由主 Agent 负责任务拆解与结果汇总,批量派发子 Agent 并行执行细分任务。官方基准数据显示,该模式下端到端执行效率最高可提升 4.5 倍,整体时延降低约 80%。
本文将从源码视角出发,逐层拆解 Swarm 模式的四层架构,深入调度引擎、状态管理、权限体系的实现细节,分析其背后的设计权衡与工程取舍,并给出实际使用中的最佳实践与能力边界。全文关键结论均附带对应源码片段对照。
一、整体架构:四层协同的并行体系
Swarm 模式并非单一模块,而是由四个层级自顶向下协同工作的完整链路,每一层职责单一、边界清晰:
TUI 命令层 (/swarm)
↓
SwarmMode 状态管理 (agent-core)
↓
AgentSwarm 工具 (模型调用)
↓
SubagentBatch 调度引擎
- TUI 命令层 :面向用户的交互入口,处理
/swarm系列指令,负责模式切换与任务发起 - SwarmMode 状态管理:维护 Swarm 模式的生命周期,管理提示词的注入与回收,是整个模式的状态中枢
- AgentSwarm 工具:封装为模型可调用的标准化工具,是主 Agent 派发批量任务的协议层
- SubagentBatch 调度引擎:底层并发调度核心,负责子 Agent 的启动、限流、重试与取消处理
1.1 三种触发模式:不同入口,不同生命周期
Swarm 模式并非只有一种开启方式,而是设计了三种触发源,分别对应不同的使用场景与生命周期,由 SwarmModeTrigger 类型统一定义:
源码对照
typescript
/**
* manual = persistent toggle (/swarm on);
* task = one-shot /swarm prompt;
* tool = AgentSwarm entry.
*/
export type SwarmModeTrigger = 'manual' | 'task' | 'tool';
packages/agent-core/src/agent/swarm/index.ts (L6-11)
| 触发类型 | 入口方式 | 生命周期 | 自动退出 |
|---|---|---|---|
manual |
用户执行 /swarm on / /swarm off |
持久生效,跨轮次保持 | 否,需手动关闭 |
task |
用户执行 /swarm <任务描述> |
仅当前轮次有效 | 是,任务完成后自动退出 |
tool |
模型主动调用 AgentSwarm 工具 |
工具执行期间有效 | 是,工具返回后自动退出 |
通过 shouldAutoExit 属性统一控制自动退出逻辑:
源码对照
typescript
get shouldAutoExit(): boolean {
return this.active === 'task' || this.active === 'tool';
}
packages/agent-core/src/agent/swarm/index.ts (L57-59)
task 和 tool 均为一次性触发,任务结束后自动恢复普通模式,避免影响后续对话的行为模式。
二、核心模块源码深度解析
2.1 SwarmMode 状态机:精细化的提示词生命周期管理
SwarmMode 是整个模式的状态中枢,核心职责是维护开关状态、记录触发来源、管理上下文提示词的注入与回收。它的设计非常细腻,针对不同触发源做了差异化处理,尽可能减少无效上下文对模型的干扰。
进入逻辑:差异化提示词注入
enter() 方法有一个关键的条件分支:只有非 tool 触发时,才会向对话上下文注入 Swarm 工作流提示词。
源码对照
typescript
enter(trigger: SwarmModeTrigger): void {
if (this.active !== null) return;
this.agent.records.logRecord({ type: 'swarm_mode.enter', trigger });
this.active = trigger;
if (trigger !== 'tool') {
this.agent.context.appendSystemReminder(SWARM_MODE_ENTER_REMINDER, {
kind: 'injection',
variant: 'swarm_mode',
});
}
this.agent.emitStatusUpdated();
}
packages/agent-core/src/agent/swarm/index.ts (L18-29)
背后的逻辑非常直观:
manual和task是用户发起的模式切换,模型需要被告知「现在进入了 Swarm 模式,应遵循分解任务、调用 AgentSwarm 的工作流」,因此必须注入工作流提示词进行引导。tool触发意味着模型已经在主动调用并行工具,说明它已经知晓并正在执行 Swarm 工作流,此时再注入提示词属于冗余信息,反而会占用宝贵的上下文窗口。
注入的进入提示词明确了主 Agent 的行为范式:先做少量探索性工作确认任务边界,再拆解为独立子任务,最后通过 AgentSwarm 批量派发,而非自己串行执行。
退出逻辑:优先回收,兜底通知
exit() 方法同样做了分层处理,并且包含一个上下文优化的细节:
源码对照
typescript
exit(): void {
if (this.active === null) return;
this.agent.records.logRecord({ type: 'swarm_mode.exit' });
const trigger = this.active;
this.active = null;
this.agent.emitStatusUpdated();
if (trigger === 'tool') return;
if (this.agent.context.popMatchedMessage((origin) => origin?.kind === 'injection' && origin.variant === 'swarm_mode')) {
return;
}
if (!this.agent.records.restoring) {
this.agent.context.appendSystemReminder(SWARM_MODE_EXIT_REMINDER, {
kind: 'injection',
variant: 'swarm_mode_exit',
});
}
}
packages/agent-core/src/agent/swarm/index.ts (L35-51)
具体规则可以总结为三点:
tool触发的模式直接退出,不注入任何提示词------工具执行完毕后模型自然收到结果,无需额外通知。manual/task触发的模式,优先尝试弹出(pop)进入时注入的提示词,如果成功则不追加退出提醒,从上下文中彻底清除 Swarm 相关指令,避免污染后续对话。- 如果弹出失败(比如中间已经有多轮对话,进入提示词不在栈顶),则追加退出提醒,明确告知模型 Swarm 模式已结束,下一个请求按普通任务处理。
这种「能回收就回收,不能回收再补通知」的设计,在保证模型行为正确的前提下,尽可能减少了无效上下文的累积。
2.2 AgentSwarm 工具:标准化的批量任务协议
AgentSwarm 是模型可直接调用的工具,也是主 Agent 与子 Agent 之间的协议层。它将批量任务抽象为标准化的参数结构,屏蔽了底层调度的复杂性,让主 Agent 只需要关注任务拆分,不需要关心并发控制细节。
参数设计:模板化 + 可恢复
核心参数分为三类,同时覆盖「新建批量任务」和「恢复已有任务」两种场景,由 Zod schema 严格校验:
源码对照
typescript
export const AgentSwarmToolInputSchema = z
.object({
description: z
.string()
.trim()
.min(1)
.describe('Short description for the whole swarm.'),
subagent_type: z
.string()
.trim()
.min(1)
.optional()
.describe('Subagent type used for every spawned subagent. Defaults to coder when omitted.'),
prompt_template: z
.string()
.trim()
.min(1)
.optional()
.describe(`Prompt template for each subagent. The ${PROMPT_TEMPLATE_PLACEHOLDER} placeholder is replaced with each item value.`),
items: z
.array(z.string().trim().min(1))
.max(MAX_AGENT_SWARM_SUBAGENTS)
.optional()
.describe(`Values used to fill ${PROMPT_TEMPLATE_PLACEHOLDER}. Each item launches one new subagent.`),
resume_agent_ids: z
.record(z.string().trim().min(1), z.string().trim().min(1))
.optional()
.describe('Map of existing subagent agent_id to the prompt used to resume that subagent. These resumed subagents are launched before new item-based subagents.'),
})
.strict();
packages/agent-core/src/tools/builtin/collaboration/agent-swarm.ts (L19-56)
参数设计要点:
description:整个 Swarm 任务的简短描述,用于日志与状态展示prompt_template+items:模板 + 数组的批量生成方式,模板中包含{``{item}}占位符,每个 item 对应一个子 Agent,最多支持 128 个resume_agent_ids:基于已有子 Agent ID 恢复执行,用于重试失败任务,优先级高于新建任务
这种模板化的设计有两个明显优势:一是主 Agent 只需关注任务拆分逻辑,不用重复编写相同的指令;二是调度层可以基于模板做去重校验------如果两个 item 填充后生成的 prompt 完全一致,会被直接拒绝,避免无意义的重复劳动。
执行流程与结果格式
工具执行时会先以 tool 触发进入 Swarm 模式,再将 items 展开为具体的任务规格,交给底层调度引擎批量执行:
源码对照
typescript
private async execution(
args: AgentSwarmToolInput,
context: ExecutableToolContext,
): Promise<ExecutableToolResult> {
try {
this.swarmMode.enter('tool');
const result = await this.runSwarm(args, context.signal, context.toolCallId);
return {
output: result,
};
} catch (error) {
return {
output: error instanceof Error ? error.message : String(error),
isError: true,
};
}
}
packages/agent-core/src/tools/builtin/collaboration/agent-swarm.ts (L111-127)
最终返回结构化的 XML 结果,由 renderSwarmResults 函数统一渲染:
源码对照
typescript
function renderSwarmResults(results: readonly SwarmRunResult[]): string {
const completed = results.filter((result) => result.status === 'completed').length;
const failed = results.filter((result) => result.status === 'failed').length;
const aborted = results.filter((result) => result.status === 'aborted').length;
const shouldRenderResumeHint =
results.some((result) => result.status !== 'completed') &&
results.some((result) => result.agentId !== undefined);
const lines = [
'<agent_swarm_result>',
`<summary>${renderSwarmSummary(completed, failed, aborted)}</summary>`,
];
if (shouldRenderResumeHint) {
lines.push(
'<resume_hint>Call AgentSwarm with resume_agent_ids using the agent_id values in this result to continue unfinished work.</resume_hint>',
);
}
for (const result of results) {
const agentId = result.agentId === undefined ? '' : ` agent_id="${result.agentId}"`;
const mode = result.spec.kind === 'resume' ? ' mode="resume"' : '';
const item = result.spec.item === undefined ? '' : ` item="${escapeXmlAttribute(result.spec.item)}"`;
const state = result.state === undefined ? '' : ` state="${result.state}"`;
const body = result.status === 'completed' ? (result.result ?? '') : (result.error ?? 'unknown error');
lines.push(
`<subagent${mode}${agentId}${item}${state} outcome="${result.status}">${body}</subagent>`,
);
}
lines.push('</agent_swarm_result>');
return lines.join('\n');
}
packages/agent-core/src/tools/builtin/collaboration/agent-swarm.ts (L236-267)
生成的结果格式示例:
xml
<agent_swarm_result>
<summary>completed: 2, failed: 1</summary>
<resume_hint>Call AgentSwarm with resume_agent_ids...</resume_hint>
<subagent agent_id="agent-1" item="src/a.ts" outcome="completed">...</subagent>
<subagent agent_id="agent-2" item="src/b.ts" outcome="failed">...</subagent>
</agent_swarm_result>
XML 格式的好处是结构清晰、模型易于解析,同时包含了汇总统计、失败重试提示、每个子 Agent 的详细结果,主 Agent 可以基于结构化结果快速完成汇总。如果存在失败的子 Agent,结果中会附带 <resume_hint>,引导模型通过 resume_agent_ids 进行断点续做。
2.3 SubagentBatch 调度引擎:两阶段自适应并发控制
SubagentBatch 是 Swarm 模式的底层核心,实现了一套兼顾效率与稳定性的两阶段调度算法。它的设计目标非常明确:在不触发模型服务商速率限制的前提下,尽可能提升并发度,缩短整体任务耗时。
调度合约注释完整描述了两阶段的设计规则:
源码对照
/*
Subagent batch scheduling contract:
Normal phase:
- Return results in input order; empty input returns an empty list.
- Start up to 5 tasks immediately, then 1 more every 700 ms while queued work remains. By default active tasks do not cap this ramp; when KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY is set to a positive integer, the ramp additionally stops while active tasks reach that cap, and resumes as tasks complete.
- Launch priority: previous agent id saved after a rate limit, explicit resume, then new spawn.
- Readiness can be reported while the attempt is active. Ready normal launches seed the first rate-limit capacity.
- The first provider rate limit stops the ramp and enters rate-limit phase.
Rate-limit phase:
- A provider rate limit requeues while there is other unfinished work. Save the agent id for same-agent retry, emit suspended, and requeue the task at the front; its own eligibility delays are 3000 ms, 6000 ms, 12000 ms, then doubling.
- If the rate-limited attempt is the only unfinished task, fail that task instead of suspending the whole batch forever.
- Enter with capacity equal to ready normal launches, minimum 1; set the next global launch no earlier than 3000 ms later; then shrink capacity by 1, minimum 1. Later rate limits shrink by 1, minimum 1, at most once per 2000 ms.
- Each pass starts at most 1 task: active attempts must be below capacity, global launch time reached, and task eligibility reached. Choose the first eligible queued task, then set next global launch to now plus the current interval. If blocked by time or queued work remains after a launch, wake at the earlier of next launch/eligibility and next capacity recovery.
- Core recovery rule: in rate-limit phase, if work is queued and no provider rate limit happened for 3 minutes, capacity increases by 1, which can launch one more task immediately. This can happen once per quiet window; a new rate limit restarts the window. If active attempts still fill capacity, wake at the next recovery time.
Results and cancellation:
- Completed, failed, aborted, and timed-out attempts occupy their input slots; when all slots have results, return the ordered list. A task timeout fails only that task and does not enter rate-limit phase or stop others.
- The first task signal is the batch signal. User cancellation preserves existing results, marks ready or agent-known unfinished tasks aborted/started, and marks never-started tasks aborted/not_started. Non-user cancellation rejects.
*/
packages/agent-core/src/session/subagent-batch.ts (L11-30)
对应的核心常量定义:
源码对照
typescript
const INITIAL_LAUNCH_LIMIT = 5;
const INITIAL_LAUNCH_INTERVAL_MS = 700;
const RATE_LIMIT_RETRY_BASE_MS = 3000;
const RATE_LIMIT_RETRY_FACTOR = 2;
const RATE_LIMIT_CAPACITY_SHRINK_INTERVAL_MS = 2000;
const RATE_LIMIT_CAPACITY_RECOVERY_INTERVAL_MS = 3 * 60 * 1000;
const RATE_LIMIT_SUSPENDED_REASON = 'Provider rate limit; subagent requeued for retry.';
const AGENT_SWARM_MAX_CONCURRENCY_ENV = 'KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY';
packages/agent-core/src/session/subagent-batch.ts (L32-40)
正常阶段:渐进式启动策略
正常启动阶段采用「批量首发 + 匀速爬坡」的渐进式策略,而非一次性全量启动,由 scheduleNormalLaunch 实现:
源码对照
typescript
private scheduleNormalLaunch(): void {
while (
this.normalLaunchCount < INITIAL_LAUNCH_LIMIT &&
this.pending.length > 0 &&
!this.rateLimitMode &&
!this.isAtConcurrencyLimit()
) {
this.startAttempt(this.pending.shift()!);
this.normalLaunchCount += 1;
}
if (
this.pending.length === 0 ||
this.rateLimitMode ||
this.normalLaunchTimer !== undefined ||
this.isAtConcurrencyLimit()
) {
return;
}
this.normalLaunchTimer = setTimeout(() => {
this.normalLaunchTimer = undefined;
if (this.finished || this.rateLimitMode || this.pending.length === 0) return;
if (this.isAtConcurrencyLimit()) return;
this.startAttempt(this.pending.shift()!);
this.normalLaunchCount += 1;
this.schedule();
}, INITIAL_LAUNCH_INTERVAL_MS);
}
packages/agent-core/src/session/subagent-batch.ts (L216-244)
启动规则总结:
- 立即启动前 5 个子 Agent(
INITIAL_LAUNCH_LIMIT = 5),快速利用并发能力 - 之后每 700ms 启动 1 个(
INITIAL_LAUNCH_INTERVAL_MS = 700),平缓提升并发量 - 支持通过环境变量
KIMI_CODE_AGENT_SWARM_MAX_CONCURRENCY设置并发上限,达到上限后等待任务完成再启动新任务
源码中的常量没有注释说明具体取值原因,但从调度合约注释可以推断:渐进式启动的核心目的是避免瞬时高并发触发服务商的限流阈值。5 和 700ms 属于工程经验调参值,是在主流模型服务商限流规则下反复验证得出的平衡点。
限速阶段:自适应退避与容量伸缩
一旦遇到服务商限流(rate limit),调度器会自动进入限速阶段,执行自适应降级策略:
- 任务重入队:被限流的任务保留原有 agentId 重新加入队列头部,保证重试时复用同一个 Agent 上下文,避免重复初始化开销
- 指数退避:单任务重试延迟按 3s → 6s → 12s 指数增长,避免持续冲击限流阈值
- 容量收缩:进入限速阶段时,并发容量设为当前已成功启动的数量(最小为 1),之后每次限流再缩减 1,最小保留 1 并发
- 容量恢复:如果 3 分钟内没有新的限流事件,并发容量 +1,逐步恢复并行能力
这套机制的精妙之处在于「自适应」:不需要预先知道服务商的限流阈值,系统会根据实际反馈动态调整并发度,在限流发生时快速降级,在稳定后逐步恢复,在不同模型、不同账号权限下都能稳定运行。
取消处理:精细化状态保留
用户主动取消(按 Esc)时,调度器不会简单地全部丢弃,而是做精细化的状态标记:
源码对照
typescript
private finishWithUserCancellation(): void {
if (this.finished) return;
this.finish(
this.states.map((state) => {
const result = this.results[state.index];
if (result !== undefined) return result;
if (state.started || state.agentId !== undefined) {
return {
task: state.task,
agentId: state.agentId,
status: 'aborted',
state: 'started',
error:
'The user manually interrupted this subagent batch before this subagent finished.',
};
}
return {
task: state.task,
status: 'aborted',
state: 'not_started',
error:
'The user manually interrupted this subagent batch before this subagent was started.',
};
}),
);
}
packages/agent-core/src/session/subagent-batch.ts (L553-581)
状态标记规则:
- 已完成的子 Agent 结果完整保留
- 已启动但未完成的标记为
aborted/started - 尚未启动的标记为
aborted/not_started
这种设计保证了用户中途取消时,已完成的工作不会全部丢失,主 Agent 可以基于部分结果继续处理,大幅提升了交互的容错性。
三、权限策略:两层控制的安全设计
Swarm 模式通过两个独立的权限策略,从不同维度控制 AgentSwarm 工具的调用边界,兼顾使用体验与操作安全。
3.1 Swarm 模式下自动放行
第一个策略是 SwarmModeAgentSwarmApprovePermissionPolicy:只要 Swarm 模式处于激活状态,调用 AgentSwarm 工具自动通过审批。
源码对照
typescript
export class SwarmModeAgentSwarmApprovePermissionPolicy implements PermissionPolicy {
readonly name = 'swarm-mode-agent-swarm-approve';
constructor(private readonly agent: Agent) {}
evaluate(context: PermissionPolicyContext): PermissionPolicyResult | undefined {
if (context.toolCall.name !== 'AgentSwarm') return;
if (!this.agent.swarmMode.isActive) return;
return {
kind: 'approve',
};
}
packages/agent-core/src/agent/permission/policies/swarm-mode-agent-swarm-approve.ts (L4-15)
背后的安全假设很清晰:用户手动开启 Swarm 模式、或输入 /swarm <任务> 的动作,本身就已经表达了「同意启动并行子 Agent」的授权意图,无需重复确认。
但这种放行只限于「启动子 Agent」这个动作本身,子 Agent 内部的工具调用(写文件、执行命令等)依然遵循独立的权限策略链,受全局的 manual/auto/yolo 模式控制。这种「外层放行、内层受控」的分层设计,既保证了批量任务的流畅性,又没有突破底层的安全边界。
3.2 工具独占调用约束
第二个策略是 AgentSwarmExclusiveDenyPermissionPolicy:AgentSwarm 必须是单次响应中的唯一工具调用,不能与其他工具混用,也不能同时调用多次。
源码对照
typescript
export class AgentSwarmExclusiveDenyPermissionPolicy implements PermissionPolicy {
readonly name = 'agent-swarm-exclusive-deny';
evaluate(context: PermissionPolicyContext): PermissionPolicyResult | undefined {
const toolCalls = context.toolCalls;
const agentSwarmCount = toolCalls.filter(
(toolCall) => toolCall.name === 'AgentSwarm',
).length;
if (agentSwarmCount === 0) return;
if (agentSwarmCount === 1 && toolCalls.length === 1) return;
return {
kind: 'deny',
message:
agentSwarmCount > 1
? multipleAgentSwarmDeniedMessage(toolCalls.length > agentSwarmCount)
: mixedAgentSwarmDeniedMessage(),
reason: {
agent_swarm_tool_calls: agentSwarmCount,
tool_calls: toolCalls.length,
},
};
}
}
packages/agent-core/src/agent/permission/policies/agent-swarm-exclusive-deny.ts (L3-27)
拒绝消息明确说明了使用规则:
AgentSwarm must be the only tool call in a model response. Retry with a single AgentSwarm call by itself, then call any other tools after it returns.
这个限制看似不够灵活,实则是保证系统一致性的必要设计。AgentSwarm 是一个阻塞式的批量操作,执行周期远长于普通工具,如果与其他工具并行调用,会出现结果时序交错、上下文状态不一致的问题;同时多个 Swarm 并发会让调度复杂度和限流风险指数级上升。
工程上的取舍很明确:牺牲单次响应的工具组合灵活性,换取批量执行的稳定性与可预测性。需要组合工具时,可以先执行 Swarm,拿到结果后再调用其他工具,通过串行化保证可控。
四、设计权衡:工程落地的现实取舍
源码里能看到参数和逻辑,但看不到背后的决策过程。深入分析 Swarm 模式的实现细节,可以发现多处非常典型的工程取舍------为了落地性、稳定性和可维护性,主动放弃了部分灵活性与理想化能力。
4.1 渐进式启动:并发效率与限流风险的平衡
为什么不一次性全量启动所有子 Agent?本质是效率与稳定性的权衡。
全量并发在理想情况下速度最快,但在实际云服务环境中,瞬时高并发极大概率触发限流,反而会因为重试导致整体耗时更长。渐进式启动相当于用少量的启动延迟,换取更低的限流概率,对于几十上百个子 Agent 的大规模任务,整体收益更高。
同时,环境变量开放并发上限的设计,也给了私有部署、高权限账号场景下的调优空间,用户可以根据自身的限流阈值灵活调整。
4.2 语义级隔离:冲突规避的轻量方案
一个很关键的事实是:Swarm 模式没有任何文件锁或系统级冲突保护机制。
多个子 Agent 对文件的写入冲突、任务范围的重叠,完全依赖主 Agent 的任务拆分能力,以及提示词中的协调规则------要求每个子 Agent 职责清晰、范围不重叠、避免分配冲突的修改任务。代码层面唯一的保护,是禁止完全相同的 prompt 重复创建子 Agent。
这是一个非常典型的工程取舍:如果在系统层实现分布式文件锁、变更冲突检测,复杂度会大幅上升,且子 Agent 的执行效率会显著下降;而通过语义约束 + 任务拆分的方式,把冲突规避的责任交给主 Agent,既保持了调度层的轻量高效,也符合「主 Agent 负责任务编排」的定位。
当然,这也意味着如果任务拆分不当,确实可能出现文件覆盖、重复劳动的问题,这是使用 Swarm 模式时最需要注意的边界。
4.3 提示词精细化管理:上下文成本的极致控制
从 enter/exit 的差异化处理、到 popMatchedMessage 的优先回收机制,可以看出整个设计对上下文 token 开销非常敏感。
Swarm 模式的提示词注入遵循「最小必要」原则:
- 不需要注入的时候坚决不注入(tool 触发)
- 能回收的时候优先回收(同轮次内立即退出)
- 必须通知的时候才追加(跨轮次退出)
这种精细化的管理,对于长对话、多轮 Swarm 任务的场景尤为重要,避免了 Swarm 相关指令在上下文中不断累积,挤占有效工作的 token 空间。
五、使用指南与最佳实践
5.1 适用场景边界
推荐使用的场景:
- 批量代码审查:多个独立文件/模块的代码规范检查、漏洞扫描
- 多文件并行重构:互不依赖的模块统一改造、批量语法迁移
- 并行技术调研:多个技术方案、多个竞品的并行信息检索与分析
- 批量内容生成:多份文档、多个测试用例的并行编写
- 大规模代码库探索:分模块并行梳理代码结构与依赖关系
不推荐使用的场景:
- 强依赖的串行任务:必须先完成 A 才能做 B 的任务,无法并行拆分
- 单文件深度修改:单个文件内的复杂重构,拆分反而会增加合并成本
- 需要全局统一决策的任务:架构选型、技术方案最终拍板等,只能由主 Agent 完成
5.2 子 Agent 类型选型
Swarm 支持三种子 Agent 类型,对应不同的任务属性:
coder(默认):通用编码角色,具备完整的文件读写、命令执行能力,适合代码修改、调试、落地类任务explore:只读探索角色,仅具备阅读和检索能力,不会修改项目文件,适合代码梳理、信息调研类任务,安全性更高plan:规划设计角色,专注于方案设计与任务拆解,不执行实际修改,适合技术方案设计、模块划分类任务
5.3 任务拆分的原则
拆分质量直接决定了 Swarm 模式的效果,核心遵循三个原则:
- 职责不重叠:每个子任务的边界清晰,避免多个子 Agent 修改同一个文件或同一段逻辑
- 颗粒度适中:颗粒度太粗体现不出并行优势,太细则主 Agent 汇总成本过高,且子 Agent 启动开销占比变大。通常以「单个独立文件」或「一个完整小功能」为单位比较合适
- 上下文自包含:每个子任务的 prompt 要包含足够的背景信息,让子 Agent 不需要额外询问就能独立完成,减少来回交互的开销
5.4 常见避坑指南
- 不要在子任务里塞过多全局背景,避免 token 浪费,只保留与当前子任务相关的必要信息
- 遇到部分子 Agent 失败时,优先用
resume_agent_ids恢复执行,而不是重新创建,保留上下文可以大幅提升重试效率 - 强写操作的任务建议适当降低并发数,减少文件系统冲突的概率;只读类任务可以放心开满并发
六、能力边界与总结
当前架构的局限
作为一套务实的工程落地方案,Swarm 模式也有明确的能力边界:
- 无 DAG 依赖支持:目前所有子任务都是并行启动,不支持任务之间的依赖关系(A 完成后才能启动 B),复杂工作流还需要主 Agent 分多轮调度
- 无子 Agent 横向通信:子 Agent 之间不能直接交互,所有信息都必须经过主 Agent 中转,不适合需要频繁协作的场景
- 汇总质量依赖主 Agent:子 Agent 数量越多,主 Agent 汇总的难度越大,信息遗漏、结论冲突的概率会上升
- Token 成本更高:并行执行意味着多份上下文开销,整体 token 消耗通常高于单 Agent 串行,本质是用成本换时间
写在最后
从单 Agent 串行到多 Agent 并行,是 AI 编程助手能力升级的必然方向。Swarm 模式的价值,不仅在于提供了更快的任务执行速度,更在于它探索出了一套可落地、可复用的多 Agent 工程范式------用分层架构解耦复杂度,用渐进式调度平衡效率与稳定性,用语义约束替代系统级锁来控制成本。
它没有追求理想化的全自主多 Agent 协作,而是选择了「主从式、批量并行、调度层轻量化」的务实路线,把复杂度集中在任务拆分和结果汇总两端,中间调度层保持简单可靠。这种设计思路,对于所有正在落地多 Agent 系统的团队,都有非常直接的借鉴意义。