Browse documentation

Technical documentation / Reference

Prompt construction

Feature docs index ยท Repository README

Magi-code assembles provider instructions from prompt templates, runtime facts, repository instructions, and available skills and agent profiles. Tool definitions travel separately from this text.

Prompt assembly

AgentSession::new_with_prompt_dir_and_subagents builds one assistant system prompt before each agent session starts. src/agent/prompt.rs renders sections in this order:

  1. prompts/system.md
  2. prompts/tools.md
  3. prompts/codemode.md, only when code_mode is enabled (capabilities.tools.code_mode.enabled) and not disabled
  4. optional generated subagent identity section
  5. prompts/skills.md
  6. generated dynamic AGENTS.md context files

Empty sections are skipped. Non-empty sections are joined with one blank line and the final prompt ends with \n.

Prompt structure:

<SYSTEM>
  Core magi-code behavior rules.
</SYSTEM>

<USER-SYSTEM>
  - operating system
  - terminal indicators
</USER-SYSTEM>

<Tools>
  General tool-use guidance; provider-native tool definitions are supplied separately.
</Tools>

<Subagent-Identities>
  Optional identity metadata when configured.
</Subagent-Identities>

<Available-Skills>
  - skill-name: frontmatter description
</Available-Skills>

<Additional-Context-Files>
  These files are automatically injected and MUST ALWAYS be remembered and considered in every action, do NOT read these files again:
  <Context File=/Users/example/.magi-code/AGENTS.md>
raw user instruction file
  </Context>
  <Context File=/repo/AGENTS.md>
raw repo instruction file
  </Context>
</Additional-Context-Files>

Template fragments

Bundled defaults live in prompts/. User overrides live in $MC_HOME/prompts/ or ~/.magi-code/prompts/ and are selected per fragment; missing overrides fall back independently to bundled defaults.

FragmentRoleVariables
system.mdCore assistant identity, global behavior, bounded runtime facts and session context.{{operating_system}}, {{terminal_environment}}, {{session_id}}, {{cwd}}
tools.mdGeneral built-in tool-use guidance; it does not enumerate tool definitions.runtime fact and session variables, {{SKILLS_LIST}}
codemode.mdcode_mode tool guidance; included only when code_mode is enabled.runtime fact and session variables, {{SKILLS_LIST}}
subagents.mdTemplate for generated subagent identity metadata.{{LIST_SUBAGENTS}} at generation site
skills.mdHuman-readable enabled skill list and skill-use rule.runtime fact and session variables, {{SKILLS_LIST}}
compact.md/compact summary instruction prompt, not part of normal system prompt.runtime fact and session variables

{{TOOLS_LIST}} is unsupported. A custom prompt fragment containing it fails fast as an unsupported variable.

Template variables are exact and case-sensitive. Extra whitespace inside braces is invalid. Unknown or malformed variables fail prompt construction with fragment name and offending token.

Runtime facts are local and bounded:

Session context is supplied by the owning run before provider work starts:

Child sessions bind their own ID and working directory without re-expanding instruction text or other inserted values. /system-prompt previews use the active session and working directory.

Dynamic AGENTS.md context

Instruction discovery is intentionally narrow and ordered:

  1. user file: $MC_HOME/AGENTS.md / ~/.magi-code/AGENTS.md
  2. repository file: active working directory AGENTS.md
  3. absolute readable UTF-8 .md files in knowledge.instructions.additional_markdown_paths, in array order

Discovered files are appended after tool, subagent, and skill sections inside <Additional-Context-Files>. Each file uses:

<Context File=PATH>
raw file content
</Context>

The delimiters identify injected files:

If no files are discovered, the prompt contains No AGENTS.md instruction files were discovered.

Tools in prompt vs provider schema

Tool-use guidance and tool definitions are separate surfaces:

SurfaceSourcePurpose
Prompt textBundled or overridden prompts/tools.md guidanceExplain how to use the bounded tool interfaces.
Provider-native tool descriptions and JSON schemasmvp_tool_definitions_json_with_subagents(...)Let the provider emit validated function/tool calls.

Tool names, descriptions, and schemas come from src/tools/capability.rs for provider requests. They are not copied into prompt text. Disabled tools are enforced in provider schemas and dispatch; the shared <Tools> guidance is not filtered.

Skills

Skill discovery reads local frontmatter but retains no body. The normal system prompt includes only enabled skill names and non-empty descriptions:

- review: Review code changes for correctness.
- zed-themes

Full skill content enters context only when the model calls read on skill://<name> or skill://<name>/<relative-reference>. This keeps the base prompt compact while listing available capabilities.

Skill root priority, highest last-write wins:

  1. $MC_HOME/skills
  2. absolute configured knowledge.skills.additional_paths in listed order
  3. repo .agents/skills

Discovery accepts direct <skill>/SKILL.md and one-level grouped <group>/<skill>/SKILL.md layouts.

Subagents

Subagent identity metadata is optional. When available, generated identity text is inserted between tools and skills. Child agent sessions receive the same prompt guidance; disabled tools narrow their provider schemas and dispatch without changing that guidance. A selected subagent profile appends its trimmed body in the same exact <Your-Role Persona=...> wrapper as a primary profile. The filename stem remains the selection/list id, while frontmatter name supplies Persona; nested selected profiles append after inherited ancestor wrappers. subagents tool calls return bounded aggregate parent-visible output; raw child transcript details stay in child sessions.

Provider request mapping

The constructed system prompt is stored as a system message in ProviderRequest conversation items, then mapped per provider API mode:

Provider API modeMapping
Chat completionsSystem prompt stays in messages[] as role system; non-system messages, tool calls, and tool results also remain in messages[]. Tool schemas use Chat format: { "type": "function", "function": { ... } }.
Responses API, custom providersAll system messages are joined with blank lines into top-level instructions; non-system conversation items go into top-level input. Tool schemas use Responses format: { "type": "function", "name": ..., "parameters": ... }.
OpenAI Codex ResponsesSame instructions + input split, with Codex defaults such as text.verbosity=low, reasoning insertion when supported, and parallel_tool_calls=true when tools are enabled.
Anthropic MessagesAll system messages are joined with blank lines into top-level system; user and assistant turns go into messages[]. Tool schemas use { "name", "description", "input_schema" }.
Claude subscriptionUses an Anthropic Messages body with host history and an mcp__magi__ tool-name prefix. Claude Code supplies authentication; magi-code executes tools. See Claude subscription.

Chat completions keeps each system message where it appears in the conversation. Responses, Anthropic, and Claude subscription merge every system message into one system text, so a later system message loses its position.

Prompt cache material includes provider id, model, system prompt, and conversation items, so changing templates, AGENTS.md, tools/skills text, or provider model changes cache identity.

Repeated read bodies

Provider requests replace later identical skill and local-file read bodies with references to earlier bodies still fully present in that request. Stored tool output and hash-edit snapshots remain unchanged. Rebuilding after compaction, rewind or replay restores full bodies when their earlier witnesses disappear.

Local-file witnesses require successful structured entries with complete and request_complete set, matching canonical path, selector and hashline tag, and byte-identical delivered bodies. Tags alone are not content identity: they are short, normalized hashes. The overlay preserves each <File path="..." tag="..."> wrapper and replaces only repeated section bodies. Raw reads, partial source reads, clipped replay, missing metadata and ambiguous call IDs retain full output. Mixed multi-path reads are handled per section.

Native Chat Completions histories currently retain full bodies: their call representation does not satisfy the overlay's unambiguous-call guard. Responses histories can use the overlay.

Only later occurrences change, keeping retained request prefixes stable. Shared limits are 256 witnesses, 4,096 candidate calls, eight sections per call and 1 MiB of owned replacement payloads; outputs without admitted evidence remain full. Code Mode inner results are not witnesses: its context items currently carry injected instructions or hook text, not structured read bodies. Arbitrary script return values are not parsed as trusted read evidence.

Customization points

Source map

BehaviorSource
Prompt section order, template loading, variable rendering, dynamic context delimiterssrc/agent/prompt.rs
Agent session prompt creation and primary-agent append hooksrc/agent.rs
AGENTS.md discovery ordersrc/instructions.rs
Bundled prompt textprompts/system.md, prompts/tools.md, prompts/codemode.md, prompts/skills.md, prompts/subagents.md, prompts/compact.md
Tool names, descriptions, provider schemassrc/tools/capability.rs
Skill discovery, frontmatter parsing, prioritysrc/skills.rs
Chat/Responses/Codex request bodiessrc/providers/openai.rs
Anthropic Messages request bodysrc/providers/anthropic.rs
Claude subscription projection, CLI launch, inert tool inventorysrc/providers/claude_projection.rs, src/providers/claude_subscription.rs, src/providers/claude_inert.rs
Related feature overviewdocs/features/instructions-prompts-skills-and-agents.md

Edit this page on GitHub โ†—