repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/iq/core.ts
RawFile outline
- RECORD_VERSION line 7
- RUBRIC_VERSION line 8
- PROMPT_VERSION line 9
- CHUNK_TARGET_CHARS line 10
- MIN_USER_MESSAGES line 11
- MIN_TOOL_RESULTS line 12
- SESSION_SETTLE_MS line 13
- DIMENSIONS line 15
- DimensionName line 53
- IqSettings line 55
- judgeModel line 56
- NormalizedEvent line 59
- id line 60
- at line 61
- kind line 62
- SourceSignature line 66
- path line 67
- size line 68
- mtimeMs line 69
- PreparedSession line 72
- source line 73
- events line 86
- chunks line 87
- sourceChars line 88
- eligibility line 89
- SessionPlan line 92
- source line 93
- sourceChars line 94
- chunkCount line 95
- eligibility line 96
- SessionEligibility line 99
- EvidenceObservation line 106
- dimension line 107
- rating line 108
- importance line 109
- confidence line 110
- eventIds line 111
- observation line 112
- sourceChunk line 113
- DimensionScore line 116
- score line 117
- meanRating line 118
- evidence line 119
- evidenceWeight line 120
- ScoreCard line 123
- overall line 124
- observedDimensionWeight line 125
- dimensions line 126
- JudgeUsage line 129
- input line 130
- output line 131
- cacheRead line 132
- cacheWrite line 133
- totalTokens line 134
- cost line 135
- calls line 136
- retries line 137
- SessionScoreRecord line 140
- version line 141
- rubricVersion line 142
- promptVersion line 143
- source line 144
- judge line 145
- score line 146
- observations line 147
- usage line 148
- chunkCount line 149
- elapsedMs line 150
- scoredAt line 151
- ModelAggregate line 154
- model line 155
- score line 156
- sessions line 157
- minimum line 158
- maximum line 159
- lastScoredAt line 160
- dimensions line 161
- evidence line 162
- ScanEstimate line 165
- calls line 166
- inputTokens line 167
- outputTokens line 168
- cost line 169
- isRecord line 172
- settingBlock line 176
- readIqSettings line 180
- defaultModelReference line 198
- parseModelReference line 214
- textContent line 225
- text line 230
- type line 230
- boundText line 237
- compactValue line 244
- normalizeMessageEntry line 258
- text line 279
- type line 279
- normalizeEntry line 326
- fileSha256 line 375
- chunkEvents line 387
- eligibilityFor line 408
- prepareSession line 428
- sessionPlan line 510
- reduceScore line 519
- emptyJudgeUsage line 566
- addUsage line 579
- ratesFor line 594
- estimateScan line 604
- aggregateModels line 631
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createInterface } from "node:readline";
import type { Api, Model, Usage } from "@earendil-works/pi-ai";
export const RECORD_VERSION = 1;
export const RUBRIC_VERSION = 1;
export const PROMPT_VERSION = 1;
export const CHUNK_TARGET_CHARS = 50_000;
export const MIN_USER_MESSAGES = 3;
export const MIN_TOOL_RESULTS = 1;
export const SESSION_SETTLE_MS = 5 * 60 * 1_000;
export const DIMENSIONS = [
{
name: "comprehension_judgment",
label: "judgment",
weight: 0.25,
description:
"Understands the actual goal and constraints, finds root causes, chooses proportional scope, and makes sound engineering decisions.",
},
{
name: "reasoning_adaptation",
label: "adaptation",
weight: 0.25,
description:
"Forms and tests useful hypotheses, integrates evidence, notices mistakes, and adapts rather than defending a failed path.",
},
{
name: "context_management",
label: "context",
weight: 0.2,
description:
"Retains decisions and constraints across a long trajectory, uses compaction and harness context well, and avoids repeated drift.",
},
{
name: "execution_reliability",
label: "reliability",
weight: 0.2,
description:
"Uses tools effectively, preserves safety boundaries and unrelated work, validates claims, and closes the requested loop.",
},
{
name: "collaboration_steerability",
label: "steerability",
weight: 0.1,
description:
"Responds precisely to steering and corrections, communicates decision-relevant information, and leaves authority with the engineer.",
},
] as const;
export type DimensionName = (typeof DIMENSIONS)[number]["name"];
export interface IqSettings {
judgeModel?: string | null;
}
export interface NormalizedEvent {
id: string;
at?: string;
kind: string;
[key: string]: unknown;
}
export interface SourceSignature {
path: string;
size: number;
mtimeMs: number;
}
export interface PreparedSession {
source: SourceSignature & {
sha256: string;
sessionId: string;
name: string;
cwd: string;
startedAt?: string;
endedAt?: string;
model?: string;
userMessages: number;
assistantMessages: number;
toolResults: number;
models: string[];
};
events: NormalizedEvent[];
chunks: NormalizedEvent[][];
sourceChars: number;
eligibility: SessionEligibility;
}
export interface SessionPlan {
source: PreparedSession["source"];
sourceChars: number;
chunkCount: number;
eligibility: SessionEligibility;
}
export type SessionEligibility =
| { ranked: true }
| {
ranked: false;
reason: "trivial" | "mixed-model" | "model-missing" | "settling";
};
export interface EvidenceObservation {
dimension: DimensionName;
rating: number;
importance: number;
confidence: number;
eventIds: string[];
observation: string;
sourceChunk: number;
}
export interface DimensionScore {
score: number | null;
meanRating: number | null;
evidence: number;
evidenceWeight: number;
}
export interface ScoreCard {
overall: number | null;
observedDimensionWeight: number;
dimensions: Record<DimensionName, DimensionScore>;
}
export interface JudgeUsage {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
totalTokens: number;
cost: number;
calls: number;
retries: number;
}
export interface SessionScoreRecord {
version: typeof RECORD_VERSION;
rubricVersion: typeof RUBRIC_VERSION;
promptVersion: typeof PROMPT_VERSION;
source: PreparedSession["source"];
judge: string;
score: ScoreCard;
observations: EvidenceObservation[];
usage: JudgeUsage;
chunkCount: number;
elapsedMs: number;
scoredAt: string;
}
export interface ModelAggregate {
model: string;
score: number;
sessions: number;
minimum: number;
maximum: number;
lastScoredAt: string;
dimensions: Record<DimensionName, number | null>;
evidence: number;
}
export interface ScanEstimate {
calls: number;
inputTokens: number;
outputTokens: number;
cost: number;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function settingBlock(value: unknown): Record<string, unknown> {
return isRecord(value) ? value : {};
}
export function readIqSettings(
globalSettings: unknown,
projectSettings: unknown,
): IqSettings {
const global = settingBlock(globalSettings);
const project = settingBlock(projectSettings);
const merged = {
...settingBlock(global.iq),
...settingBlock(project.iq),
};
if (!("judgeModel" in merged)) return {};
if (merged.judgeModel === null) return { judgeModel: null };
if (typeof merged.judgeModel !== "string" || !merged.judgeModel.trim()) {
throw new Error("iq.judgeModel must be provider/model or null");
}
return { judgeModel: merged.judgeModel.trim() };
}
export function defaultModelReference(
globalSettings: unknown,
projectSettings: unknown,
): string | undefined {
const global = settingBlock(globalSettings);
const project = settingBlock(projectSettings);
const provider = project.defaultProvider ?? global.defaultProvider;
const model = project.defaultModel ?? global.defaultModel;
return typeof provider === "string" &&
typeof model === "string" &&
provider.trim() &&
model.trim()
? `${provider.trim()}/${model.trim()}`
: undefined;
}
export function parseModelReference(
reference: string,
): { provider: string; modelId: string } | undefined {
const separator = reference.indexOf("/");
if (separator <= 0 || separator === reference.length - 1) return undefined;
return {
provider: reference.slice(0, separator),
modelId: reference.slice(separator + 1),
};
}
function textContent(content: unknown): string {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
return content
.filter(
(part): part is { type: "text"; text: string } =>
isRecord(part) && part.type === "text" && typeof part.text === "string",
)
.map((part) => part.text)
.join("\n");
}
function boundText(value: unknown, maximum: number): string {
const text = String(value ?? "").replaceAll("\0", "");
if (text.length <= maximum) return text;
const side = Math.floor((maximum - 80) / 2);
return `${text.slice(0, side)}\n…[${text.length - side * 2} chars omitted]…\n${text.slice(-side)}`;
}
function compactValue(value: unknown, depth = 0): unknown {
if (depth > 4) return "[depth omitted]";
if (typeof value === "string") return boundText(value, 1_200);
if (Array.isArray(value))
return value.slice(0, 20).map((item) => compactValue(item, depth + 1));
if (isRecord(value)) {
const result: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value).slice(0, 30))
result[key] = compactValue(child, depth + 1);
return result;
}
return value;
}
function normalizeMessageEntry(
entry: Record<string, unknown>,
): NormalizedEvent | undefined {
if (!isRecord(entry.message) || typeof entry.id !== "string")
return undefined;
const message = entry.message;
const common = {
id: entry.id,
at: typeof entry.timestamp === "string" ? entry.timestamp : undefined,
};
if (message.role === "user") {
return {
...common,
kind: "user",
text: boundText(textContent(message.content), 8_000),
};
}
if (message.role === "assistant") {
const blocks = Array.isArray(message.content) ? message.content : [];
const text = blocks
.filter(
(block): block is { type: "text"; text: string } =>
isRecord(block) &&
block.type === "text" &&
typeof block.text === "string",
)
.map((block) => block.text)
.join("\n");
const toolCalls = blocks
.filter(
(block): block is Record<string, unknown> =>
isRecord(block) &&
block.type === "toolCall" &&
typeof block.name === "string",
)
.map((block) => ({
name: block.name,
arguments: compactValue(block.arguments),
}));
return {
...common,
kind: "assistant",
model:
typeof message.provider === "string" &&
typeof message.model === "string"
? `${message.provider}/${message.model}`
: undefined,
stopReason: message.stopReason,
errorMessage: boundText(message.errorMessage, 1_000),
text: boundText(text, 4_000),
toolCalls,
};
}
if (message.role === "toolResult") {
return {
...common,
kind: "toolResult",
tool: message.toolName,
isError: message.isError === true,
text: boundText(
textContent(message.content),
message.isError === true ? 4_000 : 2_000,
),
};
}
return undefined;
}
function normalizeEntry(
entry: Record<string, unknown>,
): NormalizedEvent | undefined {
if (entry.type === "message") return normalizeMessageEntry(entry);
if (typeof entry.id !== "string") return undefined;
const common = {
id: entry.id,
at: typeof entry.timestamp === "string" ? entry.timestamp : undefined,
};
if (entry.type === "compaction") {
return {
...common,
kind: "compaction",
tokensBefore: entry.tokensBefore,
summary: boundText(entry.summary, 6_000),
implementation:
isRecord(entry.details) && isRecord(entry.details.decay)
? "decay"
: "default",
};
}
if (entry.type === "model_change")
return {
...common,
kind: "modelChange",
model: `${entry.provider}/${entry.modelId}`,
};
if (entry.type === "thinking_level_change")
return {
...common,
kind: "thinkingLevelChange",
thinkingLevel: entry.thinkingLevel,
};
if (entry.type === "branch_summary")
return {
...common,
kind: "branchSummary",
summary: boundText(entry.summary, 4_000),
};
if (entry.type === "custom_message")
return {
...common,
kind: "customMessage",
customType: entry.customType,
text: boundText(textContent(entry.content), 2_000),
};
return undefined;
}
export async function fileSha256(
path: string,
signal?: AbortSignal,
): Promise<string> {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) {
signal?.throwIfAborted();
hash.update(chunk);
}
return hash.digest("hex");
}
export function chunkEvents(
events: readonly NormalizedEvent[],
targetChars = CHUNK_TARGET_CHARS,
): NormalizedEvent[][] {
const chunks: NormalizedEvent[][] = [];
let current: NormalizedEvent[] = [];
let chars = 0;
for (const event of events) {
const eventChars = JSON.stringify(event).length;
if (current.length > 0 && chars + eventChars > targetChars) {
chunks.push(current);
current = [];
chars = 0;
}
current.push(event);
chars += eventChars;
}
if (current.length > 0) chunks.push(current);
return chunks;
}
export function eligibilityFor(input: {
userMessages: number;
toolResults: number;
models: readonly string[];
mtimeMs: number;
now?: number;
}): SessionEligibility {
if ((input.now ?? Date.now()) - input.mtimeMs < SESSION_SETTLE_MS)
return { ranked: false, reason: "settling" };
if (input.models.length === 0)
return { ranked: false, reason: "model-missing" };
if (input.models.length > 1) return { ranked: false, reason: "mixed-model" };
if (
input.userMessages < MIN_USER_MESSAGES ||
input.toolResults < MIN_TOOL_RESULTS
)
return { ranked: false, reason: "trivial" };
return { ranked: true };
}
export async function prepareSession(
path: string,
now = Date.now(),
signal?: AbortSignal,
): Promise<PreparedSession> {
const before = await stat(path);
const events: NormalizedEvent[] = [];
const models = new Set<string>();
let sessionId = "";
let name = "";
let cwd = "";
let startedAt: string | undefined;
let endedAt: string | undefined;
let userMessages = 0;
let assistantMessages = 0;
let toolResults = 0;
const hash = createHash("sha256");
const stream = createReadStream(path);
stream.on("data", (data) => hash.update(data));
const lines = createInterface({ input: stream, crlfDelay: Infinity });
for await (const line of lines) {
signal?.throwIfAborted();
if (!line.trim()) continue;
const parsed: unknown = JSON.parse(line);
if (!isRecord(parsed)) continue;
if (parsed.type === "session") {
if (typeof parsed.id === "string") sessionId = parsed.id;
if (typeof parsed.cwd === "string") cwd = parsed.cwd;
if (typeof parsed.timestamp === "string") startedAt = parsed.timestamp;
continue;
}
if (typeof parsed.timestamp === "string") endedAt = parsed.timestamp;
if (parsed.type === "session_info" && typeof parsed.name === "string")
name = parsed.name;
const event = normalizeEntry(parsed);
if (!event) continue;
events.push(event);
if (event.kind === "user") userMessages++;
if (event.kind === "toolResult") toolResults++;
if (event.kind === "assistant") {
assistantMessages++;
if (typeof event.model === "string") models.add(event.model);
}
}
const after = await stat(path);
if (before.size !== after.size || before.mtimeMs !== after.mtimeMs)
throw new Error("session changed while being read");
const chunks = chunkEvents(events);
const modelList = [...models].sort();
return {
source: {
path,
size: after.size,
mtimeMs: after.mtimeMs,
sha256: hash.digest("hex"),
sessionId,
name,
cwd,
startedAt,
endedAt,
model: modelList.length === 1 ? modelList[0] : undefined,
userMessages,
assistantMessages,
toolResults,
models: modelList,
},
events,
chunks,
sourceChars: events.reduce(
(total, event) => total + JSON.stringify(event).length,
0,
),
eligibility: eligibilityFor({
userMessages,
toolResults,
models: modelList,
mtimeMs: after.mtimeMs,
now,
}),
};
}
export function sessionPlan(prepared: PreparedSession): SessionPlan {
return {
source: prepared.source,
sourceChars: prepared.sourceChars,
chunkCount: prepared.chunks.length,
eligibility: prepared.eligibility,
};
}
export function reduceScore(
observations: readonly EvidenceObservation[],
): ScoreCard {
const dimensions = {} as Record<DimensionName, DimensionScore>;
let weightedScore = 0;
let observedDimensionWeight = 0;
for (const definition of DIMENSIONS) {
const found = observations.filter(
(observation) => observation.dimension === definition.name,
);
if (found.length === 0) {
dimensions[definition.name] = {
score: null,
meanRating: null,
evidence: 0,
evidenceWeight: 0,
};
continue;
}
let weightedRating = 9;
let totalWeight = 3;
for (const observation of found) {
const weight = observation.importance * observation.confidence;
weightedRating += observation.rating * weight;
totalWeight += weight;
}
const meanRating = weightedRating / totalWeight;
const score = Number((100 + 15 * (meanRating - 3)).toFixed(1));
dimensions[definition.name] = {
score,
meanRating: Number(meanRating.toFixed(3)),
evidence: found.length,
evidenceWeight: Number((totalWeight - 3).toFixed(2)),
};
weightedScore += score * definition.weight;
observedDimensionWeight += definition.weight;
}
return {
overall:
observedDimensionWeight > 0
? Number((weightedScore / observedDimensionWeight).toFixed(1))
: null,
observedDimensionWeight: Number(observedDimensionWeight.toFixed(2)),
dimensions,
};
}
export function emptyJudgeUsage(): JudgeUsage {
return {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: 0,
calls: 0,
retries: 0,
};
}
export function addUsage(
total: JudgeUsage,
usage: Usage,
attempts: number,
): void {
total.input += usage.input;
total.output += usage.output;
total.cacheRead += usage.cacheRead;
total.cacheWrite += usage.cacheWrite;
total.totalTokens += usage.totalTokens;
total.cost += usage.cost.total;
total.calls++;
total.retries += attempts - 1;
}
function ratesFor(model: Model<Api>, inputTokens: number) {
let rates = model.cost;
for (const tier of [...(model.cost.tiers ?? [])].sort(
(left, right) => left.inputTokensAbove - right.inputTokensAbove,
)) {
if (inputTokens > tier.inputTokensAbove) rates = tier;
}
return rates;
}
export function estimateScan(
plans: readonly SessionPlan[],
model: Model<Api>,
): ScanEstimate {
let calls = 0;
let inputTokens = 0;
let outputTokens = 0;
let cost = 0;
for (const plan of plans) {
const sourcePerChunk =
plan.chunkCount > 0 ? plan.sourceChars / 4 / plan.chunkCount : 0;
for (let chunk = 0; chunk < plan.chunkCount; chunk++) {
const requestInput = Math.ceil(
sourcePerChunk + 1_800 + Math.min(chunk * 350, 12_000),
);
const requestOutput = 400;
const rates = ratesFor(model, requestInput);
calls++;
inputTokens += requestInput;
outputTokens += requestOutput;
cost +=
(requestInput * rates.input + requestOutput * rates.output) / 1_000_000;
}
}
return { calls, inputTokens, outputTokens, cost };
}
export function aggregateModels(
records: readonly SessionScoreRecord[],
): ModelAggregate[] {
const byModel = new Map<string, SessionScoreRecord[]>();
for (const record of records) {
if (!record.source.model || record.score.overall === null) continue;
const found = byModel.get(record.source.model) ?? [];
found.push(record);
byModel.set(record.source.model, found);
}
const result: ModelAggregate[] = [];
for (const [model, modelRecords] of byModel) {
const scores = modelRecords
.map((record) => record.score.overall)
.filter((score): score is number => score !== null);
const dimensions = {} as Record<DimensionName, number | null>;
for (const definition of DIMENSIONS) {
const found = modelRecords
.map((record) => record.score.dimensions[definition.name].score)
.filter((score): score is number => score !== null);
dimensions[definition.name] = found.length
? Number(
(
found.reduce((sum, score) => sum + score, 0) / found.length
).toFixed(1),
)
: null;
}
result.push({
model,
score: Number(
(scores.reduce((sum, score) => sum + score, 0) / scores.length).toFixed(
1,
),
),
sessions: modelRecords.length,
minimum: Math.min(...scores),
maximum: Math.max(...scores),
lastScoredAt:
modelRecords
.map((record) => record.scoredAt)
.sort()
.at(-1) ?? "",
dimensions,
evidence: modelRecords.reduce(
(total, record) => total + record.observations.length,
0,
),
});
}
return result.sort(
(left, right) =>
right.score - left.score || left.model.localeCompare(right.model),
);
}