repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/quota/src/routing.ts
Rawimport type { SessionEntry } from "@earendil-works/pi-coding-agent";
/** Pi's `VIRTUAL_MODEL_API`; the constant is not part of the public package exports. */
const VIRTUAL_API = "pi-virtual";
export function isRouted(model: { api?: string } | undefined): boolean {
return model?.api === VIRTUAL_API;
}
/**
* Provider whose quota applies. A virtual selection never reaches a provider, so its quota
* belongs to the physical provider of the latest successful response since that selection.
*/
export function quotaProviderKey(
model: { provider: string; api?: string } | undefined,
branch: readonly SessionEntry[],
): string | undefined {
if (!model) return undefined;
if (!isRouted(model)) return model.provider.toLowerCase();
for (let index = branch.length - 1; index >= 0; index--) {
const entry = branch[index];
// Responses before the virtual selection belong to whatever model was selected then.
if (entry?.type === "model_change") return undefined;
if (entry?.type !== "message") continue;
const message = entry.message;
if (
message.role !== "assistant" ||
isRouted(message) ||
message.stopReason === "error" ||
message.stopReason === "aborted"
)
continue;
return message.provider.toLowerCase();
}
return undefined;
}