Instructing long-running agents

In a long-running agent, every instruction has one right home and one right moment. Three things decide both: how much attention its position gets, what it governs, and how often it changes. The start and end of the context get the most attention, and the middle fades as the context grows.

  • Agents
  • Harness Engineering
  • Context Engineering

Where things go

System prompt
rules for the whole session, including rules that span several tools. Nothing task or tool specific.
Tool description
whether and how to call one tool (purpose, when to use it, what it returns, side effects).
Field description
how to fill one parameter (format, units, where the value comes from).
Initial user message
this request's material, task and instructions.
Tool results
informing the model about the result of the call as well as any specific instructions or updates for the overall task.

How to order

  1. Prerequisites before dependents. Each token is processed only in light of what came before it, so define, frame and show before you ask.
  2. General before specific. Role and purpose first, the exact question last.
  3. Static before dynamic. System prompt, then tools, then per-session context. Providers cache the longest unchanged prefix.
  4. Important things at the edges. Standing rules at the start, the ask and the current status at the end, nothing critical in the middle of a long context.

What to add and what not to add

Put in context up front only what most tasks need, avoid adding specific instructions that are only relevant for some task. Either add them based on a fixed set of prerequisites, passed in as flags or make them discoverable through tools.

Attention: the start and the end carry the weight

Models don't weigh every part of the context equally. Information near the start and near the end is used most reliably; information in the middle is used least, and the gap widens as the context grows.

This has five consequences for prompt design:

  1. The start is for standing rules. Role, principles and cross-tool rules are well placed in the system prompt and tool definitions: they are always at the start, however long the session runs.
  2. The end is for the ask and the current state. The question, the current plan and anything the model must act on next belong in the most recent message or tool result.
  3. The original task drifts into the middle. After thirty tool calls, the user's first message is buried. In long agent loops, restate the goal and progress near the end, for example as a short status block in recent tool results.
  4. Every token added to the middle dilutes it. Large tool results and pasted documents push everything else apart. Return only what's needed, paginate, and put bulky output in a file the model can open on demand.
  5. Context is a budget, not a store. More context costs money and latency and makes each part of it less reliable. The question is not "could this help?" but "does this task need it now?" That is the subject of the next section.

What to show up front vs. what the model can discover

The model must know that discoverable material exists, so keep a short index of it in context. Load up front only what most requests need, and make the rest discoverable. Load it up front when any of these hold:

Make it discoverable when:

The easiest way to do this is to create a file system (virtual or mounted to a real one), give the model the file tree and ways to open the files.

Progressive disclosure

The pattern that makes this work has three levels:

  1. Always in context: a name and a one-line description per document.
  2. Loaded when the task matches: the full instructions.
  3. Loaded when a step needs it: supporting files, templates, scripts.

The one-line description does the same job as a tool description: it is what the model reads when deciding whether to load the rest. Write it as what it covers plus when to use it ("Deck building skill: layouts and chart rules. Read before creating any slides").

Discovery has costs: an extra round trip, and the chance the model doesn't look. Name the trigger explicitly in the index for anything where a miss is expensive, and move it up front if misses keep happening.

The system prompt

The system prompt holds everything that is true for every request in the session: who the model is, what it is for, how it works, and the rules that span tools.

Parts of the system prompt, in order

Part What goes in
Role Who the model is, for whom, in one or two sentences
Context Stable facts needed to interpret everything after: product, audience, domain terms, environment
Task / objective The standing goal and what success looks like across the session
Workflow The phases the model should move through, in order
Principles and rules Judgment calls and constraints, each with its reason
Cross-tool guidance Rules that involve more than one tool: sequencing, choosing between tools, parallelism, confirmation policy, recovery after errors
Output and communication Format, length, tone, progress updates
Safety and trust boundaries Which inputs are data rather than instructions; hard limits
Stop conditions What "done" means and how a turn should end
Reminders The one or two rules that matter most, restated briefly

Why this order

Each part is read in light of the ones above it. The role frames how context is interpreted. Context makes the task intelligible. The task gives the workflow a purpose, and the workflow gives the rules and tool guidance something to attach to ("before step 3, confirm"). Output and safety rules shape what happens at the end of each step, and stop conditions plus reminders sit last, where they are freshest when the model begins generating.

Small prompts can merge parts: role, task and context often fit in one opening paragraph. Keep the sequence even when you merge.

How to write good system instructions

What does not belong in the system prompt

The user message

The user message holds what is specific to this request. Its shape is a funnel: a one-line frame, then the material from broadest to most relevant, then the instructions, then the question as the very last thing.

Part What goes in Notes
Frame (optional) One sentence saying what's coming and what it's for "Below are three service logs and the related code; I'll ask about the outage at the end." Lets the material be read with purpose (see Order).
Environment Working directory, file tree, list of available resources Mark each entry as included below, available via a tool, or listed only. Use the same paths as the document labels that follow.
Reference material Background the model should consult but not act on: specs, docs, related files Each item wrapped and labeled with its source.
Primary material What the task is about: the file to edit, the email to answer, the dataset to analyze Last in the material block, so it sits closest to the instructions.
Examples Request-specific examples: input and ideal output 3 to 5, varied. Examples that never change go in the system prompt instead, for caching.
Instructions What to do, what "done" looks like, when to stop and ask Refer to material by its label ("the file at src/tax.py").
Output overrides Only what differs from the system prompt's defaults "For this one, return a table."
The question The specific ask Always the final line.

Untrusted content is a label, not a position

Pasted text, retrieved web pages and email bodies are not a separate slot. Place them where their role puts them (an email you're replying to is primary material; a scraped page used for background is reference) and wrap them in a tag that marks them as data, so the system prompt's trust rule can find them.

For short requests

Most of these parts are empty most of the time. A two-line request needs only the instructions and the question. The order matters once the material is long, roughly when it is longer than the instructions.

Later turns in a conversation

A follow-up message usually carries only new material and the new question, in the same order. Don't re-send or edit earlier material; the conversation is append-only, both for caching and because some models bind their reasoning to the exact history. If the environment changes (a file was edited), send the updated part as new material.

Tool descriptions and field descriptions

A tool definition is a small prompt of its own, read at two moments: the tool description when the model decides whether to call it, and each field description when it decides what to put in that field. Write each for its moment.

Parts of a tool description, in order

  1. What it does. One sentence, verb first. This is what the selection decision reads first.
  2. When to use it, and when not. Name the alternative if one exists ("For a single ticket by ID, use get_ticket").
  3. What it returns. Shape, size limits, ordering, pagination.
  4. Side effects and cost. Read-only or writing? Reversible? Slow, rate-limited, billed?
  5. Tool-specific caveats. Query syntax, known gaps, behavior on empty results.

Err toward detail. A tool description is rarely too long; a vague one makes the model guess when to call it.

Tool availability matters

Tool descriptions and schemas are part of the thread and can shape the outcome and model behavior, sometimes in unexpected ways. Tools that this agent will not call can still be worth adding (for example, to show the shape of a final result). Likewise, add a specific tool only if certain preconditions hold.

Parts of a field description (zod .describe()), in order

  1. Meaning. What the value represents.
  2. Format. Units, encoding, an example value.
  3. Source. Where the value comes from ("the id from search_tickets results", "exactly as the user wrote it").
  4. Default behavior. What happens if it's omitted, and when to override that.

The proximity rule recurses inside a tool: a rule about how two fields of the same tool interact goes on the field it changes ("Ignored when status is set"), or in the tool description if it spans several fields.

Schema first, prose second

Encode every constraint the schema can express: types, enums, required vs. optional, min and max, regex, defaults. The schema is enforced; prose is only followed. Use the description for what the schema can't say, and don't restate the schema in words. Names are part of the prompt too: customer_email needs less description than ce.

Keep field order meaningful: the model writes fields in order, as it reads them. Required fields first, and a field before any field whose value depends on it.

Where each instruction lives: as close as possible to what it governs

An instruction belongs at the narrowest scope that fully contains what it's about. The model reads a field description at the moment it fills that field, and a tool description when it weighs that tool. An instruction placed there is in front of the model exactly when it matters, and it travels with the tool if you reuse it in another agent.

Scope of the instruction

What the instruction governs Where it lives Example
The whole session, or several tools System prompt "Search before you create, to avoid duplicates. Ask before any call that deletes or sends."
This request only User message "Summarize the attached incident and propose a fix."
One tool Tool description "Use for full-text search across tickets. Returns at most 50 results; paginate with cursor."
One parameter Field description (zod .describe()) "ISO 8601 date in the user's time zone, e.g. 2026-11-06"
From a point in the work onward Tool result or appended message "3 tests failed. Fix them before running other tools."

The test: if you deleted the tool, would this sentence still make sense in the system prompt? If not, it belongs in the tool. If you deleted the field, would the sentence still make sense in the tool description? If not, it belongs in the field.

Four consequences follow:

When to add instructions and status

Add an instruction at the moment it becomes relevant, in the place the model is looking. Standing rules go once at the start. Situational guidance goes in the tool result or message that creates the situation, which puts it at the end of the context, where the weight is.

Kind When it matters Where it goes
Standing rules Every turn System prompt, once
A rule triggered by an event (tests failed, a file is too large, a write needs approval) Right after the event The tool result that reports it: "3 tests failed. Fix them before running other tools."
How to read one tool's output (pagination, truncation) When reading that output Tool description for the general rule; a hint in the result for this instance: "47 more; pass cursor to continue."
Status: plan, progress, what's next, budget left Before every next step Near the end, in recent tool results or a refreshed status message
Environment changes (a file edited elsewhere, new permissions) From now on An appended message, never an edit to earlier context
Operator changes mid-session From now on An appended system or developer message, where the API supports one
A preference the user states mid-chat From now on Already in the conversation; persist it to memory if it should outlive the session

Principles

Why this order works

Order is decided by five dimensions. Three are mechanical (caching, how the model reads tokens, where its attention falls) and two are about meaning (scope, generality). Most of the time they agree.

Dimension Rule Why
Stability Static first, dynamic last Caching reuses only an unchanged prefix
Causality Prerequisites before dependents; the ask last Each token is processed only in light of earlier tokens
Weight Rules at the start, the ask and status at the end, nothing critical in the middle The start and end get the most attention
Scope Narrowest home that contains the instruction It is in front of the model at the moment it applies
Generality General before specific Broad framing shapes how specifics are read

Stability: static before dynamic

Providers cache the longest prefix of the request that is byte-identical to a recent one. Order everything by how often it changes:

  1. System prompt (changes on deploy)
  2. Tool definitions (change on deploy)
  3. Per-session context, such as a project's file tree or a user's settings (changes per session)
  4. Earlier conversation turns (append-only)
  5. The new user message (changes every request)

Anything volatile placed early (a timestamp in the system prompt, tools sorted differently per call) invalidates the cache for everything after it. This dimension is why the system prompt holds the static material and the user message holds the dynamic material.

Causality: every prior token shapes the next

A language model processes text left to right. Each token's internal representation is built from that token and the tokens before it; it never sees what comes later. Generation then begins right after the last token of your prompt. This has practical consequences that run against how people naturally write:

Humans tend to write in the order they think: question first, context after, caveats as afterthoughts ("oh, and also..."). For a model, rewrite it as frame, context, material, instructions, question.

These are tendencies, not laws. Current models attend across the whole context and are trained to be robust to order, and reasoning models re-read the prompt as they think. The effects are small on short prompts and measurable on long ones.

Weight: the edges carry the attention

Covered in Attention: the start and the end carry the weight above.

Scope: proximity

Field-level rules on the field, tool-level rules on the tool, cross-tool and session rules in the system prompt, request rules in the user message. Proximity decides which container; the other four dimensions decide the order inside it.

Generality: general before specific

Within any container, move from broad to narrow: role before rules, rules before edge cases, background material before the primary file, the task before the exact question. Broad framing tells the model how to read the specifics.

Anti-patterns

Anti-pattern Why it hurts Fix
Loading every doc and skill up front, just in case Dilutes attention and costs tokens on every request An index up front; details loaded on demand
Status or progress in the system prompt Stale after one turn, and it breaks the cache Recent tool results or a refreshed message
Event-triggered rules only in the system prompt Far from the moment they apply Repeat the guidance in the tool result that reports the event
Huge raw tool results Bloat the middle and bury the task Trim, paginate, or write to a file and return the path
Status blocks piling up turn after turn Old status competes with the current one One compact, complete status, refreshed each time
Tool usage notes in the system prompt Far from the call, stale when the tool changes, not portable Move to the tool or field description
The same rule in the system prompt and in a tool The copies drift apart, and a subagent sharing the tool gets a third Keep it in the narrowest home only
Question first, ten pages of material after The question sits far from where generation starts Short frame first, question last
Timestamp or user name in the system prompt Breaks the cache for everything after it Put it after the cached prefix
Schema rules written as prose Prose is followed loosely; schemas are enforced Use enums, required, min/max, formats
Rules without reasons The model follows the letter and misses the intent Add a short "because" to each rule
"CRITICAL" and all-caps everywhere Over-triggers; emphasis stops meaning anything Plain wording; emphasis only on real hard limits
A caveat after an example The example has already primed the output Caveat before the example, or a better example
The key file in the middle of a long dump Middle positions are used least reliably Primary material last in the material block
Contradictions resolved by position Later doesn't reliably win Delete one of the two instructions
Editing earlier turns to change behavior Breaks the cache, and some models reject edited history Append a new message
"Think step by step" on a reasoning model Redundant cost Use the effort or reasoning setting