subagents-protocol
Mandatory protocol for delegating work to built-in subagents (coder, explore, plan), also called our bots by users. Always active. Owns the context-hygiene delegation test (material vs answer, cost balance, warm-instance reuse), launch parameters (mandatory explicit `model`), the single-source model-selection table, answer budgets, degradation handling, the launch checklist, and the role library for delegated review/audit with intent routing (`references/roles.md`).
- License 许可
- BSD-3-Clause
- 所属仓库
- kalaverin/skills
- 最近更新
- 2026-11-15
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- subagents-protocol
- version
- 0.3.1
- requires
- [ "bootstrap", "mandatory-tools", "serena-protocol" ]
- triggers
- { "always": true, "reason": "Context hygiene must apply from session start — before any delegation is planned — so the skill is always active.", "request": "subagent, subagents, delegate, delegation, delegating, our bots, project bots, delegated bots, бот, боты, ботами, ботов, субагент, субагенты, делегируй, делегирование, coder subagent, explore subagent, plan subagent, review roles, role prompts, subagent reviewer, test auditor, security reviewer, роли субагентов, ревью-роль, бот-ревьюер" }
- description
- Mandatory protocol for delegating work to built-in subagents (coder, explore, plan), also called our bots by users. Always active. Owns the context-hygiene delegation test (material vs answer, cost balance, warm-instance reuse), launch parameters (mandatory explicit `model`), the single-source model-selection table, answer budgets, degradation handling, the launch checklist, and the role library for delegated review/audit with intent routing (`references/roles.md`).
02 资源文件 2
- 参考文档README.md4.8 KB
- 参考文档references/roles.md16.0 KB
03 SKILL.md 正文
SKILL: Subagent Delegation Protocol
This skill governs every interaction with the Agent tool and its built-in subagent instances.
The main agent is an orchestrator; subagents are specialized workers.
The skill is always active: its rules — including the Context Hygiene test — apply from session start, before any delegation is planned, and take precedence over any general heuristic about delegation.
Terminology and context rule: the user may call our built-in subagents bot, bots, our bots, бот, боты, ботами, ботов, or наших ботов. Interpret these terms as our subagents when nearby context mentions delegation, Agent, coder, explore, plan, project-file access, or delegated work. Do not apply this protocol to unrelated bots; if context does not disambiguate, ask the user whether they mean our subagents.
1. When to Delegate
The delegation decision is governed EXACTLY by the three-question test of Context Hygiene (HARD) below. Typical delegation-positive cases:
- Codebase investigation beyond a few files or searches.
- Writing, refactoring, or debugging code.
- Multi-step file manipulations.
- Parallel exploration of independent questions.
- Long-running project read/write tasks that can continue in the background without shell or CLI execution.
Acting directly is legitimate exactly per the direct-action exceptions and sizing probes of Context Hygiene — nothing else.
Context Hygiene (HARD)
[ref: #sp-context-hygiene]
The main agent's context is the scarcest resource in the session. Bulk material needed only as the SOURCE OF AN ANSWER never enters it — a subagent eats the volume and returns the distillate.
The three-question test (before any read/search/explore operation):
- Material or answer? Do I need the material itself (I will edit it, quote it exactly, reason over it repeatedly) — or only an answer derived from it?
- Does the volume pay for the delegation? The prompt and the returned answer are also main-context tokens; delegate only when the volume kept out clearly outweighs that overhead.
- New instance or a warm one? A subagent that already read this corpus holds it in context — follow-ups go to the same
agent_id; a fresh instance pays the reading cost twice (resume rule, §8).
If you need only an answer AND the volume pays → delegate (to a warm instance when one covers this corpus, otherwise to a new one). Otherwise act directly.
MUST-delegate triggers:
- open-ended exploration: more than 3 files to read or grep for one question;
- large files, logs, dumps, or command output read for a single fact or a summary (did tests pass, what failed in the build);
- serial "what's in these N files" questions on one corpus — ONE subagent with the full question list (batching amortizes the prompt).
Sizing probes (allowed): when the material's size is unknown, a single careful probe — a toe in the water, never a swim — is legal before deciding: wc -l, a head, one bounded grep. The probe exists to size the volume, not to read the content; if the probe already answers the question, the question was small — act directly and move on.
Direct-action exceptions (no delegation, no guilt):
- material you will EDIT or must quote exactly;
- material that IS the deliverable;
- the small critical core of the current reasoning (the approved blueprint, the active rules);
- a single known file at a known place, a single grep hit, anything small enough that prompt+answer would cost about as much.
Subagent reuse (STRONG):
- contextual subagents are assets: an instance that has read a corpus is a warm index over it — follow-ups, refinements, and adjacent tasks on the same material go to the SAME instance via
resume; - keep a mental roster of live instances and their coverage; check the roster before any new launch;
- retire an instance when its corpus is exhausted or the topic shifts — stretching one instance across unrelated domains pollutes the subagent's own context and is also waste.
The answer budget:
- every delegation prompt carries an explicit cap: "≤5 sentences", "a ≤10-row table", "yes/no + path + one-line why";
- the cap governs ANSWERS TO QUESTIONS, not deliverables: when the task's output IS an artifact, the deliverable-in-report rule (§12) overrides — the cap then applies to everything except the deliverable;
- a raw dump from a subagent defeats the answer budget: ask the SAME instance to compress — never paste the dump into your own reasoning.
Carve-out (web): subagents cannot search the web (§6); the main agent performs Kagi calls itself and distills the results (per kagi-search) — the hygiene rule does not redirect web work, it governs local corpora.
Violation protocol: violations of this section — including over-delegation — follow §15; the balance cuts both ways.
2. Built-in Subagent Types
Use the correct subagent_type for the work:
| Type | Purpose | Use when |
|---|---|---|
coder |
General software engineering tasks through project file-write tools. | Writing code, refactoring, debugging, building features, fixing tests; no shell or CLI execution. |
explore |
Fast read-only codebase exploration. | Finding files, understanding modules, tracing call sites, answering "how does X work?", architecture reconnaissance. |
plan |
Read-only implementation planning. | Designing a change, identifying key files, comparing approaches, producing a step-by-step plan before editing. |
If a task spans multiple types, split it or choose the dominant type.
Artifact rule (CRITICAL — VERY IMPORTANT, HARD RULE): if a subagent must write ANY artifact to disk — a file, staging dump, generated document, or any other deliverable — the launch MUST explicitly set subagent_type: coder. coder is the only subagent type with file-write capability (WriteFile). explore and plan are strictly read-only and MUST NOT receive disk-writing work. The root agent MUST create every target directory before launching coder; coder may write files only inside directories that already exist and MUST NOT create directories. The prompt MUST name the artifact's target path: scratch or staging artifacts go under .tmp/; deliverables that are real project files name their real project path. Owner ruling 2026-08-31.
3. Always-Active Semantics
This skill is always active: there is no load event to wait for and no trigger to re-evaluate. The Context Hygiene test applies from the very first read operation of the session, even before any delegation is planned.
4. Launch Parameters
Every Agent call MUST include:
description: a short 3–5 word summary.subagent_type:coder,explore, orplan.prompt: a complete, self-contained instruction.model(HARD): MANDATORY on every launch, chosen per the Model Selection section below — the SINGLE SOURCE of model names, tiers, and selection criteria. NEVER omit the parameter: the fallback chain (built-in type default → the parent's current model) silently runs the subagent on a more expensive model and burns tokens. An omittedmodelis a protocol violation (§15).promptcarries an explicit answer cap per the answer budget ([ref: #sp-context-hygiene]).
Optional but important:
timeout:1200seconds for simple tasks;3600seconds (the maximum) for complex investigations or large code changes. These two constants are owned HERE — every other mention (the checklist included) references this rule and never restates the numbers.run_in_background: defaultfalse. Usetrueonly when the task can continue independently, you do not need the result immediately, and there is a clear benefit to returning control before it finishes.resume: reuse an existingagent_idwhen the new task clearly continues prior work or when that instance already holds relevant context.
Model Selection (SINGLE SOURCE)
[ref: #sp-model-selection]
This section is the ONLY place in the project where subagent model names, tiers, and selection criteria live. Every other document, checklist, or memory references this section by anchor and NEVER names a model — names change; the pointer does not.
| Tier | Model | Use for |
|---|---|---|
| Default | kimi-code/kimi-for-coding |
Everything routine: focused file/symbol lookups, known-file reads, mechanical edits, command runs, artifact attestation, template fills, single-file analysis. |
| Upgrade | kimi-code/kimi-for-coding |
Tasks needing extra attention and judgment: complex or cross-cutting research (thorough exploration, architecture reconnaissance), judgment-heavy adversarial review or audit, synthesis over many inputs, work where a miss is expensive (security detection, validation). |
Single-model reality (temporary): both tiers currently resolve to the same model name — only one coding model is available. The tiers differ in selection intent; the Upgrade row is the placeholder to update the moment a stronger model appears. Until then, model-level escalation is a no-op: escalate by resuming the SAME instance with a sharpened prompt (narrower scope, explicit suspicion list), not by switching models.
Escalation ladder: if a default-tier subagent returns shallow or wrong work, escalate by resuming the SAME instance (its corpus context is preserved) — with a sharper prompt today, and on the upgrade tier once a distinct upgrade model exists (resume with an explicit model override; if the runtime rejects a model change on resume, start a new instance on the upgrade tier). Start a new instance only when the original instance's context is polluted or lost — do not iterate against a model that is too weak for the task.
Explicit-parameter rule: the model parameter is passed on EVERY launch (§4), always from this table — never from memory, never from other documents.
5. Context Passing
Subagents do NOT have access to MCP tools, Serena memory operations, or Kagi web search. Therefore:
- Pass all necessary context explicitly inside the
prompt. - When Serena memory pages are relevant, pass their file paths (e.g.,
.serena/memories/decisions/project/xxx.md) and instruct the subagent to read them via standard shell commands. - NEVER paste large memory contents inline into the subagent prompt.
- NEVER assume the subagent sees the current conversation history or project context.
6. Web Search Bridge
Because subagents cannot use kagimcp tools, the main agent MUST perform any required internet research, documentation lookup, or web enrichment.
Distill the retrieved information and pass only the relevant facts to the subagent in its prompt.
If a subagent discovers it needs more web data, it should ask the main agent for a specific search.
7. Foreground vs Background
Default to foreground subagents. Use a background subagent only if all of the following are true:
- The task can continue independently.
- You do not need the result to decide your next action.
- Returning control early provides a clear benefit to the user or the workflow.
After starting a background task, default to returning control to the user instead of immediately waiting.
Use TaskOutput for non-blocking progress snapshots and TaskOutput(block=true) only when you intentionally want to wait.
Use TaskStop only when cancellation is truly necessary.
8. Resume vs New Instance
The Agent tool can create a new instance or resume an existing one by agent_id.
- Create a new instance when the task is unrelated to previous subagent work.
- Resume an existing instance when the task is a direct continuation or when that instance already holds relevant context.
- Each instance keeps its own context history; repeated use of the same
agent_idpreserves prior findings.
9. What Subagents Cannot Do
Subagents have no shell, CLI, MCP, or other executable-tool access. They can navigate project files and read them; only a coder subagent can write files through its write tool.
All subagents MUST NOT:
- Invoke shell tools, shell commands, CLI commands, package managers, or other executable tools.
- Create directories or modify directory structure. The root agent creates target directories before launching
coder. - Read
AGENTS.md— under NO circumstances, at any directory level, for any reason. A subagent's entire context is its launch prompt (§5);AGENTS.mdis main-agent boot material and user preferences that carry nothing a subagent needs and only burn its context. - Call Serena memory tools (
read_memory,write_memory, etc.). - Call Kagi web search tools (
kagi_search_fetch,kagi_fastgpt, etc.). - Call Serena symbolic/LSP tools (
find_symbol,replace_symbol_body, etc.).
explore and plan MUST remain read-only. coder MAY write files only inside pre-existing directories; coder MUST NOT create directories or invoke shell/CLI tools. If a subagent task needs any forbidden operation, the main agent performs it and passes the result to the subagent.
10. Prompt Quality
A subagent prompt MUST be:
- Self-contained: include goals, constraints, file paths, and expected outputs.
- Specific: define success criteria and deliverables.
- Context-aware: mention relevant memories, previous findings, or project conventions.
- Bounded: set clear scope and tell the subagent what NOT to do.
Role Library
[ref: #sp-role-library]
For delegated review/audit of an existing diff, pick a role by intent and launch it as subagent_type: explore (physically read-only = "review only") with the model chosen per [ref: #sp-model-selection]. Role definitions, output contracts, and prompt templates live in references/roles.md — load the single role section by its anchor, not the whole file.
Input materialization: subagents have no shell/git (§12), so the main agent produces the review input itself — git diff output pasted into the prompt, or written to a file under .tmp/ whose path the prompt names. Roles never run git themselves; web data, if needed, is fetched by the main agent (§6).
Intent routing:
| User intent (examples) | Role | Anchor |
|---|---|---|
| "check this diff", «посмотри изменения», «что сломается» | Reviewer | [ref: #roles-reviewer] |
| «проверь переходы статусов», "workflow behavior", «сторонние эффекты» | Domain reviewer | [ref: #roles-domain] |
| «проверь доступы», "auth/security check", «утечки данных» | Security reviewer | [ref: #roles-security] |
| «проверь консьюмера/интеграцию», "retry and idempotency" | Integration reviewer | [ref: #roles-integration] |
| «хватает ли тестов», "test coverage check" | Test auditor | [ref: #roles-test-auditor] |
| «спеки не разъехались?», "docs consistency" | Docs auditor | [ref: #roles-docs-auditor] |
| «миграция безопасна?», "rollback and locks" | Data reviewer | [ref: #roles-data-reviewer] |
Routing rules:
- Unclear intent — the request is recognizably a review but the aspect is unknown → Reviewer; fully unclear — it is not even established that the user wants a review → one short question to the user first.
- Multi-aspect request → roles in parallel (concurrent foreground launches in one block; the §7 foreground default governs the wait), at most 3 roles per diff; fixed pairings per diff type live in
[ref: #roles-parent-workflow]. - Load the role section by anchor, fill the prompt template with a narrow scope, launch per §14.
- Boundary: an explicit "code review" / «ревью кода» request — or any request expecting a formal review verdict over a whole change — goes to the
code-reviewskill (full pipeline); this library covers point assessments of a diff's named aspect. - Proactive offer: a vague review intent («проверь быстро», «посмотри») in a clearly code context → offer 2–3 fitting roles as a short option list; launch only after the user's pick.
11. Output Handling
- Subagent results are visible only to the main agent.
- Summarize subagent findings for the user in the final response; do not dump raw subagent output unless explicitly requested.
- If a subagent fails or times out, decide whether to retry, re-delegate with a clarified prompt, or handle the task directly.
- Degradation handling (launch time): if the launch itself is rejected or the requested model is unavailable, fall back to doing the work directly and disclose the fallback to the user in one line.
12. Subagent Tool Boundary (HARD)
Subagents never have shell, CLI, MCP, package-manager, or other executable-tool access. Read access is available for project navigation and file inspection. File writes are available only to an explicitly launched coder, and only through its write tool; explore and plan remain physically read-only.
Every delegation MUST follow these rules:
- Read through project tools. All subagents navigate and inspect files through their available project read tools; no shell-equivalent fallback or command emulation is permitted.
- Write only through
coder. Any disk artifact requires an explicitsubagent_type: coderlaunch. The root agent creates target directories before launch;coderwrites only inside those existing directories and cannot create directories. - Never retry, never bypass. A rejected or unavailable tool call is final: the subagent MUST NOT retry the same call and MUST NOT attempt indirect bypasses.
- State the limitation. The subagent's final report MUST explicitly list which requested operations were unavailable and what was omitted because of it.
- Deliverable-in-report. When delegating drafting or editing work, instruct the subagent to ALWAYS include the full deliverable text in its report — the report doubles as a fallback transport when writes are unavailable; the main agent then applies the edits and runs verification itself.
- Skills MAY add artifact-specific boundary addenda but MUST NOT contradict this section.
13. Directory Trees Belong to the Root Agent (HARD)
Applies whenever a delegated artifact would contain a directory tree. A subagent NEVER generates a directory tree for an artifact. Tree generation is a root-agent duty:
- The root agent has reliable shell access; subagents have no shell access at all (§12).
- A tree embedded in a deliverable must be byte-deterministic — produced by the canonical command, never paraphrased from exploration.
The canonical command and its mandatory flags live in mandatory-tools — [ref: #tree-agent-rules] (references/tree.md). Consumers reference that anchor instead of restating the command. If a consuming skill needs a fallback for a missing tree binary, the fallback is defined by that skill (e.g. the flat-list fallback defined in entity-protocol [ref: #entity-card-workflow]).
14. Subagent Launch Checklist
Use this checklist before every Agent call.
0. Before delegating
- [ ] Context hygiene checked (
[ref: #sp-context-hygiene]): for exploration — only an answer is needed and the volume pays; for execution tasks — delegation serves isolation/focus per §1; a warm instance was considered before a new launch. - [ ] Delegated review/audit task → role selected via
[ref: #sp-role-library]; the role section loaded fromreferences/roles.mdby anchor. - [ ] The prompt carries an explicit answer cap (the answer budget).
1. Subagent type
- [ ]
coderexplicitly selected for any task that writes files; target directories already exist; no directory creation or shell/CLI execution expected. - [ ]
exploreselected only for read-only codebase investigation. - [ ]
planselected only for read-only implementation planning.
2. Launch parameters
- [ ]
descriptionis 3–5 words. - [ ]
subagent_typematches the task. - [ ]
promptis self-contained and specific. - [ ]
timeoutfollows the §4 rule (the constants are owned there). - [ ]
modelis set EXPLICITLY on every launch (never omitted), chosen per[ref: #sp-model-selection]. - [ ]
run_in_backgroundistrueonly when the task can proceed independently and returning early is useful. - [ ]
resumeis used only when continuing prior work on the sameagent_id.
3. Context
- [ ] All necessary context is in the prompt.
- [ ] Relevant Serena memory pages are referenced by file path, not pasted inline.
- [ ] Web search results, if needed, were fetched by the main agent and summarized in the prompt.
4. Constraints
- [ ] The subagent is not expected to use shell, CLI, package managers, or any executable tools.
- [ ] The subagent is not expected to use MCP tools, Serena memory, or Kagi search.
- [ ] Any disk-writing task explicitly selects
coder; target directories exist before launch. - [ ]
exploreandplanreceive read-only work only. - [ ] Success criteria and deliverables are explicit.
- [ ] Scope boundaries are clear.
5. After launch
- [ ] Foreground: wait for completion and summarize findings.
- [ ] Background: use
TaskOutputfor snapshots; wait withTaskOutput(block=true)only when intentionally blocking. - [ ] Cancel with
TaskStoponly when necessary.
15. Violation Protocol
Violations of any rule in this skill follow ONE protocol: halt immediately, recall the violated section, and restart the action correctly. When the violation is already unrecoverable (the launch already fired, the output already produced), disclose it to the user in one line and apply the correct form on the very next action. This section is the single violation protocol of the skill; other sections reference it instead of restating their own.
04 同仓库更多 Skills
todo-protocol
Mandatory protocol for using the SetTodoList tool. Governs when to create a todo list, how to update it without violating immutability rules, how to synchronize item status after every tool call, and the forbidden mutations. Always active.
serena-protocol
MANDATORY skill for Serena (MCP) memory, knowledge base, and symbolic code exploration operations. Use whenever the agent needs to: read or write Serena memories, mutate or persist memory, explore code via symbolic MCP tools, resolve contradictions in stored knowledge, or follow memory metadata, naming, and routing conventions.
read-for-comments
Mandatory local standards library and archive. Before fetching any standard from the internet, the agent MUST check the Serena `standard/` archive and this skill's `references/` seed; after ANY standard-body download, the agent MUST archive it per the event-bound Archival Rule. Governs standard lookup, fetch, archival, and the family and full-body rules.
python-lang
MANDATORY skill for Python code. Use when writing, editing, refactoring, or reviewing Python files, modules, packages, classes, functions, type annotations, imports, exceptions, comprehensions, decorators, or docstrings. Enforces Google Python Style Guide and a mandatory, unconditional Ruff format+check pipeline scoped strictly to the agent's own changes.
preflight-checklist
Mandatory session-initialization closer and Startup Gate audit. Always loaded. Runs EXACTLY ONCE at session start, after all skill loading completes: verifies Startup Gate completion with evidence (mirror sync, forced import, discovery, activation, memory priming, MCP declaration, think block), runs dynamic session checks derived from the active skill set (mode states, delegation readiness), and reports a compact evidence-backed verdict table to the user before the first task output. Any FAIL is fixed before proceeding.
markdown-protocol
MANDATORY skill for Markdown authoring rules and the Markdown Headings as a Public API standard. Always active. Governs how the agent writes and edits any Markdown file: line discipline, date format, frontmatter pairing, markers and anchors, heading identity (slugs, renames, uniqueness), section shape and size, deprecation, and the errata conformance queue. The full normative standard lives in references/specification.md with rationale in references/rationale.md.