Repository navigation
Description
Summary
Maka already has a production-capable Swarm Engine: the main agent can call agent_swarm, dispatch 1–32 independent items as real child AgentRuns, run them with bounded all-settled concurrency, propagate cancellation, preserve input order, and synthesize structured results. Desktop, CLI, and Headless already expose the tool and its trace/evidence.
What Maka does not yet have is a first-class Swarm Mode: an explicit product-level orchestration policy that tells the main agent when and how to use that engine.
Maka already has the Swarm Engine. This issue adds Swarm Mode.
User entry point
↓
Session / Turn orchestration policy
↓
Prompt + tool visibility + authorization + step admission
↓
agent_swarm engine
↓
Child AgentRuns
Why this is an orchestration policy
Swarm Mode should not become another child-agent profile or a third value of the existing Agent/Plan collaboration mode.
- Collaboration mode (
agent | plan): are we planning or executing? - Orchestration mode (
default | swarm): how should executable work be scheduled? - Swarm engine (
agent_swarm): how is one bounded batch executed?
Suggested type:
type OrchestrationMode = 'default' | 'swarm';This leaves room for future research, review, debate, or pipeline policies without adding special branches to the main agent loop.
Proposed UX
/swarm
/swarm status
/swarm on
/swarm off
/swarm <task>
- Default mode: the main agent may still choose
agent_swarmopportunistically. /swarm on: persist explicit Swarm Mode for the current session./swarm off: return to default orchestration; it does not disable the Swarm Engine./swarm <task>: use Swarm Mode for this turn only, without changing the session default.- Bare
/swarm/status: report the effective mode and explain default-mode behavior.
Keep the durable default separate from a trusted turn override:
orchestrationMode: 'default' | 'swarm';
turnOrchestration?: {
mode: 'swarm';
source: 'slash_command' | 'host_api';
};
effectiveMode =
turnOrchestration?.mode ??
session.orchestrationMode;The effective mode and source should be captured in the AgentRun, so crash recovery and resume retain the original execution contract. A one-shot turn should not temporarily mutate the session and rely on a cleanup transition that may be lost after cancellation or a crash.
Shared Swarm reminder
Runtime should own a shared renderSwarmModePrompt(), reused by every host. It should tell the main agent to:
- Perform only the lightweight exploration needed to establish boundaries.
- Dispatch together only items that can execute independently.
- Make every item bounded and self-contained, with explicit scope, output, and constraints.
- Avoid overlapping writes; prefer read-only work unless isolation is available.
- Wait for the whole batch to settle.
- Verify, deduplicate, and semantically synthesize results rather than pasting child output.
- Avoid fake parallelism: if the task cannot meaningfully produce at least two independent items, explain that and continue normally.
- Call
agent_swarmas the only tool in its assistant step.
This must be trusted orchestration context, not text smuggled into a user message.
Runtime invariants
Step-0 tool visibility
Tool economy may defer the subagent group behind load_tools. Swarm Mode must not ask the model to use an invisible tool.
Add a general mechanism such as:
requiredToolsForTurn: ReadonlySet<string>A Swarm turn pins agent_swarm into the step-0 active set while preserving economy mode elsewhere. The abstraction can later serve Plan, Computer Use, Deep Research, and other modes.
Exclusive-step execution
Prompt guidance is insufficient for “do not mix agent_swarm with other tool calls in one model response.”
Add a reusable contract:
interface MakaTool {
executionSemantics?: 'parallel' | 'exclusive_step';
}Set agent_swarm to exclusive_step. Runtime keeps admission state keyed by stepId and registers before the first asynchronous boundary:
| Calls in one assistant step | Result |
|---|---|
| ordinary → ordinary | allow |
ordinary → agent_swarm |
reject the swarm call |
agent_swarm → ordinary |
reject the ordinary call |
agent_swarm → agent_swarm |
reject the second swarm call |
This remains generic for future transaction, handoff, or submission tools.
Orchestration is not authorization
The permission engine remains the single authority.
- An opportunistic call in default mode keeps current approval behavior.
/swarm <task>grants exactly theagent_swarmenvelope for that trusted turn./swarm onrecords a durable session-scoped grant for that envelope.- The grant does not authorize child Bash, writes, network, extra filesystem access, or other tools.
- Child agents retain their own profile, permission mode, sandbox, and tool policy.
- Trace/evidence records the authorization source and scope.
main agent → agent_swarm envelope may be authorized by explicit Swarm Mode
child agent → individual tools remains independently permission-gated
Staged PR plan
PR 1 — Runtime orchestration contract
Host-independent semantics:
- Add
OrchestrationModeand validation. - Persist the session default in
SessionHeader/SessionSummary, withdefaultas the legacy fallback. - Add a trusted turn-level override.
- Record effective mode/source in
AgentRun. - Add shared
renderSwarmModePrompt(). - Add
requiredToolsForTurnand step-0 pinning. - Add generic
exclusive_stepadmission. - Add exact scoped Swarm authorization without widening child permissions.
- Emit trace fields for mode, source, authorization, and admission rejection.
- Add storage compatibility, permission, cancellation, crash, resume, tool-economy, and concurrency tests.
Acceptance:
- Legacy sessions decode as
default. - One-shot and persistent Swarm contracts survive recovery.
agent_swarmis visible at step 0.- Mixed same-step calls cannot execute both the swarm and another tool.
- Swarm authorization never grants child-tool authority.
PR 2 — CLI /swarm
- Add
/swarm,status,on,off, and/swarm <task>. - Persist on/off through the Runtime session API.
- Send one-shot tasks as trusted turn overrides while keeping displayed text clean.
- Show mode-change and one-shot notices.
- Restore/display mode correctly after session switch,
--resume, rewind/branch, and new session. - Reject unsafe mode mutation during a running turn or permission handoff.
- Add parser, driver, transcript, lifecycle, cancellation, and resume tests.
Acceptance:
- One-shot affects exactly one turn.
- Persistent mode lasts until off.
- Default mode still permits opportunistic Swarm.
- Command text is not injected as a fake user-level system instruction.
PR 3 — Desktop and Headless parity
Desktop:
- Add a Swarm Mode toggle/badge.
- Handle
/swarm <task>consistently with CLI. - Persist/restore the default and show effective mode for active, resumed, and branched sessions.
- Surface scoped authorization and exclusive-step rejection in trace/evidence.
Headless:
- Add session-default and turn-override API options.
- Keep default behavior backward compatible.
- Expose effective mode/source in structured evidence.
- Add host-contract tests proving Runtime policy, not host-specific prompt text, controls behavior.
Acceptance:
- Desktop, CLI, and Headless have identical orchestration semantics.
- UI differences cannot change runtime safety.
- Existing
agent_swarmrendering/evidence stays compatible.
Follow-up enhancements — out of the first delivery
A. prompt_template × items
Accept a reusable prompt template plus structured items, then normalize it into the existing explicit item contract. This reduces payload size, makes large batches easier to construct, and keeps task wording consistent while preserving item order and evidence.
B. resume_agent_ids
Resume selected failed, interrupted, or parked child runs instead of starting replacements. This needs stable identity/lineage, terminal-state and workspace eligibility checks, indeterminate tool-boundary handling, resumed-vs-new result projection, and idempotency. It must build on Runtime resume safety rather than bypass it.
C. Provider rate-limit awareness
Classify provider throttling separately from ordinary failure and feed Retry-After/quota information into scheduling. The scheduler needs provider/connection identity, retryability, backoff, side-effect awareness, and fairness between batches sharing a provider.
D. Dynamic concurrency capacity
Adapt capacity under a hard safety ceiling using rate-limit observations, latency/failure rate, CPU/memory pressure, provider configuration, global/session fairness, and cost/token budgets. Capacity changes must preserve result-slot order and structured cancellation.
E. Real worktree isolation
Honor the reserved isolation intent with actual isolated workspaces. Define worktree lifecycle, base commit and dirty-worktree policy, deterministic child cwd, patch/commit artifacts, conflict-aware write-back, cancellation/crash cleanup, orphan recovery, and filesystem permission boundaries.
F. Per-item retry policy
Add bounded explicit retry policy for retryable transport/provider errors, deterministic failures, permission waiting/denial, cancellation, and indeterminate post-crash execution. Include backoff, attempt lineage/evidence, and protection against silently duplicating side effects.
G. Multi-batch pipeline Swarm
Support dependent stages such as map → review → reduce or research → challenge → synthesis. This is a DAG/pipeline layer above bounded swarms:
- Nodes are bounded swarms or reducer steps.
- Edges carry typed artifacts/results.
- Stages wait only for declared dependencies.
- Failure policies can be fail-fast, all-settled, quorum, or partial continuation.
- Cancellation/resume operate on graph state.
- Final synthesis receives provenance-preserving evidence.
The current bounded Swarm Engine remains the leaf executor.
First-delivery non-goals
- Raising the current concurrency safety cap.
- Nested child swarms.
- Arbitrary decomposition without main-agent semantic ownership.
- Silent permission widening.
- Shared-workspace concurrent writes without isolation.
- A general DAG engine.
- Provider-specific scheduling logic.
Definition of done
A user can enter persistent Swarm Mode or run one one-shot Swarm turn through CLI, Desktop, or Headless; the main agent receives trusted shared guidance; agent_swarm is immediately visible; Runtime enforces exclusive-step admission; authorization is narrow and auditable; session switching, cancellation, crash recovery, and resume preserve the effective contract; and default mode retains today's opportunistic Swarm behavior.
中文设计说明
摘要与定位
Maka 已经有完整的 Swarm Engine:agent_swarm 可以启动真实 child AgentRun,进行有界 all-settled 并发、取消传播、顺序稳定的结构化汇总,并已经接入 Desktop、CLI、Headless 和 trace/evidence。
这个 issue 增加的是产品层的 Swarm Mode。它不是新的 child profile,也不是 Agent/Plan 的第三种协作模式,而是与协作模式正交的调度策略:
- 协作模式决定“规划还是执行”。
- 调度模式决定“可执行工作如何调度”。
agent_swarm负责“一批独立 child 如何执行”。
建议增加 OrchestrationMode = 'default' | 'swarm'。
用户语义
支持:
/swarm、/swarm status:显示当前有效模式。/swarm on:当前 Session 持久进入显式 Swarm Mode。/swarm off:返回普通调度,但不禁用 Swarm Engine。/swarm <task>:只覆盖当前 Turn,不修改 Session 默认值。
普通模式下主 Agent 仍可在合适时主动调用 Swarm。一次性 Turn override 与 Session 默认值必须分开,有效模式及来源要记录进 AgentRun,以便 crash recovery 和 resume 保持原始契约。
共享 reminder
Runtime 提供所有 Host 共用的 renderSwarmModePrompt(),要求主 Agent:
- 只做确认边界所需的轻量探索。
- 只把真正独立的工单放入同一批。
- 每项都必须有明确范围、产出、限制,并且自包含。
- 避免重叠写入;无隔离时优先只读。
- 等待整批 settled。
- 验证、去重和语义汇总,而不是粘贴 child 输出。
- 无法合理拆成至少两个独立工单时,不制造虚假并行。
- 调用
agent_swarm的 step 不混用其他工具。
它必须属于可信调度上下文,不能伪装成用户消息。
Runtime 不变量
step 0 工具可见
Tool economy 可能把 subagent 组藏在 load_tools 后。增加通用 requiredToolsForTurn,让 Swarm Turn 从 step 0 就看到 agent_swarm,普通模式继续保持 economy。
exclusive-step
给 MakaTool 增加通用 executionSemantics?: 'parallel' | 'exclusive_step',令 agent_swarm 使用 exclusive_step。Runtime 按 stepId 在首个异步边界前登记 admission:
- 普通 → 普通:允许。
- 普通 → Swarm:拒绝 Swarm。
- Swarm → 普通:拒绝普通工具。
- Swarm → Swarm:拒绝第二个 Swarm。
调度不等于授权
Permission Engine 继续作为唯一授权者:
- 普通模式的机会性 Swarm 保持现有审批。
/swarm <task>只授权当前可信 Turn 的 Swarm envelope。/swarm on只形成 Session 范围的 Swarm envelope 授权。- child 的 Bash、写入、网络、额外目录等仍独立审批。
- trace/evidence 记录授权来源和范围。
三阶段 PR
PR 1:Runtime orchestration contract
增加模式类型/校验、Session 持久化与旧数据 fallback、Turn override、AgentRun effective mode、共享 reminder、step-0 tool pinning、通用 exclusive-step、精确授权及 trace。覆盖 storage、permission、cancellation、crash、resume、tool economy 和并发 admission 测试。
验收重点:旧 Session 兼容;一次性和持久模式可恢复;Swarm 工具首步可见;同 step 不会同时执行 Swarm 与普通工具;Swarm 授权不会扩张 child 权限。
PR 2:CLI /swarm
实现 /swarm、status、on、off、/swarm <task>,通过 Runtime API 持久化 on/off,一次性任务使用可信 Turn override,显示模式提示,并处理 session switch、resume、rewind/branch、新 Session 以及运行中/权限等待时的安全切换。补齐解析、driver、transcript、生命周期、取消和 resume 测试。
PR 3:Desktop 与 Headless 对齐
Desktop 增加 toggle/badge、一次性命令、模式恢复与 trace/evidence 展示。Headless 增加 Session 默认值和 Turn override API,保持默认向后兼容,并输出 effective mode/source。Host-contract tests 确保语义由共享 Runtime 控制。
首轮明确不做的增强
A. prompt_template × items
用一个可复用模板配合结构化 items,在 Runtime 中规范化为现有显式工单。减少 payload、统一措辞、方便大批量构造,同时保持顺序和 evidence。
B. resume_agent_ids
恢复指定失败、中断或 parked child,需要稳定 identity/lineage、状态与 workspace eligibility、未确定工具边界处理、恢复/新建结果区分和幂等性。必须建立在 Runtime resume 安全契约上。
C. Provider 限流感知
把 throttling 从普通失败中独立分类,将 Retry-After、quota、provider/connection identity 输入调度器,并处理可重试性、退避、副作用状态和共享 provider 的公平性。
D. 动态并发容量
在硬安全上限下,根据限流、延迟/失败率、CPU/内存、provider 配置、公平性、成本/token budget 自适应调整;不能破坏结果顺序和取消语义。
E. worktree 真正隔离
真正创建隔离 workspace,定义生命周期、base commit/dirty policy、child cwd、patch/commit artifact、冲突感知 write-back、取消/崩溃清理、孤儿恢复和路径权限边界。
F. 子任务重试策略
为 transport/provider 错误、确定性失败、权限等待/拒绝、取消和崩溃后未确定执行提供有限次数、退避、attempt lineage/evidence,并防止悄悄重复副作用。
G. 多批次流水线 Swarm
支持 map → review → reduce、research → challenge → synthesis 等 DAG。节点是 bounded swarm 或 reducer,边传递有类型结果,每阶段只等待声明依赖,支持 fail-fast/all-settled/quorum/partial continuation,并让 cancellation/resume 操作图状态。现有 bounded Swarm 保持为叶子执行器。
首轮非目标与完成定义
首轮不提高并发上限、不允许 child 嵌套 Swarm、不静默放宽权限、不在无隔离时并发共享写入、不实现通用 DAG 和 provider-specific scheduler。
完成时,CLI/Desktop/Headless 均可进入持久 Swarm Mode 或发起一次性 Swarm Turn;主 Agent 获得可信共享指导;agent_swarm 首步可见;Runtime 强制 exclusive-step;授权严格可审计;session 切换、取消、crash recovery 和 resume 均保留契约;普通模式继续支持机会性 Swarm。
Activity