Skip to content

[Refactor] system prompt construction: section registry + variant strategies #2827

Closed

Description

@VascoSch92

Context

Studying how Claude Code, Codex, and Gemini CLI build their system prompts exposed a clean 5-layer model. Mapping it back to our SDK shows which layers we already have, which are partial, and which are missing. Two open issues — #1317 (interactive vs non-interactive defaults) and #85 (bash vs powershell) — are symptoms of the layers we haven't built yet.

Reference: Claude Code's layering

Layer Purpose Claude Code Our SDK today
1. Priority Resolver pick which prompt variant applies (override > coordinator > agent > custom > default) buildEffectiveSystemPrompt() (utils/systemPrompt.ts:41) missing — one default prompt, variation is {% if %} inside the template. Overlaps with the existing "different prompt per launch mode" issue.
2. Content Factory produce each section's text named section producers + systemPromptSection() registry (constants/systemPromptSections.ts:20) partial — Jinja {% include %} + AgentContext.get_system_message_suffix() act as a factory, but there is no typed Section unit.
3. Assembly / cache split join sections, mark static vs dynamic for prompt caching SYSTEM_PROMPT_DYNAMIC_BOUNDARY + splitSysPromptPrefix() (utils/api.ts:321) partial — SystemPromptEvent.to_llm_message() already emits two TextContent blocks with cache_prompt flags (event/llm_convertible/system.py:72). Boundary is implicit (whichever function produced it), not declared per-section.
4. CLAUDE.md / project docs loading inject repo instructions as a user-role <system-reminder>, not in the system block context.ts:170 → api.ts:463 partial — AGENTS.md is loaded, but the framing/preamble and the user-role injection pattern are worth adopting.
5. Auto-memory persistent cross-conversation memory with typed entries (user / feedback / project / reference) memdir/memdir.ts:419 loadMemoryPrompt() missing.

This issue proposes the refactor for Layers 2 + 3 (unblocks #85 and #1317). Layers 1, 4, 5 are tracked as separate follow-up issues — see the end.

Problem

Today's prompt:

  • Lives in openhands-sdk/openhands/sdk/context/prompts/templates/system_prompt.j2.
  • Rendered by AgentBase.static_system_message (agent/base.py:219) + AgentContext.get_system_message_suffix (agent_context.py:178) via render_template() (context/prompts/prompt.py:88).
  • Varies by {% if %} branches and {% include "model_specific/..." %}.
  • Shell-specific language is hand-patched by a regex helper:
def refine(text: str) -> str:
    if sys.platform == "win32":
        text = re.sub(r"\bexecute_bash\b", "execute_powershell", text, flags=re.IGNORECASE)
        text = re.sub(r"(?<!execute_)(?<!_)\bbash\b", "powershell", text, flags=re.IGNORECASE)
    return text

This does not scale. Every new axis (model × platform × interaction mode × repo × tools) multiplies conditionals inside one template. Per-section cache-hit measurement is impossible. Section-level unit tests require a Jinja environment.

Proposal

Introduce a typed PromptSection unit, a PromptRegistry that assembles sections, and variant strategies that select section content from a single PromptContext. Keep Jinja only at leaf bodies. Sections stay synchronous — any I/O is resolved into PromptContext before assembly.

context/prompts/section.py (new)

from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Literal, Protocol

class Platform(str, Enum):
    POSIX = "posix"
    WINDOWS = "windows"

class InteractionMode(str, Enum):
    INTERACTIVE = "interactive"
    NON_INTERACTIVE = "non_interactive"

class ModelFamily(str, Enum):
    ANTHROPIC = "anthropic"
    OPENAI = "openai"
    GEMINI = "gemini"
    OTHER = "other"

CacheTier = Literal["static", "dynamic"]

@dataclass(frozen=True)
class PromptContext:
    model_family: ModelFamily
    platform: Platform
    interaction_mode: InteractionMode
    tool_names: frozenset[str]
    cwd: Path
    now: datetime
    repo_skills: tuple[str, ...] = ()
    available_skills: tuple[str, ...] = ()
    secret_names: tuple[str, ...] = ()
    enable_browser: bool = False
    custom_suffix: str | None = None

class PromptSection(Protocol):
    name: str
    cache_tier: CacheTier
    def guard(self, ctx: PromptContext) -> bool: ...
    def render(self, ctx: PromptContext) -> str | None: ...

context/prompts/registry.py (new)

from .section import PromptContext, PromptSection

class PromptRegistry:
    def __init__(self) -> None:
        self._sections: list[PromptSection] = []

    def register(self, section: PromptSection) -> None:
        if any(s.name == section.name for s in self._sections):
            raise ValueError(f"duplicate section: {section.name}")
        self._sections.append(section)

    def replace(self, section: PromptSection) -> None:
        self._sections = [s for s in self._sections if s.name != section.name]
        self._sections.append(section)

    def build(self, ctx: PromptContext) -> tuple[str, str]:
        """Return (static_block, dynamic_block) — maps 1:1 to SystemPromptEvent."""
        static_parts, dynamic_parts = [], []
        for s in self._sections:
            if not s.guard(ctx):
                continue
            body = s.render(ctx)
            if not body:
                continue
            (static_parts if s.cache_tier == "static" else dynamic_parts).append(body)
        return "\n\n".join(static_parts), "\n\n".join(dynamic_parts)

context/prompts/sections/shell.py (new — closes #85)

from ..section import PromptContext, Platform

class ShellGuidanceSection:
    name = "shell_guidance"
    cache_tier = "static"

    def guard(self, ctx: PromptContext) -> bool:
        return bool(ctx.tool_names & {"execute_bash", "execute_powershell"})

    def render(self, ctx: PromptContext) -> str | None:
        if ctx.platform is Platform.WINDOWS:
            tool, shell = "execute_powershell", "PowerShell"
        else:
            tool, shell = "execute_bash", "bash"
        return (
            f"## Shell\n"
            f"Use the `{tool}` tool to run {shell} commands. "
            f"Paths and quoting must follow {shell} conventions."
        )

refine() is deleted. The prompt describes the actually-bound tool, so it cannot drift.

context/prompts/sections/efficiency.py (new — closes #1317)

from ..section import PromptContext, InteractionMode

class EfficiencySection:
    name = "efficiency"
    cache_tier = "static"

    def guard(self, ctx: PromptContext) -> bool:
        return True

    def render(self, ctx: PromptContext) -> str | None:
        if ctx.interaction_mode is InteractionMode.INTERACTIVE:
            return (
                "## Efficiency\n"
                "- The user is waiting. Finish the task and stop.\n"
                "- Do not re-verify work that already succeeded.\n"
                "- Do not produce a written report unless asked.\n"
                "- Final message: one or two sentences on what changed."
            )
        return (
            "## Thoroughness\n"
            "- Verify results before declaring success.\n"
            "- Summarize what changed and why at the end of the turn."
        )

InteractionVariant should also own VerificationPolicySection and FinalMessageFormatSection — the specific sentences in today's PROBLEM_SOLVING_WORKFLOW / VERSION_CONTROL templates that drive the over-verification reported in #1317. Porting those is part of this work; a flag alone will not change model behavior.

context/prompts/default_registry.py (new)

def build_default_registry() -> PromptRegistry:
    r = PromptRegistry()
    # static tier
    r.register(PreambleSection())
    r.register(CoreMandatesSection())
    r.register(EfficiencySection())           # #1317
    r.register(ShellGuidanceSection())        # #85
    r.register(FileSystemSection())
    r.register(VersionControlSection())
    r.register(ProblemSolvingSection())
    r.register(SecuritySection())
    r.register(BrowserSection())              # guard: ctx.enable_browser
    # dynamic tier
    r.register(DateTimeSection())
    r.register(RepoContextSection())
    r.register(AvailableSkillsSection())
    r.register(CustomSuffixSection())
    return r

agent/base.py — edit

# agent/base.py:219 (static_system_message) and :256 (dynamic_context)
def static_system_message(self) -> str:
    static, _ = self._prompt_registry.build(self._build_prompt_context())
    return static

def dynamic_context(self) -> str:
    _, dynamic = self._prompt_registry.build(self._build_prompt_context())
    return dynamic

SystemPromptEvent.to_llm_message() (event/llm_convertible/system.py:72) is untouched — it still emits two TextContent blocks with cache_prompt=True/False. The registry's (static, dynamic) tuple maps 1:1 onto them, so Layer 3's cache behavior is preserved, but now declared per-section instead of implicit.

Deletions

  • refine() and its call sites.
  • context/prompts/templates/system_prompt.j2 (after all sections are ported).
  • The variant templates system_prompt_interactive.j2 / system_prompt_long_horizon.j2 / system_prompt_planning.j2 / system_prompt_tech_philosophy.j2 — these become InteractionVariant / workflow-mode strategies instead of parallel template files.

Tests (tests/context/prompts/)

def test_shell_section_posix_vs_windows():
    posix = ShellGuidanceSection().render(_ctx(platform=Platform.POSIX,
                                                tool_names=frozenset({"execute_bash"})))
    win   = ShellGuidanceSection().render(_ctx(platform=Platform.WINDOWS,
                                                tool_names=frozenset({"execute_powershell"})))
    assert "execute_bash" in posix and "PowerShell" not in posix
    assert "execute_powershell" in win and "bash" not in win

def test_efficiency_interactive_is_terser():
    i = EfficiencySection().render(_ctx(mode=InteractionMode.INTERACTIVE))
    n = EfficiencySection().render(_ctx(mode=InteractionMode.NON_INTERACTIVE))
    assert len(i) < len(n)

def test_registry_cache_tier_split():
    r = build_default_registry()
    static, dynamic = r.build(_ctx())
    assert "current_datetime" not in static.lower()
    assert "## Efficiency" in static or "## Thoroughness" in static

def test_snapshot_default_prompt_matches_current_template():
    # Regression guard during migration.
    ...

Benefits

  • A/B testing becomes trivial. Sections are first-class values. Swapping EfficiencySection for an EfficiencyV2Section via registry.replace(...) is one line, gated by a flag. Today this requires editing system_prompt.j2, shipping a build, and having no clean way to compare the two rendered outputs side by side. Snapshot diffs between variants fall out for free.
  • Per-section unit testability. Each PromptSection is a pure sync function of PromptContext. Tests assert on the rendered string directly — no Jinja env, no filesystem loader, no render_template() bootstrap. This is currently impossible; the smallest testable unit is the whole template.
  • Cache behavior is declared, not implicit. cache_tier lives on the section, so the static/dynamic split is auditable by reading the registry. Today the split is "whichever function produced this block," which drifts silently when someone adds dynamic content to a static path (cache-miss regression, no signal).
  • No more post-render regex hacks. refine() works by string-rewriting a rendered prompt — it breaks the moment a section legitimately mentions "bash" for an unrelated reason. Variant strategies remove the class of bug entirely.
  • Combinatorial variants stay readable. model_family × platform × interaction_mode × tools is a matrix. As {% if %} branches inside one template it becomes unreadable by the third axis. As small section classes with guards it stays flat.
  • Tool-prompt drift is impossible. ShellGuidanceSection describes the tool actually bound in ctx.tool_names. Rename execute_bash → execute_shell and the prompt follows automatically. Today the tool name is hardcoded in prose.
  • Measurable cache-hit rate per section. With cache_tier on each section we can emit metrics of the form prompt.section.<name>.bytes split by tier, making it obvious which section is pushing content into the dynamic tier and costing cache hits.
  • Safer refactors. Snapshot tests per section + a default-prompt regression snapshot mean a section port is mechanically verifiable. Today porting anything out of system_prompt.j2 requires manual diffing of a 150-line rendered string.
  • Cleaner extension point for downstream users. Consumers of the SDK can registry.replace(EfficiencySection(), MyEfficiency()) from their own code. Today the only override path is a full template replacement via GEMINI_SYSTEM_MD-style env var, which loses all other sections.
  • Unblocks Layers 1, 4, 5. The priority resolver (Layer 1), AGENTS.md preamble injection (Layer 4), and auto-memory (Layer 5) all want a typed Section to hand to the assembler. Landing this refactor first means those issues each become small additions instead of each inventing their own assembly story.

Migration plan

  1. Land PromptSection, PromptContext, PromptRegistry alongside existing template — no behavior change.
  2. Port sections one by one from system_prompt.j2 into registered sections with a snapshot test per port against the currently-rendered default output.
  3. Land ShellGuidanceSection, delete refine() — closes #85.
  4. Land InteractionVariant (Efficiency + VerificationPolicy + FinalMessageFormat) behind config flag with a snapshot diff against non-interactive — closes Consider different default prompts for interactive vs non-interactive agents #1317.
  5. Retire system_prompt.j2 and the four workflow-variant .j2 files.

Acceptance criteria

  • PromptSection, PromptContext, PromptRegistry landed.
  • AgentBase.static_system_message / dynamic_context route through the registry; SystemPromptEvent two-block cache behavior unchanged by inspection + tests.
  • refine() removed; #85 closed.
  • Interactive variant produces a measurably terser prompt; non-interactive snapshot unchanged; Consider different default prompts for interactive vs non-interactive agents #1317 closed.
  • system_prompt.j2 and system_prompt_{interactive,long_horizon,planning,tech_philosophy}.j2 removed.
  • Section-level unit tests run without a Jinja environment.

Activity

  1. added
    enhancement
    proposal
    and removed on Apr 14, 2026
  2. changed the title [-]Refactor system prompt construction: section registry + variant strategies[/-] [+][Refactor] system prompt construction: section registry + variant strategies[/+] on Apr 14, 2026
  3. VascoSch92 commented on Apr 23, 2026

    @VascoSch92
    MemberAuthor

    Follow-up: measured cache state, and why Layer 3 matters in dollars

    Traced the full request path. Measured, default Agent + default tools, Sonnet 4.5:

    tools              5,567 tok   ← cache hash starts here (no breakpoint on tools)
    system.content[0]  2,797 tok   ← cache_control: ephemeral (5m, no ttl set)
    system.content[1]     34 tok   ← dynamic_context, NOT cached
    

    Cached prefix total: 8,364 tok, of which 67% is tool definitions. Cache markers applied: only llm.py:1333,1337 (block 0) and llm.py:1342-1344 (last user/tool msg). That's 2 of Anthropic's 4 breakpoints.

    Is current_datetime breaking the cache today?

    No. It defaults to datetime.now() at agent_context.py:91-92 with microsecond precision, but it lives in block 1, which llm.py:1334 explicitly leaves uncached. Anthropic hashes up to the breakpoint, so block 1 doesn't affect block 0's hit rate. Cost today: ~25 tokens of uncached input per call.

    Why Layer 3 still matters

    Today's split ("whichever function produced this block") is convention, not invariant. Any contributor adding {{ current_datetime }} into system_prompt.j2 — or any other turn-varying data — invalidates the full 8,364-token cached prefix. At Anthropic's (1.25× − 0.1×) spread that's ~$0.029/conv on Sonnet 4.5, ~$0.15/conv on Opus 4.7. A typed cache_tier per section makes this test-enforceable instead of review-time folklore.

    Latent determinism bugs to fix alongside

    Won't bite today (block 1 uncached) but will the moment we add a dynamic-tier breakpoint:

    • utils.py:251 — Path.iterdir() unsorted
    • utils.py:272 — Path.rglob("*.md") unsorted

    Skill order drifts across machines/filesystems. Wrap both in sorted().

    Hidden issue worth flagging

    Anthropic's cache key is tools → system → messages. Tools are 67% of our cached prefix. Any tool-set variance across conversations (browser on/off, MCP set, custom tools) invalidates the whole prefix even with a byte-identical system prompt. Single-agent-config deployments are fine; heterogeneous ones leak. Worth measuring.

    Near-term companions to the refactor (all small, independently landable)

    1. Surface cache-hit-rate on Metrics — telemetry.py:218-236 already reads the fields. Every cache decision is unvalidatable without this.
    2. Sort the two fs walks (utils.py:251,272) and the skill/secret lists in agent_context.py:151,243.
    3. Round current_datetime to minutes at agent_context.py:169 — defensive, one line.
    4. CI snapshot test on static_system_message asserting no timestamps / paths / hostnames — catches the regression this refactor structurally prevents.

    Anthropic facts worth pinning

    • Max 4 breakpoints; pricing 1.25× / 2× / 0.1× for 5m-write / 1h-write / read.
    • Cache isolation moved to workspace-level on 2026-02-05 (already in effect).
    • Min cacheable prefix: 1,024 tok Sonnet 4.5, 4,096 tok Opus 4.7.
  4. added
    behavior-initiative
    on Apr 23, 2026
  5. enyst commented on Apr 23, 2026

    @enyst
    Member

    Anthropic's cache key is tools → system → messages. Tools are 67% of our cached prefix. Any tool-set variance across conversations (browser on/off, MCP set, custom tools) invalidates the whole prefix even with a byte-identical system prompt.

    This is also on topic in:

  6. juanmichelini commented on Jun 9, 2026

    @juanmichelini
    Collaborator

    @VascoSch92 love this! I would add a 6th layer: "model specific instructions"
    We can use the index data to get good tweaks for particular models.

  7. enyst commented on Jun 11, 2026

    @enyst
    Member

    The original issue says “study how Claude Code, Codex, and Gemini CLI build their system prompts“, but I see only Claude Code? 😂

    I think we may need some flexibility for other LLM families. IIRC GPT-x models already have a different prompt when running on subscription. 🤔 Moreover, we have a section per model family, but a single section when the rest is included is actually not going to cover much. Yet another detail, sorry for writing on the fly, is the task tracking tool: GPT-x have their own, and its instruction partially overlaps with our system prompt from what I remember.

    Are we able to load each system prompt section per LLM family, WDYT? At least a few main ones. @VascoSch92

  8. VascoSch92 commented on Jun 11, 2026

    @VascoSch92
    MemberAuthor

    The original issue says “study how Claude Code, Codex, and Gemini CLI build their system prompts“, but I see only Claude Code? 😂

    I studied them, but then Codex and Gemini were not that interesting, so there's no need to include them here. :-)

    Moreover, we have a section per model family, but a single section when the rest is included is actually not going to cover much.

    What do you mean by the rest?

    Actually, you can easily create a specific system prompt per model and/or model family, or however you prefer. At the end of the day, the registry just pieces together different sections, and a system prompt is simply a sequence of those sections. So, you just need a constructor to give the registry the right sequence of sections. Instead of only having build_default_registry, you can have build_MODEL_A_registry, where you can either reuse existing sections or add new ones.

    Yet another detail, sorry for writing on the fly, is the task tracking tool: GPT-x have their own, and its instruction partially overlaps with our system prompt from what I remember.

    This can be resolved with having a build_GPT_registry().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    behavior-initiativeenhancementproposal

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions