2025-12-22 18:05:44 +01:00
|
|
|
// Lazy-load pi-coding-agent model metadata so we can infer context windows when
|
|
|
|
|
// the agent reports a model id. This includes custom models.json entries.
|
2025-12-05 22:33:09 +01:00
|
|
|
|
2025-12-23 02:48:48 +01:00
|
|
|
import { loadConfig } from "../config/config.js";
|
2026-01-30 03:15:10 +01:00
|
|
|
import { resolveOpenClawAgentDir } from "./agent-paths.js";
|
|
|
|
|
import { ensureOpenClawModelsJson } from "./models-config.js";
|
2025-12-23 02:48:48 +01:00
|
|
|
|
2025-12-05 22:33:09 +01:00
|
|
|
type ModelEntry = { id: string; contextWindow?: number };
|
|
|
|
|
|
|
|
|
|
const MODEL_CACHE = new Map<string, number>();
|
|
|
|
|
const loadPromise = (async () => {
|
|
|
|
|
try {
|
2026-01-31 06:40:45 +01:00
|
|
|
const { discoverAuthStorage, discoverModels } = await import("./pi-model-discovery.js");
|
2025-12-23 02:48:48 +01:00
|
|
|
const cfg = loadConfig();
|
2026-01-30 03:15:10 +01:00
|
|
|
await ensureOpenClawModelsJson(cfg);
|
|
|
|
|
const agentDir = resolveOpenClawAgentDir();
|
2026-01-31 06:40:45 +01:00
|
|
|
const authStorage = discoverAuthStorage(agentDir);
|
|
|
|
|
const modelRegistry = discoverModels(authStorage, agentDir);
|
2025-12-26 11:49:13 +01:00
|
|
|
const models = modelRegistry.getAll() as ModelEntry[];
|
2025-12-22 18:05:44 +01:00
|
|
|
for (const m of models) {
|
2026-01-31 16:19:20 +09:00
|
|
|
if (!m?.id) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2025-12-22 18:05:44 +01:00
|
|
|
if (typeof m.contextWindow === "number" && m.contextWindow > 0) {
|
|
|
|
|
MODEL_CACHE.set(m.id, m.contextWindow);
|
2025-12-05 22:33:09 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// If pi-ai isn't available, leave cache empty; lookup will fall back.
|
|
|
|
|
}
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
export function lookupContextTokens(modelId?: string): number | undefined {
|
2026-01-31 16:19:20 +09:00
|
|
|
if (!modelId) {
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
2025-12-05 22:33:09 +01:00
|
|
|
// Best-effort: kick off loading, but don't block.
|
|
|
|
|
void loadPromise;
|
|
|
|
|
return MODEL_CACHE.get(modelId);
|
|
|
|
|
}
|