Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: CI

on:
push:
branches: [main]
pull_request:

jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
- run: bun install --frozen-lockfile
- run: bun run typecheck
- run: bun run lint
- run: bun run format:check
- run: bun test
5 changes: 5 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
dist/
coverage/
bun.lock
*.svg
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"useTabs": true,
"printWidth": 120,
"semi": true,
"singleQuote": false,
"trailingComma": "all"
}
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Local semantic context optimizer for [omp](https://github.com/can1357/oh-my-pi): permanently shrinks session context by LLM-summarizing stale conversation ranges — but only when the projected token savings beat the one-time prompt-cache bust a rewrite costs.

Structural compressors (truncation, headroom-style request trimming) shrink *requests* but never shrink *history*: the full transcript keeps flowing through every call. molt replaces stale ranges in history with dense technical summaries, so every later request is actually smaller. Originals are archived on disk and recoverable verbatim at any time.
Structural compressors (truncation, headroom-style request trimming) shrink _requests_ but never shrink _history_: the full transcript keeps flowing through every call. molt replaces stale ranges in history with dense technical summaries, so every later request is actually smaller. Originals are archived on disk and recoverable verbatim at any time.

## How it works

Expand Down Expand Up @@ -64,13 +64,13 @@ Disable your structural compressor after parity (e.g. `omp plugin disable omp-he

`.omp/molt.json` in the working directory; missing keys fall back to defaults:

| Key | Default | Meaning |
|---|---|---|
| `auto` | `true` | scheduler-driven molting; `false` = model-invoked only |
| `maxContextPercent` | `0.7` | usage ratio above which the gate may fire |
| `protectTurns` | `2` | tool outputs younger than this are never candidates |
| `maxRangeTokens` | `20000` | max estimated tokens per summarized range |
| `model` | `"@smol"` | summarizer model spec, resolved via `ctx.models.resolve` |
| Key | Default | Meaning |
| ------------------- | --------- | -------------------------------------------------------- |
| `auto` | `true` | scheduler-driven molting; `false` = model-invoked only |
| `maxContextPercent` | `0.7` | usage ratio above which the gate may fire |
| `protectTurns` | `2` | tool outputs younger than this are never candidates |
| `maxRangeTokens` | `20000` | max estimated tokens per summarized range |
| `model` | `"@smol"` | summarizer model spec, resolved via `ctx.models.resolve` |

## Tools & commands

Expand Down
181 changes: 181 additions & 0 deletions bun.lock

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions eslint.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import tseslint from "typescript-eslint";

export default [
{ ignores: ["node_modules", "dist", "coverage"] },
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unsafe-function-type": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_", caughtErrorsIgnorePattern: "^_" },
],
},
},
];
1 change: 1 addition & 0 deletions molt-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Build a new omp extension, **molt** (`~/projects/woss/molt`, npm package name `omp-molt`), that does what Sleev does locally: permanently shrinks session context by LLM-summarizing stale conversation ranges, scheduling rewrites only when projected savings beat the one-time prompt-cache bust. This replaces the structural-compression role of the `omp-headroom` fork (which trims requests but never shrinks history). User decisions: name `molt`; headroom is **disabled after parity** (not uninstalled); summarizer model is **configurable, default omp `@smol` role**.

Verified ground truth this plan relies on:

- omp extension API (docs/extensions.md on can1357/oh-my-pi): `pi.on(...)`, `pi.registerTool`, `pi.registerCommand`, `pi.appendEntry(customType, data)` + `ctx.sessionManager.getBranch()` for persistence, `ctx.getContextUsage()`, `ctx.models.resolve(spec)` / `ctx.models.current()`, `before_agent_start` returns `{systemPrompt}`, `context` event receives `{messages}` and returns `{messages}`, `tool_call`/`tool_result` events, 30s handler budget (2s on `session_shutdown`).
- Model invocation from an extension: `import { complete } from "@oh-my-pi/pi-ai"` with a model from `ctx.models.resolve(selector)` — proven pattern from alesha-pro/omp-statecompact `src/index.ts:4,115,231`.
- Splice machinery to port: complexthings/pi-dynamic-context-pruning (`pruner.ts`, `state.ts`, `compress-tool.ts`) — full shapes and pipeline captured in DcpScan findings below.
Expand Down
19 changes: 15 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,29 @@
"license": "MIT",
"type": "module",
"exports": "./src/index.ts",
"files": ["src", "README.md"],
"files": [
"src",
"README.md"
],
"omp": {
"extensions": ["./src/index.ts"]
"extensions": [
"./src/index.ts"
]
},
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run"
"test": "vitest run",
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check ."
},
"devDependencies": {
"@oh-my-pi/pi-coding-agent": "17.0.6",
"@oh-my-pi/pi-ai": "17.0.6",
"@oh-my-pi/pi-coding-agent": "17.0.6",
"eslint": "^10.15.0",
"prettier": "^3.10.1",
"typescript": "^5.9.3",
"typescript-eslint": "^8.73.0",
"vitest": "^5.1.1"
}
}
4 changes: 2 additions & 2 deletions server/molt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ export async function moltStatsHandler(_input: RpcInput<typeof moltStats>) {
try {
const sessionsDir = join(homedir(), ".omp", "agent", "sessions");
let newest: { file: string; mtime: number } | null = null;
for (const slug of readdirSyncFs(sessionsDir)) {
for (const slug of readdirSync(sessionsDir)) {
try {
for (const f of readdirSyncFs(join(sessionsDir, slug))) {
for (const f of readdirSync(join(sessionsDir, slug))) {
if (!f.endsWith(".jsonl")) continue;
const full = join(sessionsDir, slug, f);
const mtime = statSync(full).mtimeMs;
Expand Down
34 changes: 22 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,7 @@

import type { ExtensionAPI } from "@oh-my-pi/pi-coding-agent";
import { persistOriginal } from "./archive.ts";
import {
CONTEXT_SOFT_NUDGE,
CONTEXT_STRONG_NUDGE,
ITERATION_NUDGE,
MOLT_SYSTEM_PROMPT,
TURN_NUDGE,
} from "./prompt.ts";
import { CONTEXT_SOFT_NUDGE, CONTEXT_STRONG_NUDGE, ITERATION_NUDGE, MOLT_SYSTEM_PROMPT, TURN_NUDGE } from "./prompt.ts";
import {
createState,
deserializeMoltState,
Expand All @@ -18,7 +12,13 @@ import {
} from "./state.ts";
import { loadConfig, shouldAutoMolt, type MoltConfig } from "./scheduler.ts";
import { summarizeRanges } from "./summarizer.ts";
import { applyPruning, collectRangeMessages, estimateMessageTokens, estimateRangeSourceTokens, estimateTokens } from "./splicer.ts";
import {
applyPruning,
collectRangeMessages,
estimateMessageTokens,
estimateRangeSourceTokens,
estimateTokens,
} from "./splicer.ts";
import { cacheEconomics } from "./telemetry.ts";
import { createBlocks, registerTools } from "./tools.ts";

Expand Down Expand Up @@ -174,7 +174,11 @@ export default function molt(pi: ExtensionAPI) {
async function runAutoMolt(toolCallIds: string[]): Promise<void> {
const ctx = latestCtx;
if (!ctx) return;
const messages = ctx.sessionManager?.getBranch?.().filter((e: any) => e.messages).flatMap((e: any) => e.messages) ?? [];
const messages =
ctx.sessionManager
?.getBranch?.()
.filter((e: any) => e.messages)
.flatMap((e: any) => e.messages) ?? [];
const idTargets = toolCallIds
.map((id) => state.toolCalls.get(id))
.filter((r): r is NonNullable<typeof r> => r !== undefined && r.timestamp > 0);
Expand All @@ -186,9 +190,15 @@ export default function molt(pi: ExtensionAPI) {

const model = await ctx.models.resolve(config.model);
const resolved = model ?? (await ctx.models.resolve("current")) ?? ctx.models.current();
const summary = await summarizeRanges({ ...ctx, models: { resolve: () => Promise.resolve(resolved) } }, ranges, messages, {
model: config.model,
}, state);
const summary = await summarizeRanges(
{ ...ctx, models: { resolve: () => Promise.resolve(resolved) } },
ranges,
messages,
{
model: config.model,
},
state,
);

// Archive the raw messages inside the summarized ranges, then embed the marker.
const originals = collectRangeMessages(messages, state, summary.ranges);
Expand Down
3 changes: 2 additions & 1 deletion src/prompt.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// molt — prompt text

export const SUMMARIZER_SYSTEM_PROMPT = `You compress stale agent conversation ranges. Return JSON {topic, ranges:[{startId,endId,summary}]} where each summary is an exhaustive technical summary preserving file paths, commands, errors, decisions, and current values; omit nothing a later engineer needs.`.trim();
export const SUMMARIZER_SYSTEM_PROMPT =
`You compress stale agent conversation ranges. Return JSON {topic, ranges:[{startId,endId,summary}]} where each summary is an exhaustive technical summary preserving file paths, commands, errors, decisions, and current values; omit nothing a later engineer needs.`.trim();

export const MOLT_SYSTEM_PROMPT = `
You operate in a context-constrained environment. Manage context continuously to avoid buildup and preserve retrieval quality.
Expand Down
3 changes: 1 addition & 2 deletions src/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,7 @@ export function shouldAutoMolt(
candidateTokens * economics.readRate * SAVINGS_HORIZON_REQUESTS - bustCost - summarizerCostEstimate;

const fire =
projectSavingsUsd > 0 ||
(economics.readRate === 0 && economics.writeRate === 0 && candidateTokens > 20_000);
projectSavingsUsd > 0 || (economics.readRate === 0 && economics.writeRate === 0 && candidateTokens > 20_000);

return { fire, candidateRanges: fire ? ranges : [], economics, candidateTokens, projectSavingsUsd };
}
27 changes: 9 additions & 18 deletions src/splicer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ export function collectRangeMessages(
const startTs = Math.min(
...ranges.map((r) => state.messageIdSnapshot.get(r.startId.trim()) ?? Number.POSITIVE_INFINITY),
);
const endTs = Math.max(
...ranges.map((r) => state.messageIdSnapshot.get(r.endId.trim()) ?? 0),
);
const endTs = Math.max(...ranges.map((r) => state.messageIdSnapshot.get(r.endId.trim()) ?? 0));
return messages.filter((m) => {
const ts = m.timestamp ?? 0;
return ts >= startTs && ts <= endTs;
Expand Down Expand Up @@ -101,9 +99,7 @@ function applyCompressionBlocks(messages: AnyMsg[], state: MoltState): AnyMsg[]
}
}
const prevContent: any[] = Array.isArray(prev.content) ? prev.content : [];
const hasMatchingToolCalls = prevContent.some(
(b) => b.type === "toolCall" && toolCallIdsInRange.has(b.id),
);
const hasMatchingToolCalls = prevContent.some((b) => b.type === "toolCall" && toolCallIdsInRange.has(b.id));
if (!hasMatchingToolCalls) break;
lo = scanIdx;
}
Expand All @@ -123,7 +119,10 @@ function applyCompressionBlocks(messages: AnyMsg[], state: MoltState): AnyMsg[]
}
while (hi + 1 < messages.length) {
const next = messages[hi + 1]!;
if ((next.role === "toolResult" || next.role === "bashExecution") && assistantToolCallIds.has(next.toolCallId)) {
if (
(next.role === "toolResult" || next.role === "bashExecution") &&
assistantToolCallIds.has(next.toolCallId)
) {
hi++;
} else if (PASSTHROUGH_ROLES.has(next.role)) {
hi++;
Expand All @@ -146,9 +145,7 @@ function applyCompressionBlocks(messages: AnyMsg[], state: MoltState): AnyMsg[]
text: `[Molted section: ${block.topic}]\n\n${block.summary}\n\n<molt-block-id>b${block.id}</molt-block-id>`,
},
],
timestamp: Number.isFinite(block.anchorTimestamp)
? block.anchorTimestamp - 0.5
: block.endTimestamp + 0.5,
timestamp: Number.isFinite(block.anchorTimestamp) ? block.anchorTimestamp - 0.5 : block.endTimestamp + 0.5,
};

const addedTokens = estimateMessageTokens(syntheticMsg);
Expand Down Expand Up @@ -237,9 +234,7 @@ function applyToolOutputPruning(messages: AnyMsg[], state: MoltState): void {
msg.content = [
{
type: "text",
text: msg.isError
? "[Error output removed]"
: "[Output removed — duplicate of a later identical call]",
text: msg.isError ? "[Error output removed]" : "[Output removed — duplicate of a later identical call]",
},
];
}
Expand Down Expand Up @@ -298,11 +293,7 @@ function injectMessageIds(messages: AnyMsg[], state: MoltState): void {
if (firstToolCallIdx === -1) {
msg.content = [...msg.content, idBlock];
} else {
msg.content = [
...msg.content.slice(0, firstToolCallIdx),
idBlock,
...msg.content.slice(firstToolCallIdx),
];
msg.content = [...msg.content.slice(0, firstToolCallIdx), idBlock, ...msg.content.slice(firstToolCallIdx)];
}
} else if (typeof msg.content === "string") {
msg.content = msg.content + idTag;
Expand Down
4 changes: 1 addition & 3 deletions src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ export function deserializeMoltState(raw: unknown): Partial<MoltState> | undefin
}));
return {
compressionBlocks: validBlocks,
nextBlockId:
data.nextBlockId ??
(validBlocks.length > 0 ? Math.max(0, ...validBlocks.map((b) => b.id)) + 1 : 1),
nextBlockId: data.nextBlockId ?? (validBlocks.length > 0 ? Math.max(0, ...validBlocks.map((b) => b.id)) + 1 : 1),
prunedToolIds: new Set(data.prunedToolIds ?? []),
tokensSaved: data.tokensSaved ?? 0,
readRate: data.readRate ?? 0,
Expand Down
4 changes: 3 additions & 1 deletion src/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export interface CacheEconomics {
}

/** Real cache rates ($/token) from ctx.model.cost; 0/0 when unknown (favors rewriting). */
export function cacheEconomics(model: { cost?: { input?: unknown; cacheRead?: unknown; cacheWrite?: unknown } } | undefined | null): CacheEconomics {
export function cacheEconomics(
model: { cost?: { input?: unknown; cacheRead?: unknown; cacheWrite?: unknown } } | undefined | null,
): CacheEconomics {
const cost = model?.cost;
if (!cost) return { readRate: 0, writeRate: 0 };
const readRate = asNumber(cost.cacheRead);
Expand Down
17 changes: 10 additions & 7 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ function expandBlockPlaceholders(summary: string, state: MoltState): string {
});
}

function resolveIdToTimestamp(
rawId: string,
field: "startTimestamp" | "endTimestamp",
state: MoltState,
): number {
function resolveIdToTimestamp(rawId: string, field: "startTimestamp" | "endTimestamp", state: MoltState): number {
const id = rawId.trim();
const blockMatch = id.match(/^b(\d+)$/i);
if (blockMatch) {
Expand Down Expand Up @@ -128,10 +124,17 @@ export function registerTools(pi: ExtensionAPI, state: MoltState): void {
{ description: "One or more ranges to molt" },
),
}),
async execute(_toolCallId, params: { topic: string; ranges: Array<{ startId: string; endId: string; summary: string }> }, _signal, _onUpdate, ctx) {
async execute(
_toolCallId,
params: { topic: string; ranges: Array<{ startId: string; endId: string; summary: string }> },
_signal,
_onUpdate,
ctx,
) {
// Archive originals + embed the recall marker, same contract as runAutoMolt.
const messages =
ctx?.sessionManager?.getBranch?.()
ctx?.sessionManager
?.getBranch?.()
.filter((e: any) => e.messages)
.flatMap((e: any) => e.messages) ?? [];
const originals = collectRangeMessages(messages as any[], state, params.ranges);
Expand Down
Loading
Loading