π OMP EXTENSION SPEEDRUN MASTERCLASS
Status: 100% Perfected & Synthesized Objective: Practical Highest-Level Idiot Overstanding of OMP Extensions.
An OMP Extension is a single TypeScript file loaded by the oh-my-pi framework. It exports a default function that binds to the OMP event bus via pi.on().
π‘οΈ The 3 Golden Invariants (Do Not Violate)
- β‘ Zero-Blocking (Async Egress): Never await heavy network or disk I/O in your event handlers. OMP halts while it waits for you. Enqueue payloads and use an out-of-band
setIntervalflusher. - π‘οΈ Zero-Crashing (Safe Wrappers): If your extension throws an unhandled exception, OMP dies. Wrap every hook in a
try/catch(see the Idiot-Proof Skeleton). - π§Ή Zero-Leakage (Redaction):
tool_callandbefore_provider_requestpayloads contain raw LLM prompts, which will include the userβs API keys, JWTs, and passwords. You MUST apply regex scrubbing before writing to disk or network.
πͺ The Definitive Lifecycle Hooks Dictionary
Extracted directly from production extensions (langfuse.ts, ompkeep.ts, orca-agent-status.ts).
π§ Session & Agent Lifecycle
session_startβ Fired once per user execution. Good place to initialize trace IDs.session_shutdownβ Fired on exit. CRITICAL: Use this toclearIntervaland await your final network flush.goal_updatedβ Fired when the sessionβs overarching objective changes.before_agent_start/agent_startβ Fired when a subagent is spawned.agent_endβ Fired when a subagent terminates.
π Turn & Generation (The Core Loop)
turn_start/turn_endβ A βturnβ is one cycle of thinking/acting. End payload containsdurationMsandcontextTokens.before_provider_requestβ Right before the LLM is called. Contains the full prompt.after_provider_responseβ LLM responds. Contains output tokens, latency, cost, and stop reasons.message_endβ Fired when an agent message concludes.
π οΈ Tool Execution
tool_execution_start/tool_callβ Agent requests a tool. Contains raw input arguments (scrub these!).tool_execution_end/tool_resultβ Tool finishes. Contains output/error. Deep-truncate outputs (they can be huge base64 strings).
π¨ Diagnostics & Recovery
session_compactβ Context window exceeded; OMP summarized the history.auto_retry_startβ OMP caught an error and is automatically retrying.ttsr_triggeredβ Test-Time System Prompt Modification triggered (rule injection).
ποΈ The βIdiot-Proofβ Skeleton (Copy-Paste)
This skeleton guarantees you will never crash OMP and never block the main thread.
import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
export default function myGodTierExtension(pi: ExtensionAPI): void {
// 1. STATE & QUEUES
const queue: any[] = [];
let flushTimer: ReturnType<typeof setInterval>;
let pendingFlush = Promise.resolve();
// 2. THE SAFE WRAPPER (Prevents Crashing OMP)
function safeOn(event: string, handler: (...args: any[]) => Promise<void>) {
pi.on(event as any, async (...args: any[]) => {
try { await handler(...args); }
catch (err) { pi.logger.warn(`[MyExt] Error in ${event}: ${String(err)}`); }
});
}
// 3. NON-BLOCKING FLUSHER
function flush() {
if (queue.length === 0) return;
const batch = queue.splice(0);
pendingFlush = pendingFlush.then(async () => {
try {
// e.g., await fetch('...', { body: JSON.stringify(batch), signal: AbortSignal.timeout(5000) });
} catch (e) { /* ignore */ }
});
}
// 4. LIFECYCLE BINDINGS
safeOn("session_start", async (_ev, ctx) => {
flushTimer = setInterval(flush, 2000); // Flush every 2s out-of-band
pi.logger.info("[MyExt] Online.");
});
safeOn("before_provider_request", async (ev) => {
// Redact and push to queue, DO NOT await fetch here!
queue.push({ type: "llm_req", model: ev.model });
});
safeOn("session_shutdown", async () => {
clearInterval(flushTimer);
flush();
await pendingFlush; // Block ONLY on shutdown to guarantee delivery
});
}