Advanced Orchestration Engines ⏱ 12 min read 📁 examples/15_delegation.mjs

Lesson 26: Context Management and Compaction

Ensure models never lose direction or context: global objective threading, deterministic foldContext markers, history compaction, sliding windows, and save_artifact.

1. Why This Feature Exists

Context window exhaustion and silent history truncation cause subtle, catastrophic agent hallucinations. Merci SDK guarantees that no turn is ever dropped without an explicit, verifiable marker.

2. Key Symbols and Exports

withObjective(objective)
Rides into session runs and subagent briefs as [Global Objective] injection.
foldContext()
Deterministic folding primitive: replaces stale turns with summaries or explicit markers — zero silent drops.
compactHistory() & Loss Markers
Opt-in LLM history compaction with fallback loss markers if summarizer fails.
StateMachine Context Window
maxContextEntries bounds active view and explicitly announces what is out of view.
save_artifact tool
Persists large payloads (logs, data dumps) to disk and passes lightweight references.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel
} from 'merci-sdk';
import { foldContext } from 'merci-sdk';
import { compactHistory } from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

// 1. Objective Threading
const session = client.session(getDefaultModel({ provider: PROVIDER }))
    .withObjective('Ensure zero regressions during v2 database schema migration.');

// 2. Deterministic Context Folding
const rawMessages = [
    { role: 'user', content: 'Step 1 output...' },
    { role: 'assistant', content: 'Acknowledged.' },
    { role: 'user', content: 'Step 50 output...' }
];

const folded = foldContext(rawMessages, {
    maxEntries: 4,
    summaryMarker: '[CONTEXT FOLDED: Steps 1-48 summarized to disk]'
});

console.log('Folded Messages count:', folded.length);

4. Wire and Telemetry Mechanics

Folded markers and loss tags are injected into the message row at deterministic boundaries. The wire payload stays lean while maintaining total auditability.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/15_delegation.mjs

Read the full example: examples/15_delegation.mjs →

Expected Output: Demonstrates objective threading across subagents, deterministic folding, compaction with loss markers, and artifact saving.