repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/prune/index.ts

Raw
File outline
/**
 * prune — Lossless Conversation Compactor
 * 
 * Algorithmic compaction that preserves searchable transcript.
 * Replaces default LLM summarization with deterministic extraction.
 */

import { Type } from 'typebox';
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
import { normalize } from './src/normalize.ts';
import { extract } from './src/extract.ts';
import { format } from './src/format.ts';
import { merge } from './src/merge.ts';
import { recall, formatRecallResults } from './src/recall.ts';
import type { PruneSettings, Message } from './src/types.ts';
import { DEFAULT_SECTION_LIMIT, DEFAULT_TRANSCRIPT_LIMIT } from './src/constants.ts';

// ─── Settings ──────────────────────────────────────────────────────────────

const RECALL_TOOL = 'prune_recall';
const PRUNE_DETAILS_KIND = 'prune';

interface PruneCompactionDetails {
  kind: typeof PRUNE_DETAILS_KIND;
  version: 1;
  sourceEntriesProcessed: number;
  tailKept: number;
}

const DEFAULT_SETTINGS: Required<PruneSettings> = {
  overrideDefault: true,
  sectionLimit: DEFAULT_SECTION_LIMIT,
  transcriptLimit: DEFAULT_TRANSCRIPT_LIMIT,
  toolCapPerTurn: 8,
  debug: false,
};

// ─── State ────────────────────────────────────────────────────────────────

let settings = { ...DEFAULT_SETTINGS };

// ─── Helpers ────────────────────────────────────────────────────────────

function loadSettings(pi: ExtensionAPI): void {
  const raw = (pi as unknown as { settingsManager?: { getSettings?: () => { prune?: PruneSettings } } })
    .settingsManager?.getSettings?.();
  if (raw?.prune) {
    settings = { ...DEFAULT_SETTINGS, ...raw.prune };
  }
}

function isPruneCompaction(entry: unknown): boolean {
  const e = entry as { type?: string; summary?: string; fromHook?: boolean; details?: { kind?: string } };
  if (e?.type !== 'compaction') return false;
  if (e.details?.kind === PRUNE_DETAILS_KIND) return true;
  // Backwards-compatible detection for prune compactions created before details existed.
  return e.fromHook === true && typeof e.summary === 'string' && e.summary.includes('Use prune_recall');
}

function setContains(values: string[], value: string): boolean {
  return values.includes(value);
}

// ─── Core prune function ─────────────────────────────────────────────────

function prune(
  messages: Message[],
  previous?: string,
  metadata: { sourceEntriesProcessed?: number; tailKept?: number; tokenEstimate?: number } = {},
): string {
  const blocks = normalize(messages);
  const data = extract(blocks);

  const output = format(data, {
    sectionLimit: settings.sectionLimit,
    transcriptLimit: settings.transcriptLimit,
    ...metadata,
  });

  const summary = previous ? merge(previous, output.summary) : output.summary;

  if (settings.debug) {
    console.log('[prune]', {
      blocks: blocks.length,
      outputLines: output.stats.messagesOut,
      elapsedMs: output.stats.elapsedMs.toFixed(2),
    });
  }

  return summary;
}

function toPruneMessage(message: unknown): Message | undefined {
  const m = message as {
    role?: string;
    content?: string | Array<{ type: string; text?: string; name?: string; arguments?: Record<string, unknown>; thinking?: string }>;
    toolName?: string;
    isError?: boolean;
    command?: string;
    output?: string;
    exitCode?: number;
    summary?: string;
  };

  switch (m.role) {
    case 'user':
      return { role: 'user', content: m.content };
    case 'assistant':
      return { role: 'assistant', content: m.content };
    case 'tool':
    case 'toolResult':
      return {
        role: 'tool',
        content: m.content,
        toolName: m.toolName,
        isError: m.isError,
      };
    case 'bashExecution':
      return {
        role: 'tool',
        content: m.output ?? '',
        toolName: 'bash',
        isError: typeof m.exitCode === 'number' ? m.exitCode !== 0 : false,
      };
    case 'branchSummary':
    case 'compactionSummary':
      return m.summary ? { role: 'assistant', content: m.summary } : undefined;
    case 'custom':
      return undefined;
    default:
      if (settings.debug) console.log('[prune] skipped unsupported message role', m.role);
      return undefined;
  }
}

// ─── Extension ────────────────────────────────────────────────────────────

export default function (pi: ExtensionAPI) {
  loadSettings(pi);

  function enableRecallTool(): void {
    const active = pi.getActiveTools();
    if (!setContains(active, RECALL_TOOL)) pi.setActiveTools([...active, RECALL_TOOL]);
  }

  function disableRecallTool(): void {
    const active = pi.getActiveTools();
    if (setContains(active, RECALL_TOOL)) pi.setActiveTools(active.filter((name) => name !== RECALL_TOOL));
  }

  function syncRecallTool(ctx: { sessionManager: { getBranch(): unknown[] } }): void {
    const hasPruneSummary = ctx.sessionManager.getBranch().some(isPruneCompaction);
    if (hasPruneSummary) enableRecallTool();
    else disableRecallTool();
  }

  // ─── session_before_compact ──────────────────────────────────────────

  pi.on('session_before_compact', async (event) => {
    const { preparation } = event;

    if (!settings.overrideDefault) return;

    const allMessages = [
      ...preparation.messagesToSummarize,
      ...preparation.turnPrefixMessages,
    ].map(toPruneMessage).filter((message): message is Message => message !== undefined);

    const summary = prune(allMessages, preparation.previousSummary, {
      sourceEntriesProcessed: allMessages.length,
      tailKept: preparation.turnPrefixMessages.length,
      tokenEstimate: preparation.tokensBefore,
    });

    const details: PruneCompactionDetails = {
      kind: PRUNE_DETAILS_KIND,
      version: 1,
      sourceEntriesProcessed: allMessages.length,
      tailKept: preparation.turnPrefixMessages.length,
    };

    return {
      compaction: {
        summary,
        firstKeptEntryId: preparation.firstKeptEntryId,
        tokensBefore: preparation.tokensBefore,
        details,
      },
    };
  });

  // ─── recall tool activation ──────────────────────────────────────────

  pi.on('session_start', async (_event, ctx) => {
    syncRecallTool(ctx);
  });

  pi.on('session_tree', async (_event, ctx) => {
    syncRecallTool(ctx);
  });

  // ─── session_compact ─────────────────────────────────────────────────

  pi.on('session_compact', async (event, ctx) => {
    if (!event.fromExtension || !isPruneCompaction(event.compactionEntry)) return;
    enableRecallTool();
    const entry = event.compactionEntry as { id?: string; summary?: string; tokensBefore?: number };
    const lineCount = entry.summary?.split('\n').length ?? 0;
    const msg = `prune compaction saved${entry.id ? ` #${entry.id}` : ''}: ${lineCount} lines${entry.tokensBefore ? ` from ${entry.tokensBefore.toLocaleString()} tok` : ''}`;
    if (settings.debug) console.log('[prune]', msg);
    if (ctx.hasUI) ctx.ui.notify(msg, 'info');
  });

  // ─── Tool: prune_recall ───────────────────────────────────────────────

  pi.registerTool({
    name: 'prune_recall',
    label: 'Prune Recall',
    description: 'Search compacted session history. Returns matching messages with relevance scores.',
    parameters: Type.Object({
      query: Type.String({ description: 'Search query (string or regex pattern)' }),
      scope: Type.Optional(Type.Union([
        Type.Literal('lineage'),
        Type.Literal('all'),
      ])),
      limit: Type.Optional(Type.Number({ minimum: 1, maximum: 20 })),
      expand: Type.Optional(Type.Array(Type.Number())),
    }),

    async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
      const results = recall(ctx.sessionManager, {
        query: params.query,
        scope: params.scope ?? 'lineage',
        limit: params.limit ?? 5,
        expand: params.expand ?? [],
      });
      return {
        content: [{ type: 'text', text: formatRecallResults(results) }],
        details: { count: results.length },
      };
    },
  });

  // ─── Command: /prune ───────────────────────────────────────────────

  pi.registerCommand('prune', {
    description: 'Run lossless compaction: /prune [focus?]',
    handler: async (_args, ctx) => {
      if (settings.debug) console.log('[prune] Manual compaction requested');
      ctx.compact({
        onComplete: (result) => {
          if (ctx.hasUI) ctx.ui.notify(`prune compaction complete: ${result.summary.split('\n').length} lines`, 'info');
        },
        onError: (error) => {
          if (ctx.hasUI) ctx.ui.notify(`prune compaction failed: ${error.message}`, 'error');
          else console.error(`[prune] compaction failed: ${error.message}`);
        },
      });
      if (ctx.hasUI) ctx.ui.notify('prune compaction started', 'info');
    },
  });

  // ─── Command: /prune-recall ────────────────────────────────────────

  pi.registerCommand('prune-recall', {
    description: 'Search compacted history: /prune-recall <query> [scope]',
    handler: async (args, ctx) => {
      const parts = args.trim().split(/\s+/).filter(Boolean);
      const scope = parts.at(-1) === 'all' ? 'all' : 'lineage';
      const query = scope === 'all' ? parts.slice(0, -1).join(' ') : parts.join(' ');
      const results = recall(ctx.sessionManager, { query, scope, limit: 10 });
      const text = formatRecallResults(results);
      if (ctx.hasUI) {
        ctx.ui.notify(text.slice(0, 1000), results.length ? 'info' : 'warning');
      } else {
        console.log(text);
      }
    },
  });
}