---
title: "Long-Running Autonomous Worker"
domain: "Autonomous Operations"
summary: "Durability, cost, credential, and self-monitoring patterns for agent jobs that run unattended for hours or on a schedule."
url: "https://agentic-patterns.com/packs/long-running-autonomous-worker"
markdown_url: "https://agentic-patterns.com/packs/long-running-autonomous-worker.md"
pattern_count: 5
---

# Long-Running Autonomous Worker

> Durability, cost, credential, and self-monitoring patterns for agent jobs that run unattended for hours or on a schedule.

**Domain:** Autonomous Operations

## How to apply this stack with a coding agent

```text
Apply the "Long-Running Autonomous Worker" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Filesystem-Based Agent State** — Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks. ([page](https://agentic-patterns.com/patterns/filesystem-based-agent-state) | [.md](https://agentic-patterns.com/patterns/filesystem-based-agent-state.md))
2. **Context Window Auto-Compaction** — Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically ([page](https://agentic-patterns.com/patterns/context-window-auto-compaction) | [.md](https://agentic-patterns.com/patterns/context-window-auto-compaction.md))
3. **Prompt Caching via Exact Prefix Preservation** — Keeps static prompt content first in a fixed order and only appends new messages, including config changes, so each request reuses the cached prefix ([page](https://agentic-patterns.com/patterns/prompt-caching-via-exact-prefix-preservation) | [.md](https://agentic-patterns.com/patterns/prompt-caching-via-exact-prefix-preservation.md))
4. **Credential-Free Outbox** — The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything ([page](https://agentic-patterns.com/patterns/credential-free-outbox) | [.md](https://agentic-patterns.com/patterns/credential-free-outbox.md))
5. **Dead-Man's Switch for Scheduled Agent Jobs** — Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale ([page](https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs) | [.md](https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md))

---

## Filesystem-Based Agent State

- URL: https://agentic-patterns.com/patterns/filesystem-based-agent-state
- Markdown: https://agentic-patterns.com/patterns/filesystem-based-agent-state.md
- Category: Context & Memory | Status: foundational

> Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.

### Use when

- Multi-step workflows with expensive operations such as API calls or data processing
- Tasks may be interrupted or exceed single-session context limits
- Several agents or sessions build on earlier work

### Avoid when

- Short tasks that finish in one session with cheap steps
- The execution environment has no persistent storage
- Concurrent writers with no file locking or atomic writes

<details>
<summary>Full pattern specification</summary>

---
title: "Filesystem-Based Agent State"
summary: "Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks."
status: "foundational"
category: "Context & Memory"
url: "https://agentic-patterns.com/patterns/filesystem-based-agent-state"
source: "https://www.anthropic.com/engineering/code-execution-with-mcp"
authors: ["Nikola Balic (@nibzard)"]
tags: ["state-management","persistence","resumption","long-running-tasks"]
signals: ["Multi-step workflows with expensive operations such as API calls or data processing","Tasks may be interrupted or exceed single-session context limits","Several agents or sessions build on earlier work"]
anti_signals: ["Short tasks that finish in one session with cheap steps","The execution environment has no persistent storage","Concurrent writers with no file locking or atomic writes"]
updated_at: "2026-10-13"
---

# Filesystem-Based Agent State

> Agents persist intermediate results and working state to files, creating durable checkpoints that enable workflow resumption, recovery from failures, and support for long-running tasks.

## Use when

- Multi-step workflows with expensive operations such as API calls or data processing
- Tasks may be interrupted or exceed single-session context limits
- Several agents or sessions build on earlier work

## Avoid when

- Short tasks that finish in one session with cheap steps
- The execution environment has no persistent storage
- Concurrent writers with no file locking or atomic writes

## Problem

Many agent workflows are long-running or may be interrupted (by errors, timeouts, or user intervention). Keeping all intermediate state in the model's context window is fragile and doesn't persist across sessions. When failures occur or when agents hit context limits, work is lost and must restart from scratch.

## Solution

Agents persist intermediate results and working state to files in the execution environment. This creates durable checkpoints that enable workflow resumption, recovery from failures, and support for tasks that exceed single-session context limits.

Instead of treating state as transient prompt text, the workflow externalizes progress into explicit artifacts that any later run can inspect and continue from. This gives agents a resumable execution model and makes failure recovery deterministic.

File-backed state also improves observability: humans can inspect checkpoints, compare intermediate outputs across retries, and diagnose where runs diverged.

Some agents exhibit "proactive state externalization" — writing `SUMMARY.md` or `CHANGELOG.md` without explicit prompting when approaching context limits. That model-driven behavior, and how to shape it, is covered as its own pattern in [Proactive Agent State Externalization](proactive-agent-state-externalization.md); this entry stays with deliberate, workflow-level checkpointing.

**Core pattern:**

```python
# Agent writes intermediate state to files
def multi_step_workflow():
    # Check if previous work exists
    if os.path.exists("state/step1_results.json"):
        print("Resuming from step 1...")
        step1_data = json.load(open("state/step1_results.json"))
    else:
        print("Starting from beginning...")
        step1_data = perform_step1()
        with open("state/step1_results.json", "w") as f:
            json.dump(step1_data, f)

    # Continue with step 2
    if os.path.exists("state/step2_results.json"):
        print("Resuming from step 2...")
        step2_data = json.load(open("state/step2_results.json"))
    else:
        step2_data = perform_step2(step1_data)
        with open("state/step2_results.json", "w") as f:
            json.dump(step2_data, f)

    # Final step
    return perform_step3(step2_data)
```

**State organization:**

```
workspace/
├── state/
│   ├── step1_results.json
│   ├── step2_results.json
│   └── progress.txt
├── data/
│   ├── input.csv
│   └── processed.csv
└── logs/
    └── execution.log
```

## How to use it

**Best for:**

- Multi-step workflows with expensive operations (API calls, data processing)
- Long-running tasks that may exceed session limits
- Workflows that need recovery from transient failures
- Collaborative tasks where multiple agents or sessions build on previous work
- Batch processing jobs with checkpointing

**Implementation patterns:**

1. **Checkpoint after expensive operations:**

   ```python
   def process_large_dataset():
       checkpoint_file = "state/processed_rows.json"

       # Load progress if exists
       if os.path.exists(checkpoint_file):
           processed = json.load(open(checkpoint_file))
           start_row = len(processed)
       else:
           processed = []
           start_row = 0

       # Process from checkpoint
       for i, row in enumerate(data[start_row:]):
           result = expensive_operation(row)
           processed.append(result)

           # Checkpoint every 100 rows
           if (i + 1) % 100 == 0:
               with open(checkpoint_file, "w") as f:
                   json.dump(processed, f)

       return processed
   ```

2. **State file with metadata:**

   ```json
   {
     "workflow_id": "abc-123",
     "current_step": "data_processing",
     "completed_steps": ["data_fetch", "validation"],
     "last_update": "2024-01-15T10:30:00Z",
     "data": {
       "records_processed": 1500,
       "errors_encountered": 3
     }
   }
   ```

3. **Progress logging for visibility:**

   ```python
   def log_progress(step, status, details=None):
       with open("logs/progress.log", "a") as f:
           timestamp = datetime.now().isoformat()
           log_entry = f"{timestamp} | {step} | {status}"
           if details:
               log_entry += f" | {json.dumps(details)}"
           f.write(log_entry + "\n")
           print(log_entry)  # Also show in agent context
   ```

4. **Using framework primitives:**

   ```python
   # FileStore previously shipped as langchain.storage; current releases
   # expose it through the langchain-classic package
   from langchain_classic.storage import FileStore
   store = FileStore("agent_memory")
   store.mset([("step1", step1_data), ("step2", step2_data)])
   ```

## Trade-offs

**Pros:**

- Enables workflow resumption after interruption
- Protects against data loss from transient failures
- Supports long-running tasks beyond single-session limits
- Allows inspection of intermediate results
- Facilitates debugging (can examine state at each checkpoint)
- Multiple agents can collaborate by reading/writing shared state

**Cons:**

- Agents must write checkpoint/recovery logic
- File I/O adds overhead to workflow execution
- Requires discipline around state naming and organization
- Stale state files can cause confusion if not cleaned up
- Concurrent access needs coordination (file locking, atomic writes)
- Execution environment needs persistent storage

**Operational considerations:**

- Define state file cleanup policies (retention period, automatic cleanup)
- Use atomic writes to prevent corruption (write to temp, then rename)
- Include timestamps and version info in state files
- Consider state file size limits (don't checkpoint massive datasets)
- Secure state files if they contain sensitive data
- For very large state, use memory-mapped files or efficient serialization (MessagePack)

## References

* Anthropic Engineering: Code Execution with MCP (published November 4, 2025): https://www.anthropic.com/engineering/code-execution-with-mcp
* Cognition AI: Devin's proactive state externalization to `SUMMARY.md`/`CHANGELOG.md` (posted September 2025): https://cognition.com/blog/devin-sonnet-4-5-lessons-and-challenges
* Claude Code memory (auto memory and CLAUDE.md as shipped file-backed memory): https://code.claude.com/docs/en/memory
* LangChain: `FileStore` for persistent key-value state (now in the `langchain-classic` package): https://github.com/langchain-ai/langchain
* Related: [Proactive Agent State Externalization](proactive-agent-state-externalization.md) (the model-initiated counterpart) and Episodic Memory Retrieval & Injection (conversation-level persistence)

</details>

---

## Context Window Auto-Compaction

- URL: https://agentic-patterns.com/patterns/context-window-auto-compaction
- Markdown: https://agentic-patterns.com/patterns/context-window-auto-compaction.md
- Category: Context & Memory | Status: foundational

> Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically

### Use when

- Long sessions fail with context_length_exceeded errors
- Operators truncate transcripts by hand
- Agent supports multiple model providers with different transcript rules

### Avoid when

- Short sessions that never approach the context limit
- Summary detail loss is not acceptable and manual curation is required

<details>
<summary>Full pattern specification</summary>

---
title: "Context Window Auto-Compaction"
summary: "Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically"
status: "foundational"
category: "Context & Memory"
url: "https://agentic-patterns.com/patterns/context-window-auto-compaction"
source: "https://github.com/openclaw/openclaw/blob/main/src/agents/embedded-agent-runner/compact.ts"
authors: ["OpenClaw Contributors"]
tags: ["context-management","compaction","overflow-recovery","token-estimation","transcript-validation","api-compaction"]
signals: ["Long sessions fail with context_length_exceeded errors","Operators truncate transcripts by hand","Agent supports multiple model providers with different transcript rules"]
anti_signals: ["Short sessions that never approach the context limit","Summary detail loss is not acceptable and manual curation is required"]
updated_at: "2026-10-13"
---

# Context Window Auto-Compaction

> Catches context overflow errors, compacts and validates the transcript with capped reserve headroom, and retries the request automatically

## Use when

- Long sessions fail with context_length_exceeded errors
- Operators truncate transcripts by hand
- Agent supports multiple model providers with different transcript rules

## Avoid when

- Short sessions that never approach the context limit
- Summary detail loss is not acceptable and manual curation is required

## Problem

Context overflow is a silent killer of agent reliability. When accumulated conversation history exceeds the model's context window:

- **API errors**: Requests fail with `context_length_exceeded` or similar errors
- **Manual intervention**: Operators must truncate transcripts, losing valuable context
- **Retry complexity**: Detecting overflow and retrying with compaction is error-prone

Agents need automatic compaction that preserves essential information while staying within token limits, with model-specific validation and capped reserve headroom to prevent immediate re-overflow.

## Solution

Automatic session compaction triggered by context overflow errors, with smart reserve tokens and lane-aware retry. The system detects overflow, compacts the session transcript, validates the result, and retries the request—all transparently to the user.

**Core concepts:**

- **Overflow detection**: Catches API errors indicating context length exceeded (`context_length_exceeded`, `prompt is too long`, etc.).
- **Auto-retry with compaction**: On overflow, the session is compacted and the request is retried automatically.
- **Reserve headroom cap**: Post-compaction reserve tokens are capped at 25% of the context budget, so prompts retain at least three quarters of the model window.
- **Lane-aware compaction**: Uses hierarchical lane queuing (session → global) to prevent deadlocks during compaction.
- **Post-compaction verification**: Estimates token count after compaction and verifies it's less than the pre-compaction count.
- **Model-specific validation**: Anthropic models require strict turn ordering; Gemini models have different transcript requirements.

**Implementation sketch:**

```typescript
async function compactEmbeddedPiSession(params: {
  sessionFile: string;
  config?: Config;
}): Promise<CompactResult> {
  // 1. Load session and configure reserve tokens
  const sessionManager = SessionManager.open(params.sessionFile);
  const settingsManager = SettingsManager.create(workspaceDir, agentDir);

  // Cap reserve tokens at 25% of the context budget
  const reserveTokens = resolveEffectiveCompactionReserveTokens({
    contextTokenBudget: resolveContextTokenBudget(params.config),
    reserveTokens: settingsManager.getCompactionReserveTokens(),
  });

  // 2. Sanitize session history for model API
  const prior = sanitizeSessionHistory({
    messages: session.messages,
    modelApi: model.api,
    modelId,
    provider,
    sessionManager,
  });

  // 3. Model-specific validation
  const validated = provider === "anthropic"
    ? validateAnthropicTurns(prior)
    : validateGeminiTurns(prior);

  // 4. Compact the session
  const result = await session.compact(customInstructions);

  // 5. Estimate tokens after compaction
  let tokensAfter: number | undefined;
  try {
    tokensAfter = 0;
    for (const message of session.messages) {
      tokensAfter += estimateTokens(message);
    }
    // Sanity check: tokensAfter should be less than tokensBefore
    if (tokensAfter > result.tokensBefore) {
      tokensAfter = undefined;  // Don't trust the estimate
    }
  } catch {
    tokensAfter = undefined;
  }

  return {
    ok: true,
    compacted: true,
    result: {
      summary: result.summary,
      tokensBefore: result.tokensBefore,
      tokensAfter,
    },
  };
}
```

**Reserve headroom and attempt budget:**

```typescript
// Reserve summary/housekeeping headroom without letting it
// dominate small model windows.
const MAX_COMPACTION_RESERVE_RATIO = 0.25;

/** Caps compaction headroom so prompts retain at least three quarters of the model window. */
function resolveEffectiveCompactionReserveTokens(params: {
  contextTokenBudget: number;
  reserveTokens: number;
}): number {
  const contextTokenBudget = Math.max(1, Math.floor(params.contextTokenBudget));
  return Math.min(
    Math.max(0, Math.floor(params.reserveTokens)),
    Math.floor(contextTokenBudget * MAX_COMPACTION_RESERVE_RATIO),
  );
}

// Overflow-triggered compaction retries stop after this many attempts.
export const MAX_OVERFLOW_COMPACTION_ATTEMPTS = 3;
```

**API-based compaction (OpenAI Responses API):**

Some providers offer dedicated compaction endpoints that are more efficient than manual summarization:

```typescript
// OpenAI's /responses/compact endpoint
const compacted = await responsesAPI.compact({
  messages: currentMessages,
});

// Returns a list of items that includes:
// - A special type=compaction item with encrypted_content
//   that preserves the model's latent understanding
// - Condensed conversation items

currentMessages = compacted.items;
```

This approach has advantages:
- **Preserves latent understanding**: The `encrypted_content` maintains the model's compressed representation of the original conversation
- **More efficient**: Server-side compaction is faster than client-side summarization
- **Auto-compaction**: Can trigger automatically when `auto_compact_limit` is exceeded

**Two complementary approaches:**

This pattern describes **reactive compaction** (detect overflow, compact, retry). An alternative approach is **preventive filtering** (reduce context at ingestion), used by systems like HyperAgent for browser accessibility tree extraction. Preventive filtering can delay or eliminate the need for reactive compaction by keeping context leaner from the start.

**Lane-aware retry to prevent deadlocks:**

```typescript
// Compaction runs through session lane, then global lane
async function compactEmbeddedPiSession(params: CompactParams): Promise<CompactResult> {
  const sessionLane = resolveSessionLane(params.sessionKey);
  const globalLane = resolveGlobalLane(params.lane);

  return enqueueCommandInLane(sessionLane, () =>
    enqueueCommandInLane(globalLane, () =>
      compactEmbeddedPiSessionDirect(params)  // Core compaction logic
    )
  );
}
```

## Evidence

- **Evidence Grade:** `high` (documented production implementations)
- **Key Findings:**
  - OpenAI documents server-side compaction for Codex through the `/responses/compact` design (September 2026): a `compaction` item with `encrypted_content` preserves the model's compressed representation of the conversation, and `auto_compact_limit` triggers compaction automatically
  - OpenClaw implements reactive, client-side compaction: overflow detection, a reserve cap of 25% of the context budget, and at most 3 overflow compaction attempts
  - The Pi coding agent (earendil-works/pi) supplies the embedded session compaction core that OpenClaw's runner builds on
  - Beurer-Kellner et al. (2025) catalog context minimization as a complementary defense that removes untrusted content from context; they report no quantitative token-reduction figure
- **Unverified:** Whether other commercial products (Cursor, GitHub Copilot) publish their compaction strategies

## How to use it

1. **Configure reserve headroom**: Set compaction reserve tokens, and cap them at a fraction of the context budget (OpenClaw uses 25%) so headroom cannot crowd out the prompt.
2. **Handle overflow errors**: Catch API errors, detect overflow via error message matching, then trigger compaction.
3. **Validate transcripts**: Apply model-specific validation (Anthropic turns, Gemini ordering) before retry.
4. **Estimate post-compaction tokens**: Verify that compaction actually reduced token count before retrying.
5. **Use lane queuing**: Run compaction through hierarchical lanes to avoid deadlocks with concurrent operations.

**Pitfalls to avoid:**

- **Aggressive floor setting**: Reserve tokens too high may leave insufficient room for actual conversation content.
- **Missing model validation**: Skipping model-specific transcript validation can cause API errors on retry.
- **Token estimation drift**: Estimation heuristics may diverge from actual token counts; treat estimates as sanity checks only.
- **Infinite compaction loops**: If compaction fails to reduce tokens, avoid infinite retry loops. OpenClaw caps overflow compaction at 3 attempts.

## Trade-offs

**Pros:**

- **Transparent recovery**: Overflow errors are handled automatically without user intervention.
- **Preserve essential context**: Compaction generates summaries rather than arbitrary truncation.
- **Prevents re-overflow**: Reserve token floor ensures immediate re-overflow is unlikely.
- **Model-aware**: Different validation rules per provider ensure API compatibility.

**Cons/Considerations:**

- **Summary quality**: Auto-generated summaries may lose nuanced details that manual curation would preserve.
- **Latency penalty**: Compaction and retry adds overhead (seconds to minutes depending on context size).
- **Token estimation errors**: Heuristics may misestimate actual token counts, leading to failed retries.
- **Complexity**: Lane-aware queuing and model-specific validation increase implementation complexity.

## References

- [OpenClaw compact.ts](https://github.com/openclaw/openclaw/blob/main/src/agents/embedded-agent-runner/compact.ts) - Compaction orchestration
- [OpenClaw agent-compaction-constants.ts](https://github.com/openclaw/openclaw/blob/main/src/agents/agent-compaction-constants.ts) - Reserve ratio cap and overflow attempt limit
- [OpenClaw context-window-guard.ts](https://github.com/openclaw/openclaw/blob/main/src/agents/context-window-guard.ts) - Context evaluation
- [Pi coding agent](https://github.com/earendil-works/pi) - Embedded session compaction core; formerly `mariozechner/pi-coding-agent`, now the earendil-works/pi monorepo
- [Unrolling the Codex agent loop | OpenAI Blog](https://openai.com/index/unrolling-the-codex-agent-loop/) - API-based `/responses/compact` endpoint approach
- Beurer-Kellner et al. (2025). "Design Patterns for Securing LLM Agents against Prompt Injections." [arXiv:2506.08837](https://arxiv.org/abs/2506.08837) - Context minimization as a complementary defense
- Related: [Context Window Anxiety Management](/patterns/context-window-anxiety-management) for proactive management
- Related: [Prompt Caching via Exact Prefix Preservation](/patterns/prompt-caching-via-exact-prefix-preservation)

</details>

---

## Prompt Caching via Exact Prefix Preservation

- URL: https://agentic-patterns.com/patterns/prompt-caching-via-exact-prefix-preservation
- Markdown: https://agentic-patterns.com/patterns/prompt-caching-via-exact-prefix-preservation.md
- Category: Context & Memory | Status: foundational

> Keeps static prompt content first in a fixed order and only appends new messages, including config changes, so each request reuses the cached prefix

### Use when

- Long agent conversations with many tool calls
- Zero Data Retention rules out server-side conversation state
- Inference cost or latency grows as history grows

### Avoid when

- Tool list or model must change mid-conversation
- Short single-turn requests with little repeated content

<details>
<summary>Full pattern specification</summary>

---
title: "Prompt Caching via Exact Prefix Preservation"
summary: "Keeps static prompt content first in a fixed order and only appends new messages, including config changes, so each request reuses the cached prefix"
status: "foundational"
category: "Context & Memory"
url: "https://agentic-patterns.com/patterns/prompt-caching-via-exact-prefix-preservation"
source: "https://openai.com/index/unrolling-the-codex-agent-loop/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["prompt-caching","exact-prefix","performance","stateless","zero-data-retention","message-ordering","optimization"]
signals: ["Long agent conversations with many tool calls","Zero Data Retention rules out server-side conversation state","Inference cost or latency grows as history grows"]
anti_signals: ["Tool list or model must change mid-conversation","Short single-turn requests with little repeated content"]
updated_at: "2026-10-13"
---

# Prompt Caching via Exact Prefix Preservation

> Keeps static prompt content first in a fixed order and only appends new messages, including config changes, so each request reuses the cached prefix

## Use when

- Long agent conversations with many tool calls
- Zero Data Retention rules out server-side conversation state
- Inference cost or latency grows as history grows

## Avoid when

- Tool list or model must change mid-conversation
- Short single-turn requests with little repeated content

## Problem

Long-running agent conversations with many tool calls can suffer from **quadratic performance degradation**:

- **Growing JSON payloads**: each iteration sends the entire conversation history to the API
- **Expensive re-computation**: without caching, the model re-processes the same static content repeatedly
- **ZDR constraints**: Zero Data Retention (ZDR) policies prevent server-side state, which rules out the `previous_response_id` optimization
- **Configuration changes**: mid-conversation changes (sandbox, tools, working directory) can break cache efficiency

## Solution

Maintain prompt cache efficiency through **exact prefix preservation**: append new messages instead of modifying existing ones, and order messages so that the stable content sits at the front.

**Core insight**: prompt caches work only on **exact prefix matches**. If the first N tokens of a request match a previous request, the cached computation can be reused. Caching operates at the token level, not the message level: the cache checks token by token, independent of message boundaries.

**Message ordering strategy:**

1. **Static content first** (cached across all requests): system message (if server-controlled), tool definitions in a consistent order, developer instructions, then user or project instructions.
2. **Variable content last** (changes per request): user message, assistant messages, and tool call results appended iteratively.

**Configuration change via insertion:** when configuration changes mid-conversation, insert a new message. Do not modify an existing one.

```
[Static prefix...]
<sandbox_config_v1>     // Original config message
[Conversation...]

<sandbox changed>
<sandbox_config_v2>     // NEW message inserted
[Conversation continues...]
```

The insertion preserves the exact prefix of all previous messages, so the cache hits continue.

**What breaks cache hits:**

- Changing the list of available tools (position-sensitive)
- Reordering messages
- Modifying existing message content
- Changing the model (it affects the server-side system message)

**Provider variations:**

- **OpenAI**: caching requires an exact rendered-prefix match ("Cache reuse requires the entire rendered prefix to match"). Older models cache implicitly at model-dependent intervals; newer models also support explicit cache breakpoints (up to four cache writes per request), with cached tokens discounted up to 95% (reads at 0.1x the uncached input rate on most models)
- **Anthropic**: explicit `cache_control` breakpoints plus automatic caching, a 5-minute default TTL with a 1-hour TTL option, cache reads at 0.1x the base input price (0.05x on Opus 5.5/Sonnet 5.5, 0.025x on Fable 5.1/Mythos 5.1), and a per-model minimum cacheable prefix length

**Stateless design for ZDR:**

Avoid `previous_response_id` to support Zero Data Retention. Rely on prompt caching for linear sampling cost:

```
Without previous_response_id:
- Quadratic network traffic (send full JSON each time)
- Linear sampling cost (due to prompt caching)

With previous_response_id:
- Linear network traffic
- But violates ZDR (server must store conversation state)
```

### Example: one prefix, three requests

```mermaid
graph TD
    subgraph "Request 1"
        A1[System message] --> A2[Tools] --> A3[Instructions] --> A4[User message]
    end

    subgraph "Request 2 - Cache Hit!"
        B1[System message] --> B2[Tools] --> B3[Instructions] --> B4[User message] --> B5[Assistant response] --> B6[Tool result]
    end

    subgraph "Request 3 - Cache Hit!"
        C1[System message] --> C2[Tools] --> C3[Instructions] --> C4[User message] --> C5[Assistant response] --> C6[Tool result 1] --> C7[Tool result 2]
    end

    classDef cached fill:#90EE90
    classDef fresh fill:#FFB6C1
    class A1,A2,A3,B1,B2,B3,C1,C2,C3 cached
    class A4,B4,B5,B6,C4,C5,C6,C7 fresh
```

**Green = Cached** (exact prefix match) | **Pink = Recomputed** (new tokens)

## How to use it

**Prompt construction checklist:**

1. Order messages by stability: static, then variable.
2. Never modify existing messages; always append new ones.
3. Keep tool order consistent: enumerate tools in a deterministic order.
4. For configuration changes, insert; do not update.

**Handling configuration changes:**

| Change Type | What NOT to do | What TO do |
|-------------|----------------|------------|
| Sandbox/approval mode | Modify permission message | Insert new `role=developer` message |
| Working directory | Modify environment message | Insert new `role=user` message |
| Tool list | Change mid-conversation | Avoid if possible; breaks cache |

**MCP server considerations:**

MCP servers can emit `notifications/tools/list_changed` to signal tool list changes. Avoid honoring this mid-conversation, because it breaks cache hits. Either delay the tool refresh until a conversation boundary or accept the cache miss as a necessary trade-off.

**Compaction:**

The Codex post that documents this pattern also describes a `/responses/compact` endpoint for auto-compaction: the client posts the conversation and receives a `compaction` item with opaque `encrypted_content` that summarizes prior turns while keeping the request stateless. `auto_compact_limit` controls when compaction triggers. Compaction trades context for a cache reset: everything after the compacted summary is new tokens.

**Implementation sketch:**

```typescript
function buildPrompt(state: ConversationState): Prompt {
  return {
    items: [
      // Static prefix (cached); keep tools in a consistent order
      { role: 'system', content: state.systemMessage },
      { type: 'tools', tools: state.tools },
      { role: 'developer', content: state.instructions },
      // Variable content (appended)
      ...state.history,
    ],
  };
}

// Configuration change: insert a new message, never edit an existing one
function handleConfigChange(state: ConversationState, newConfig: SandboxConfig) {
  return {
    ...state,
    history: [
      ...state.history,
      { role: 'developer', content: formatSandboxConfig(newConfig) },
    ],
  };
}
```

## Trade-offs

**Pros:**

- **Linear sampling cost**: prompt caching makes repeated inference linear rather than quadratic
- **ZDR-compatible**: the stateless design supports Zero Data Retention policies
- **No server state**: avoids `previous_response_id` complexity
- **Simple conceptual model**: exact prefix matching is easy to reason about

**Cons:**

- **Quadratic network traffic**: the JSON payload still grows quadratically; only sampling is cached
- **Cache fragility**: mid-conversation changes to tools or model break prefix matching
- **Disciplined ordering required**: all static content must come before variable content, and tool enumeration must stay consistent

**Failure modes / gotchas:**

- **Silent cache miss:** one reordered tool, one edited earlier message, or one non-deterministic value in the static prefix invalidates all later tokens. Track cached-token counts per request to see the drop.
- **Honoring `tools/list_changed` mid-conversation:** a tool refresh rewrites the static prefix and breaks cache hits for the rest of the conversation.
- **Swapping the model mid-conversation:** the model change alters the server-side system message, so the prefix no longer matches.
- **Compaction resets the cache:** everything after the compacted summary is recomputed, so budget for one full cache rebuild after each compaction.

## References

* [Unrolling the Codex agent loop | OpenAI Blog](https://openai.com/index/unrolling-the-codex-agent-loop/) (September 11, 2026) — exact-prefix caching under ZDR, insert-don't-modify config changes, `tools/list_changed` cache misses, and the `/responses/compact` auto-compaction endpoint
* [Prompt Caching Documentation | OpenAI](https://developers.openai.com/api/docs/guides/prompt-caching) — prefix-match rules, explicit breakpoints on newer models, cache pricing
* [Prompt Caching | Anthropic](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) — `cache_control` breakpoints, TTLs, read pricing, minimum cacheable length
* [Codex CLI | GitHub](https://github.com/openai/codex)
* Related: [Context Window Auto-Compaction](/patterns/context-window-auto-compaction)

</details>

---

## Credential-Free Outbox

- URL: https://agentic-patterns.com/patterns/credential-free-outbox
- Markdown: https://agentic-patterns.com/patterns/credential-free-outbox.md
- Category: Security & Safety | Status: emerging

> The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything

### Use when

- Agent reads untrusted text (issues, READMEs, dependency docs) and must also publish results
- Results can be expressed as a file: a git bundle, a patch, a report
- A CI system can run a credentialed job on a schedule or event

### Avoid when

- The agent needs an interactive, authenticated session with an outside system mid-task
- Results must be published synchronously within the agent's turn
- There is no separate trusted runner to hold the credential

<details>
<summary>Full pattern specification</summary>

---
title: "Credential-Free Outbox"
summary: "The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything"
status: "emerging"
category: "Security & Safety"
url: "https://agentic-patterns.com/patterns/credential-free-outbox"
source: "https://tinysystems.io/blog/the-outbox/"
authors: ["tpoxa (@tpoxa)"]
tags: ["credentials","prompt-injection","least-privilege","git","ci","containment","outbox"]
signals: ["Agent reads untrusted text (issues, READMEs, dependency docs) and must also publish results","Results can be expressed as a file: a git bundle, a patch, a report","A CI system can run a credentialed job on a schedule or event"]
anti_signals: ["The agent needs an interactive, authenticated session with an outside system mid-task","Results must be published synchronously within the agent's turn","There is no separate trusted runner to hold the credential"]
updated_at: "2026-11-08"
---

# Credential-Free Outbox

> The agent writes finished work as a file to an outbox and a separate short-lived job with its own token delivers it, so the agent never holds a credential that can publish anything

## Use when

- Agent reads untrusted text (issues, READMEs, dependency docs) and must also publish results
- Results can be expressed as a file: a git bundle, a patch, a report
- A CI system can run a credentialed job on a schedule or event

## Avoid when

- The agent needs an interactive, authenticated session with an outside system mid-task
- Results must be published synchronously within the agent's turn
- There is no separate trusted runner to hold the credential

## Problem

A coding agent has to publish its work: push a branch, open a pull request, post a comment. The obvious way is to give it a token. But the same agent reads untrusted text all day, so a prompt injection can use that token for anything it allows: force-push, reach other repositories, open a pull request somewhere it shouldn't. Short-lived CI tokens don't fix this cleanly either. GitHub revokes a job's token when the job ends, often before a long-running agent has finished.

## Solution

The agent holds no publishing credentials at all. It writes its finished work as a file to an outbox, and a separate, short-lived, credentialed job delivers it.

- **Agent:** commits on a branch, then runs `git bundle create outbox/<branch>.bundle main..<branch>`. No remote, no token.
- **Courier:** a CI job with its own fresh token lists the outbox, validates each bundle name against a strict pattern, fetches the bundle, rebases it onto the current main and pushes.
- **Acknowledge after delivery:** the courier deletes a bundle only after the push succeeds. A failed push leaves it in place for the next run, so nothing is lost or delivered twice.
- **Identity-bearing side effects** (opening the PR, posting a comment) are done by the courier too, never by the agent.

```pseudo
agent:
    work(); commit(branch)
    write_bundle("outbox/" + branch + ".bundle")

courier (scheduled or event-driven, outside the agent sandbox):
    for b in list(outbox) where name matches ^[A-Za-z0-9][A-Za-z0-9._-]*\.bundle$:
        fetch(b)                 # argv-only channel, no shell
        rebase(onto = "main")
        push(token)
        open_pr(token)
        ack(b)                   # only after the push succeeded
```

## How to use it

- Run the courier outside the agent's sandbox, with a token scoped to the target repository and as short-lived as the platform allows.
- Read bundles through an argv-only channel and never interpolate agent-written text into a shell command. The bundle name allow-list is part of the pattern, not decoration.
- Rebase in the courier. A bundle made from an old clone can carry stale workflow files, and some CI tokens are not allowed to push changes to workflows even incidentally.
- On GitHub, pushes made with the job's `GITHUB_TOKEN` don't trigger further workflows, so the courier has to open the pull request itself rather than relying on a push-triggered job.

## Trade-offs

- **Pros:** a hijacked agent has no token to push, force-push or reach other repositories with. Nothing in the sandbox needs rotating. Every delivery is done and logged by one auditable job.
- **Cons:** delivery is asynchronous, so there is a delay between "done" and "visible". The courier needs read access to the agent's outbox, which is its own small trust boundary. The model API key usually still lives in the sandbox, so this narrows the blast radius rather than eliminating it.

## References

- https://tinysystems.io/blog/the-outbox/
- https://github.com/tiny-systems/tiny
- https://microservices.io/patterns/data/transactional-outbox.html

</details>

---

## Dead-Man's Switch for Scheduled Agent Jobs

- URL: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs
- Markdown: https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs.md
- Category: Reliability & Eval | Status: emerging

> Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale

### Use when

- Two or more scheduled agent jobs run unattended
- Jobs can fail silently from expired tokens, scheduler errors, or permission changes
- Durable per-run logs exist

### Avoid when

- Jobs run but produce wrong output, which a sentinel does not detect
- Only on-demand jobs with no regular cadence

<details>
<summary>Full pattern specification</summary>

---
title: "Dead-Man's Switch for Scheduled Agent Jobs"
summary: "Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale"
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/dead-mans-switch-for-scheduled-agent-jobs"
source: "https://github.com/jimy-r/agent-workspace-architecture/blob/main/PATTERNS.md"
authors: ["James Ross (@jimy-r)"]
tags: ["scheduled-agents","silent-failure","watchdog","observability","automation"]
signals: ["Two or more scheduled agent jobs run unattended","Jobs can fail silently from expired tokens, scheduler errors, or permission changes","Durable per-run logs exist"]
anti_signals: ["Jobs run but produce wrong output, which a sentinel does not detect","Only on-demand jobs with no regular cadence"]
updated_at: "2026-07-23"
---

# Dead-Man's Switch for Scheduled Agent Jobs

> Each scheduled job writes a success sentinel to its log, and a separate checker files a task when the sentinel is missing or stale

## Use when

- Two or more scheduled agent jobs run unattended
- Jobs can fail silently from expired tokens, scheduler errors, or permission changes
- Durable per-run logs exist

## Avoid when

- Jobs run but produce wrong output, which a sentinel does not detect
- Only on-demand jobs with no regular cadence

## Problem

An agent workspace accumulates scheduled jobs: a morning digest, a background task manager, a weekly self-audit, a memory consolidation pass. These fail silently. A scheduler misconfiguration, an expired OAuth token, or a permission regression doesn't throw an error anywhere a human looks — the job's logs simply stop appearing. Nothing watches for absence, so a broken daily job can stay broken for weeks before anyone notices the output is missing.

## Solution

Invert the monitoring direction: alert on missing success instead of on errors.

- Every scheduled job writes an explicit success sentinel (for example `MORNING_BRIEF_OK`) into its per-run log as its final act.
- A freshness checker knows each tracked task, its cadence, and its staleness window. It scans the most recent log per task: sentinel present and recent means FRESH; missing, stale, or sentinel-less files a finding.
- Findings land in the agent's own task queue — the place the operator already reads — not a separate dashboard nobody opens.
- A per-task `manual` flag exempts on-demand jobs from staleness, so the watchdog doesn't cry wolf on tasks that legitimately run irregularly.
- The checker runs from a different cadence than the jobs it watches (a weekly audit plus on-demand), which answers who-watches-the-watchman without new infrastructure.

```pseudo
for task in tracked_tasks:
    log = latest_log(task)
    if task.manual and log is None:        status = MANUAL_OK
    elif log is None or age(log) > task.window: status = STALE
    elif task.sentinel not in log.text:    status = NO_SENTINEL
    else:                                  status = FRESH
    if status not in (FRESH, MANUAL_OK):
        file_finding(task, status)   # lands in the agent's task queue
```

## Evidence

- **Evidence Grade:** `medium`
- **Most Valuable Findings:** caught a multi-day silent failure in production (a permission regression left a daily job running read-only; config looked correct, the missing sentinel proved otherwise). The underlying inversion is long-established for human cron jobs (Healthchecks.io).
- **Unverified / Unclear:** the agent-specific variant is validated in one production workspace; it says nothing about jobs that run but produce wrong output (pair with synthetic canaries for that class).

## How to use it

Worth adopting once a workspace has two or more scheduled agent jobs. Requirements: durable per-run logs, a success-sentinel convention written into every job's instructions, and a checker invoked by a cadence you already trust (a recurring self-audit is the natural host). Tune staleness windows per task — a 2-hourly job and a weekly job need different definitions of "late."

## Trade-offs

- **Pros:** catches the failure class config inspection cannot ("configured" is not "running"); no external service; the sentinel convention costs one line per job.
- **Cons:** per-task configuration to keep current as jobs come and go; a job that runs but produces garbage still passes its sentinel; the checker needs a host cadence of its own.

## References

- [agent-workspace-architecture — PATTERNS.md](https://github.com/jimy-r/agent-workspace-architecture/blob/main/PATTERNS.md) — production implementation this pattern is extracted from (freshness-checker detail in META_ARCHITECTURE.md)
- [Healthchecks.io](https://healthchecks.io/) — the cron-monitoring service that established the missing-success inversion for human jobs

</details>
