πŸŽ“ 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)

  1. ⚑ 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 setInterval flusher.
  2. πŸ›‘οΈ 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).
  3. 🧹 Zero-Leakage (Redaction): tool_call and before_provider_request payloads 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 to clearInterval and 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 contains durationMs and contextTokens.
  • 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
  });
}

0 items under this folder.