getOrCreateSession function ✓ 81.3%
Last updated: 2026-03-03T18:32:34.140Z
Location
Metrics
LOC: 64
Complexity: 12
Params: 0
Coverage: 81.3% (26/32 lines, 12x executed)
Signature
getOrCreateSession(): : Promise<LanguageModelSession | null>
Architecture violations
- [warning] max-cyclomatic-complexity: 'getOrCreateSession' has cyclomatic complexity 12 (max 10)
Source Code
async function getOrCreateSession(): Promise<LanguageModelSession | null> {
if (optimizerSession) {
// Recycle when context window is almost exhausted
const remaining = optimizerSession.tokensRemaining;
const max = optimizerSession.maxTokens;
if (remaining !== undefined && max !== undefined && max > 0) {
const usedRatio = (max - remaining) / max;
if (usedRatio >= 0.85) {
log.debug(
`Contexto do optimizer quase cheio (${remaining}/${max} tokens). Reciclando...`,
);
optimizerSession.destroy();
optimizerSession = null;
}
}
}
if (optimizerSession) return optimizerSession;
if (
sessionFailedAt &&
Date.now() - sessionFailedAt < SESSION_FAILURE_TTL_MS
) {
return null;
}
try {
const api = getLanguageModelApi();
if (!api) {
log.warn("LanguageModel API não encontrada.");
sessionFailedAt = Date.now();
return null;
}
const avail = await api.availability({
expectedInputs: [{ type: "text", languages: ["en"] }],
expectedOutputs: [{ type: "text", languages: ["en"] }],
});
if (avail === "unavailable") {
log.warn(`Chrome AI indisponível (status: "${avail}").`);
sessionFailedAt = Date.now();
return null;
}
log.debug(`Criando sessão de otimização (availability: "${avail}")...`);
const systemPrompt = renderSystemPromptForOptimizer();
optimizerSession = await api.create({
systemPrompt,
temperature: OPTIMIZER_TEMPERATURE,
topK: 1,
expectedOutputs: [{ type: "text", languages: ["en"] }],
});
log.info("Sessão Chrome AI ScriptOptimizer criada com sucesso.");
sessionFailedAt = null;
return optimizerSession;
} catch (err) {
log.warn("Falha ao criar sessão de otimização:", err);
sessionFailedAt = Date.now();
return null;
}
}
Dependencies (Outgoing)
| Target | Type |
|---|---|
| getLanguageModelApi | calls |
| renderSystemPromptForOptimizer | calls |
Impact (Incoming)
| Source | Type |
|---|---|
| optimizeScript | calls |