mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-20 06:02:14 +03:00
O adapter descartava o TransformInfo inteiro, então a UI mostrava um número de economia sem dizer de onde ele vinha — contagem do provider, estimativa ou só diferença de bytes. O 1.4.0 expõe normalizeAccounting(), que classifica essa evidência e resolve a semântica de cache por família: Anthropic reporta input, cache-create e cache-read em buckets DISJUNTOS, enquanto OpenAI e xAI reportam cached como SUBCONJUNTO do input. Somar à mão dá double-count silencioso. O novo omniglyphTelemetry.ts não filtra por denylist — MONTA um objeto novo, campo a campo, só com número e enum. TransformInfo mistura contadores inofensivos com material que não pode ser persistido: bytes PNG, imageSourceText(s), recoverable[].text, os sha8 de system/CLAUDE.md/primeira mensagem, nomes de tags observadas e o bloco env (cwd, branch, versões). Copiar o objeto inteiro transformaria telemetria de compressão em vazamento de prompt. O teste de negação prova que segredo, caminho do operador, texto do system e base64 não aparecem, e varre a allowlist exigindo que toda string seja de um enum conhecido. - provider threaded do chatCore e do bridge Codex WS até a engine; ausente vira `unknown`, que faz o upstream recusar adivinhar buckets de cache; - contabilidade propagada para o engineBreakdown do passo (o agregado do pipeline soma todas as engines e não serviria); - skip não emite contabilidade: zeros ali seriam indistinguíveis de "a engine nem rodou".
118 lines
5.2 KiB
TypeScript
118 lines
5.2 KiB
TypeScript
/**
|
|
* Core telemetry + step-decision machinery for the stacked compression pipeline, extracted
|
|
* from `strategySelector.ts` so that god-file stays bounded. This module is a leaf: it depends
|
|
* only on the shared compression types, so it never participates in a cycle.
|
|
*
|
|
* It holds the per-run accumulator (`StackAccumulator` + `createStackAccumulator`), the TV1
|
|
* bail-out config + advance decision (`BailoutConfig` + `decideStep`), and the per-step
|
|
* telemetry fold (`mergeStackStep`). The sync/async stacked loops in `strategySelector.ts`
|
|
* consume these.
|
|
*/
|
|
|
|
import type { CompressionResult, CompressionStats } from "./types.ts";
|
|
|
|
/**
|
|
* TV1 — Opt-in bail-out configuration for the stacked pipeline.
|
|
* When enabled: a step that throws is silently skipped (verbatim kept); a step whose gain is
|
|
* below `minGainPercent` is also skipped. DEFAULT = disabled (byte-identical to pre-TV1).
|
|
*/
|
|
export interface BailoutConfig {
|
|
enabled: boolean;
|
|
/** Minimum savings percent required to advance currentBody. Default: 10. */
|
|
minGainPercent?: number;
|
|
}
|
|
|
|
/** Accumulates per-step telemetry across a stacked run (shared sync/async). */
|
|
export interface StackAccumulator {
|
|
techniques: Set<string>;
|
|
rules: Set<string>;
|
|
breakdown: NonNullable<CompressionStats["engineBreakdown"]>;
|
|
rtkRawOutputPointers: NonNullable<CompressionStats["rtkRawOutputPointers"]>;
|
|
validationWarnings: Set<string>;
|
|
validationErrors: Set<string>;
|
|
fallbackApplied: boolean;
|
|
}
|
|
|
|
export function createStackAccumulator(): StackAccumulator {
|
|
return {
|
|
techniques: new Set<string>(),
|
|
rules: new Set<string>(),
|
|
breakdown: [],
|
|
rtkRawOutputPointers: [],
|
|
validationWarnings: new Set<string>(),
|
|
validationErrors: new Set<string>(),
|
|
fallbackApplied: false,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* TV1 — Pure helper that decides whether a completed step should advance `currentBody`. Called
|
|
* only when bail-out is ENABLED; the loops bypass it on the default-off path (zero cost). Returns
|
|
* `{ advance: true }` to accept the step, or `{ advance: false }` to skip it (verbatim kept).
|
|
*/
|
|
export function decideStep(
|
|
result: CompressionResult,
|
|
bailout: BailoutConfig
|
|
): { advance: boolean } {
|
|
if (!result.compressed) return { advance: false };
|
|
// Clamp: a negative minGainPercent would mean "always advance" (invalid state).
|
|
const minGain = Math.max(0, bailout.minGainPercent ?? 10);
|
|
const gain = result.stats?.savingsPercent ?? 0;
|
|
if (gain < minGain) return { advance: false };
|
|
return { advance: true };
|
|
}
|
|
|
|
/**
|
|
* A dispatched step whose engine found nothing eligible (e.g. session-dedup with no repeated
|
|
* blocks, ccr below its min-chars threshold) returns `stats: null` instead of throwing or
|
|
* advancing. Left unrecorded, that step vanishes from the pipeline's telemetry with zero trace —
|
|
* no `engineBreakdown` entry, no warning, no error (#6479, #6491). Surface it as a validation
|
|
* warning so operators can tell "engine ran but had nothing to do" apart from "engine never ran".
|
|
*/
|
|
function recordNullStatsStep(acc: StackAccumulator, engineId: string): void {
|
|
acc.validationWarnings.add(`${engineId}: skipped (no eligible content)`);
|
|
}
|
|
|
|
/** Folds one engine result into the accumulator (telemetry + breakdown entry). */
|
|
export function mergeStackStep(
|
|
acc: StackAccumulator,
|
|
engineId: string,
|
|
result: CompressionResult
|
|
): void {
|
|
if (!result.stats) {
|
|
// No-op engine (e.g. ccr / session-dedup found no candidate): stats is null so there is no
|
|
// telemetry to fold, but the engine still RAN — record a zero-savings breakdown entry so its
|
|
// identity survives. Without this the breakdown stays empty and ensureEngineBreakdown
|
|
// synthesizes a generic "stacked" 0% node, hiding which engine an operator actually asked for.
|
|
// Also surface a validation warning so operators can tell "engine ran but had nothing to do"
|
|
// apart from "engine never ran" (#6479, #6491).
|
|
recordNullStatsStep(acc, engineId);
|
|
acc.breakdown.push({
|
|
engine: engineId,
|
|
originalTokens: 0,
|
|
compressedTokens: 0,
|
|
savingsPercent: 0,
|
|
techniquesUsed: [],
|
|
});
|
|
return;
|
|
}
|
|
result.stats.techniquesUsed.forEach((technique) => acc.techniques.add(technique));
|
|
result.stats.rulesApplied?.forEach((rule) => acc.rules.add(rule));
|
|
result.stats.rtkRawOutputPointers?.forEach((pointer) => acc.rtkRawOutputPointers.push(pointer));
|
|
result.stats.validationWarnings?.forEach((warning) => acc.validationWarnings.add(warning));
|
|
result.stats.validationErrors?.forEach((error) => acc.validationErrors.add(error));
|
|
acc.fallbackApplied = acc.fallbackApplied || result.stats.fallbackApplied === true;
|
|
acc.breakdown.push({
|
|
engine: engineId,
|
|
originalTokens: result.stats.originalTokens,
|
|
compressedTokens: result.stats.compressedTokens,
|
|
savingsPercent: result.stats.savingsPercent,
|
|
techniquesUsed: result.stats.techniquesUsed,
|
|
...(result.stats.rulesApplied ? { rulesApplied: result.stats.rulesApplied } : {}),
|
|
...(result.stats.durationMs !== undefined ? { durationMs: result.stats.durationMs } : {}),
|
|
// O agregado do pipeline soma tokens de todas as engines; a contabilidade
|
|
// física do omniglyph só faz sentido no passo que a produziu.
|
|
...(result.stats.omniglyph ? { omniglyph: result.stats.omniglyph } : {}),
|
|
});
|
|
}
|