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
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.mjsRead the full example: examples/15_delegation.mjs →