Skip to content

docs(context): define model-visible injection surfaces, ordering, authority, and evidence #194

Open

Description

@tt-a1i

docs(context): define model-visible injection surfaces, ordering, authority, and evidence

Summary

OpenPI does not need a second prompt assembler, MCP runtime, resource router, memory store, or keyword-based context router. Pi already owns prompt construction, resource loading, tool registration, Session context, provider serialization, and extension lifecycle. OpenPI owns only its handlers, active-tool filtering, child policy, package-specific projections, and UI.

What is missing is one documentation contract answering:

  • what may enter model-visible context;
  • when and in what order it enters;
  • whether it is always present or loaded on demand;
  • who owns execution authority versus text provenance;
  • how refresh, compaction, child creation, and provider serialization alter it;
  • what evidence can prove the provider-bound payload rather than merely an intermediate projection.

Fixed research baselines:

  • OpenPI 2a69d3f32994da4123f1312b7fa84ef3d6119be1
  • Pi @earendil-works/[email protected] / earendil-works/[email protected]
  • Codex a9e447a69dee4f2789dd8d8c776e314772c1f049
  • Hermes cbd8de8ad64530be01efea23b7764d5c37c634ed
  • Grok Build c2ad97f87aea4303b6000a2c22128bc91ee76c9b
  • Gemini CLI 812f7a2bcf20b6e80e2e50c3c8fa8e26567bc1e8
  • OpenCode 8615731d46153dd29b89e205fb55b2cc16205cb0
  • Claude Code: official rolling documentation only; implementation is proprietary.

Five source workstreams completed, covering seven grouped systems; no workstream failed.

1. Taxonomy

These mechanisms must not be collapsed into “the prompt”:

  1. Base system/developer instructions — host/provider-owned baseline behavior.
  2. Append-system instructions — explicit host/CLI/extension additions.
  3. Repository context files — AGENTS.md, CLAUDE.md, GEMINI.md, rules and imports.
  4. Skill catalog metadata — bounded discovery data such as name, description and location.
  5. Skill body/resources — full SKILL.md, references, scripts or assets loaded after selection.
  6. Tool metadata in the system prompt — prompt snippets/guidelines for active tools.
  7. Provider tool definitions — schemas transmitted separately from message text.
  8. Dynamic/deferred tool discovery — active-surface mutation or tool-search gateways.
  9. MCP server instructions — server-provided text, distinct from tools/resources/prompts.
  10. MCP tools — executable schemas and results.
  11. MCP resources — URI-addressed data read explicitly or through a client projection.
  12. MCP prompts — templates expanded into messages; not automatically system instructions.
  13. Files and attachments — user parts or tool results.
  14. Hook/extension contributions — system changes, custom messages, context rewrites and final payload rewrites.
  15. Memory/retrieval — durable or query-selected records, owned by memory: 研究 Project-scoped Durable Learning,并严格区分事实、经验与 Skill #167.
  16. Compaction summary/retained tail — lossy Session-context projection, owned by docs(context): compare compaction across Pi, Codex, Hermes, Grok, Claude, Gemini, and OpenCode #190.
  17. Child-specific prompt and resources — a fresh child projection, not the parent transcript.
  18. UI-only state — footer, dashboard, spinner, suggestion and rendered summaries; not model context unless explicitly serialized.

2. Authority is not placement

A text fragment can be placed in a system prompt and still originate from an untrusted repository, Skill, MCP server, tool result, memory record, or model summary.

model-visible role/placement ≠ content provenance ≠ runtime authority

Runtime permissions, tool allowlists, sandbox/approval policy, child capability intersection, Trust-gated resource loading, and extension ownership enforce authority. Tool schemas and prompt instructions can steer the model but cannot grant capabilities.

Pi Project Trust correction

Pi Project Trust gates project settings, .pi resources, packages and extensions. It is not a sandbox and does not restrict what writable tools can do after startup.

AGENTS.override.md, AGENTS.md, and CLAUDE.md are loaded regardless of Project Trust unless context loading is disabled. Consequently:

  • repository context can persuade the model to invoke writable tools with the Pi process’s authority;
  • it cannot grant Project Trust or widen a runtime allowlist;
  • Trust must not be documented as protection from repository prompt injection;
  • context provenance must remain visible even when its text occupies a high-priority prompt position.

Evidence: Pi security, v0.84.3.

3. Exact Pi/OpenPI pipeline

3.1 System prompt construction

For Pi 0.84.3, the relevant construction order is:

base system prompt
  + active-tool prompt snippets/guidelines
  + append-system text
  + context files
  + visible Skill catalog, only when `read` is active
  + cwd

Provider tool definitions are separate request fields; they are not simply another block inside the system string.

The Skill catalog is not unconditionally present. Pi injects only visible Skills and only when read is active. It contains discovery metadata; full SKILL.md content enters context only through read or /skill:name.

Evidence:

  • Pi Skills, v0.84.3
  • installed dist/core/system-prompt.js
  • installed dist/core/skills.js:250-298

3.2 Turn and provider hooks

After user input/template/Skill expansion constructs the current user message, Pi runs distinct mutation points:

  1. before_agent_start may append a custom message and/or change the system prompt;
  2. context may rewrite the message array before each model call;
  3. before_provider_request may rewrite the final provider-specific serialized payload;
  4. tool_result may rewrite tool output before it becomes later context;
  5. compaction/tree hooks may replace summaries or branch projections.

ctx.getSystemPrompt() observes an intermediate projection. It excludes later context and before_provider_request rewrites, so it cannot prove the final bytes submitted to a provider.

Evidence: Pi Extensions, v0.84.3, installed dist/core/agent-session.js:879-916, and installed dist/core/extensions/runner.js:737-803,837-886.

3.3 Tool registration and replacement

Pi tool precedence is explicit:

  1. built-ins are registered first;
  2. extension tools replace equal names in extension load order;
  3. SDK custom tools replace extension or built-in definitions.

A replacement owns its complete schema and prompt metadata; prompt snippets/guidelines are not inherited from the replaced built-in.

OpenPI capability groups mutate the active tool surface through Pi’s registration seam. In explicit mode no general loading gateway is permanently exposed; in adaptive mode only openpi_load_tools is. Activated capability groups remain monotonic for that Session, while state-owned tools may still appear/disappear with their actual lifecycle.

This is dynamic tool loading, not a universal provider-side tool-search protocol.

Evidence:

3.4 Pi has no built-in MCP

Pi 0.84.3 intentionally has no built-in MCP client. Therefore “MCP resources/prompts are Pi on-demand sources” is false. Any MCP integration is an extension/package and must document separately:

  • server instructions;
  • tool schemas and approvals;
  • resources and explicit reads;
  • prompt-template expansion;
  • connection/catalog refresh;
  • output bounds and provenance.

MCP tools, resources, prompts and server instructions are four distinct surfaces. A resource is not a tool schema; a prompt is not automatically injected resource content.

Evidence: Pi usage documentation, v0.84.3.

3.5 Compaction reinjection

Every request after compaction receives the current system prompt again, including currently loaded context files and visible Skill catalog, plus the compaction summary and retained messages.

Previously read Skill bodies, file contents and tool results are not independently reloaded just because compaction occurred. They remain available only if retained in recent messages, represented in the summary, or explicitly read again.

Evidence: Pi compaction, v0.84.3 and installed dist/core/session-manager.js:198-228.

3.6 Child projection

OpenPI children do not copy the parent projection or transcript. They create a fresh:

  • SettingsManager;
  • DefaultResourceLoader;
  • extension registry;
  • system prompt;
  • Pi AgentSession.

They inherit model/thinking defaults. Same-cwd Trust may reuse the parent’s resolved decision; alternate-cwd Trust is resolved separately and fails closed when unavailable. The role body is child-specific appended system text. Tools are the fail-closed intersection of parent authority, child-safe package classification, role narrowing and post-start preflight.

Evidence:

4. Cross-system comparison

4.1 Codex

At the fixed revision, Codex constructs context from base instructions, contextual developer fragments, world-state sections, history/current input and model-visible tool definitions. Important differences from Pi include:

  • AGENTS.md is collected from project root to cwd with provenance and project_doc_max_bytes;
  • Skill snapshots distinguish catalog/metadata from selected full bodies;
  • ToolRouter determines model-visible specifications for each step;
  • step context binds environment, permissions, sandbox, MCP projection and tool router for that sampling step;
  • required MCP servers and catalogs are refreshed from current mentions/plugins/environment/capability roots;
  • memory and compaction are separate extension/context paths;
  • child/fork prompt history is controlled explicitly and all agents share the workspace filesystem.

MCP tools are demonstrably registered in the tool router. The fixed source does not justify saying every MCP resource, prompt or server instruction is automatically injected.

Provider serialization remains authoritative: Responses may use the instructions field or developer-prefixed input depending on route/model compatibility.

Primary source: Codex fixed tree.

4.2 Claude Code

Official rolling documentation establishes:

  • CLAUDE.md, local files, rules and imports as persistent context sources;
  • Skill descriptions for discovery and full bodies loaded progressively;
  • MCP tools/resources/prompts as distinct operations;
  • hook output that may contribute model context;
  • independent subagent context rather than automatic parent-transcript copying;
  • auto memory and compaction as separate mechanisms.

It does not publish the complete prompt assembler, exact hidden ordering, per-section budgets, internal Tool Search adoption, or every refresh rule. Anthropic’s Tool Search API is a provider capability; it must not be attributed to Claude Code without a product contract.

Sources:

4.3 Hermes

Hermes explicitly divides its system prompt into stable, context and volatile tiers:

stable identity/tool/execution guidance
  -> caller/workspace/project context
  -> Skills index, memory/profile snapshots, plugin and runtime metadata

Notable mechanisms:

  • project context supports Hermes, AGENTS, CLAUDE and Cursor conventions with first-match priority, scanning and truncation;
  • Skills use a compact index; full bodies/references load through skill_view;
  • compaction can prune loaded Skill results and emits reload markers;
  • external memory prefetch modifies only the API copy of the current user message, leaving stored user content clean;
  • memory-provider context is bounded and its static instructions are distinct from recalled data;
  • its MCP transport exposes tools, but the fixed source does not establish generic MCP resources/prompts as automatic context.

Source: Hermes fixed tree.

4.4 Grok Build

Grok Build demonstrates genuine deferred MCP tool discovery:

  • stable built-ins search_tool and use_tool search and invoke namespaced server tools;
  • all server tool schemas need not occupy the ordinary active surface;
  • /mcps can change server/catalog state;
  • MCP output is bounded and full payloads spill to Session artifacts.

Its fixed docs/source also distinguish:

  • project instructions preserved as structured compaction items;
  • Skill catalog metadata versus invoked full body, with source provenance and hot reload;
  • bounded first-turn/post-compaction memory retrieval;
  • child-specific persona/tool context and explicit MCP inheritance modes;
  • automatic announcement deduplication after compaction.

The source proves MCP tool search, not automatic model injection of MCP resources, prompts or server instructions.

Sources:

4.5 Gemini CLI

At the fixed revision:

  • global/workspace/ancestor GEMINI.md and trusted-root just-in-time context are distinct tiers;
  • imports expand into hierarchical context and /memory reload refreshes them;
  • Skill metadata is present for discovery; activate_skill loads body/folder context after visible consent;
  • MCP initialization instructions, tools, resources and prompts use different routes;
  • resources enter context through explicit URI/read operations;
  • MCP prompts are exposed as commands and expanded into prompt messages;
  • attachments use multimodal content parts;
  • subagents have independent loops/tool sets and may own inline MCP servers;
  • compaction/tool-output distillation and auto memory remain separate systems.

Unlike Pi, Gemini applies trusted-folder rules to project/JIT memory loading. That product-specific Trust behavior must not be generalized across agents.

Sources:

4.6 OpenCode

The fixed source builds a dynamic per-turn system array and tool surface:

  • global/project AGENTS.md with Claude fallback;
  • configured local globs and remote instruction URLs;
  • nearby rules loaded once per assistant message when files are read;
  • Skills catalog plus a Skill loading tool;
  • permission-filtered MCP instructions and tools;
  • plugin hooks capable of transforming system/messages;
  • provider-aware attachment/tool-result handling;
  • compaction plugins and pruning.

Remote instructions and plugin transforms are especially important provenance boundaries: their placement in system text does not make their source trusted.

The fixed tree does not establish a general provider-side Tool Search protocol or a distinct durable-memory subsystem.

Sources:

5. Cost, refresh and invalidation contract

Documentation should classify every source as one of:

  • conditionally always present: base/append system, loaded context files, visible Skill catalog, active tool schemas;
  • turn-triggered: current user input, attachment, before_agent_start, contextual rules;
  • request-triggered: context, memory/retrieval, provider rewrite;
  • tool-triggered: file/resource reads and tool results;
  • lifecycle-triggered: reload, Trust resolution, capability activation, MCP reconnect, compaction, fork/child creation.

No static token table should be promised across providers. Instead document bounded units and observables:

  • characters/bytes before serialization;
  • active tool count and schema fingerprint;
  • context-file/Skill catalog sources;
  • loaded Skill body/resource IDs;
  • message/result truncation;
  • provider-reported input/cache usage after the request.

Refresh rules must state whether changes require /reload, a new Session, a new child, MCP reconnect, a new request, or explicit re-read. “File changed on disk” does not universally imply the current model projection changed.

6. Observability and evidence

These are useful but insufficient individually:

  • getSystemPrompt();
  • startup header/resource list;
  • active tool roster;
  • Skill/MCP catalog;
  • context usage counters;
  • request/resource/cache fingerprints;
  • UI footer/dashboard;
  • provider usage totals.

They cannot prove what the model saw because later hooks or provider adapters may alter the request, and they cannot prove model attention or compliance.

A terminal capture at the client’s provider boundary can prove the bytes, request metadata, tool definitions and attachments the client submitted. It still cannot prove provider acceptance without a response, provider-internal rewriting, model attention, or causal use.

Sensitive captures must store hashes/shape/provenance by default, not raw prompts, credentials, attachments, memory text or MCP payloads.

7. Relationship to existing Issues

This Issue is documentation-only and owns no implementation seam:

  • #169 owns external Browser/Web/GitHub/Computer/Security Provider seams and any future MCP/provider inventory.
  • #157 owns recoverable, source-labelled resource references.
  • #167 owns durable memory/retrieval.
  • #190 owns compaction and context-pivot comparison.
  • #156 owns prompt-cache diagnostics and cache-boundary UI.
  • #193 owns Session/replay lifecycle terminology.

This contract supplies only taxonomy, ordering, provenance, authority, cost classes, refresh semantics and evidence limits.

8. Minimal Pi-native recommendation

  1. Add one documentation inventory of model-visible sources and lifecycle triggers.
  2. Keep prompt assembly, Sessions, Trust, Skills, tool registration and provider serialization in Pi.
  3. Keep OpenPI capability decisions model-driven; do not add a keyword router or fixed orchestration state machine.
  4. Reuse before_agent_start, context, before_provider_request, tool_result, resource discovery, active-tool filtering and child-session construction.
  5. Document MCP only at an extension/provider seam; do not add MCP to OpenPI core.
  6. Preserve catalog/body progressive disclosure for Skills and tools.
  7. Record provenance and sanitized fingerprints, not raw sensitive context.
  8. Add no runtime implementation unless this documentation exposes a concrete contradiction.

9. Non-goals

  • No second prompt assembler or instruction precedence engine.
  • No OpenPI-owned MCP client/server catalog.
  • No generic resource router.
  • No provider-neutral Tool Search abstraction.
  • No automatic loading of all Skill bodies or MCP resources.
  • No Trust change that suppresses Pi context files by default.
  • No claim that prompt placement makes repository/MCP/tool/memory content trusted.
  • No durable-memory, compaction, cache-diagnostic or replay implementation here.
  • No raw provider-payload logging by default.
  • No attempt to infer model attention from telemetry.
  • No UI state promoted into model context or execution truth.

10. Unknowns

  • Exact provider-specific system/developer/user serialization after Pi adapters.
  • Final ordering when multiple extensions mutate the same system/messages/payload stages.
  • Provider-specific support and billing for deferred tool definitions.
  • Generic MCP resources/prompts/server-instruction behavior, because Pi has no built-in MCP.
  • Claude Code’s private prompt assembler and Tool Search internals.
  • Full Grok project-instruction discovery details outside the inspected shell/docs paths.
  • Exact hot-reload behavior for every live Skill/context source.
  • Provider-internal request rewriting and whether any model attended to injected content.

11. Acceptance criteria

Activity

  1. added
    documentation
    on Aug 25, 2026
  2. 627150795 commented on Aug 28, 2026

    @627150795
    Contributor

    Hi! I would like to work on this documentation issue.

    I will produce a focused OpenPI/Pi context contract covering model-visible source classes, injection order, timing, provenance, authority, refresh/compaction/child-session effects, and provider-boundary evidence. I will keep comparisons bounded, preserve ownership for the related issues, and add no second prompt assembler, MCP stack, memory store, or router.

  3. 627150795 commented on Aug 28, 2026

    @627150795
    Contributor

    Update: I completed the documentation-only implementation for this issue.

    • PR: docs(context): define model-visible context contract #248
    • Commit: b9fcaac
    • Validation: git diff --check, bun run lint, and bun run typecheck passed.
    • Scope: 18 model-visible context source classes, Pi/OpenPI injection order, Trust and provenance boundaries, Skill/tool/MCP distinctions, hook and provider-boundary evidence, compaction/branch/child effects, refresh/cost classes, and bounded cross-system comparison.
    • No runtime code, tool behavior, storage behavior, or provider serialization changed.

    The earlier comment is the public record that I was working on this issue.

  4. tt-a1i commented on Sep 9, 2026

    @tt-a1i
    CollaboratorAuthor

    2026-09-09 源码对照(OpenPI a9b40f0;Pi 6160683 / 0.85.1)。官方 extras + 社区 rewriter clone 到 /tmp,未 pi install,未运行。

    #194 的第 14 类「Hook/extension contributions」需要再拆一层,否则会把四条不同生命周期写成「改写 prompt」:

    1. input transform / handled(官方 input-transform.ts):本地改写或短路。transform 之后才 skill/template 展开;不能再变成扩展命令,能变成 /skill:。无隐藏模型。
    2. Skill 目录 vs /skill:name:目录是 system prompt 元数据(有 read 才出现);/skill: 在 input 之后急切展开进用户消息。这是 Pi 已有表面,不是正文缓存,不要重开 Skill 正文该何时加载、压缩后如何恢复?Claude Code / Codex / OpenCode / Hermes 调研与 OpenPI 建议 #324。
    3. 官方 /handoff 草稿:modelRegistry.complete(cacheRetention: none)+ ui.editor + newSession + setEditorText。编码 agent 等用户提交。context: 研究可回收的探索 checkpoint/rewind,不把它等同于 context_pivot #154 / docs(session): define lifecycle, recovery, replay, and side-effect boundaries #193 / /plan fresh 已占用新会话缝。
    4. Sidecar complete():dodo-reach/pi-clarify 1.0.1、@rukaachan/pi-clarify 1.1.0、Talk-like-a-pro 0.2.0(git-only)。不经 AgentSession.prompt,不进 Session 用户消息,也多半不经 agent-loop 的 before_provider_request。getSystemPrompt() / footer message.usage 证明不了这些字节。草稿派(clarify / handoff)把权威留在 Enter;Talk-like-a-pro 的 transform 会让主 agent 立刻跑扩展发明的任务书——Ignore。

    同名陷阱:@dkmnx/pi-clarify 0.3.0 的 /clarify 是开关,机制是常驻 system-prompt 强制门 + clarify_prompt 工具,靠近 #499,不是发送前改写。

    本票继续做文档合同即可。不要第二套 assembler,不要 OpenPI 默认 rewriter。

    记录:docs/research/EXPERIMENT_INPUT_TRANSFORM_2026-09-09.md(本地 draft)。

  5. tt-a1i commented on Sep 9, 2026

    @tt-a1i
    CollaboratorAuthor

    结论

    社区 pi-antiloop 1.5.1 的 force-break 是第 14 类 mid-run 注入,不是新 Ideas。可学的只有「相同工具 + 相同结果指纹则不算 progress」;不要把反循环散文、Footer、/antiloop 收进 OpenPI。

    事实(源码,未 pi install)

    • npm [email protected] / gitHead b2258fc。检测在 turn_end。resultFingerprint = ok|/err| + 规范化结果尾 400 字。两边都有指纹且不够像 → 否决 tool-loop。缺一边指纹则退回只比 argv。
    • warn 只 notify。force 用 pi.sendUserMessage(..., { deliverAs: "steer" }) 在下一轮 LLM 前塞一段反循环说明。README「追加到最后一条 assistant」与源码不符。
    • setStatus("antiloop", …) / 可选整槽 Footer 是第 18 类 UI-only。interactiveFooter 源码默认关(README 示例仍写 true)。OpenPI Footer last-wins。
    • 本树 Goal steer、setup / pivot followUp 是包拥有的明确动作,不是启发式循环检测。

    建议

    本票继续只做注入面合同。把这条 steer 标成「extension 在 turn_end 往用户通道塞字」。不要第 19 类 loop-break instructions。不要 Wrap。

    记录:docs/research/EXPERIMENT_ANTILOOP_2026-09-09.md(本地 draft)。何时 abort 一轮见 #193。#159 是并发 lease,不是本条。

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

    documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions