getSession function exported ✓ 80.0%
Last updated: 2026-03-03T18:32:34.140Z
Location
Metrics
LOC: 49
Complexity: 9
Params: 0
Coverage: 80.0% (20/25 lines, 11x executed)
Signature
getSession(): : Promise<LanguageModelSession | null>
Summary
Returns an existing or freshly created LanguageModel session. The session carries a system prompt tailored for form-value generation. Recycles automatically when the context window is ≥85% full to prevent the model from consuming gigabytes of memory across many form fills.
Tags
#@returns A reusable AI session, or `null` when AI is unavailable
Source Code
export async function getSession(): Promise<LanguageModelSession | null> {
if (session) {
// Recycle when context window is almost exhausted
const remaining = session.tokensRemaining;
const max = session.maxTokens;
if (remaining !== undefined && max !== undefined && max > 0) {
const usedRatio = (max - remaining) / max;
if (usedRatio >= 0.85) {
log.debug(
`Contexto da sessão quase cheio (${remaining}/${max} tokens restantes). Reciclando sessão...`,
);
session.destroy();
session = null;
}
}
}
if (session) {
log.debug("Reutilizando sessão existente.");
return session;
}
log.debug("Criando nova sessão...");
const systemPrompt = renderSystemPrompt(fieldValueGeneratorPrompt);
const api = getLanguageModelApi();
if (!api) {
log.warn("Chrome AI API não encontrada — sessão não criada.");
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: unavailable) — sessão não criada.",
);
return null;
}
session = await api.create({
systemPrompt,
expectedOutputs: [{ type: "text", languages: ["en"] }],
});
log.debug("Sessão criada com sucesso.");
return session!;
}
Dependencies (Outgoing)
| Target | Type |
|---|---|
| getLanguageModelApi | calls |
Impact (Incoming)
| Source | Type |
|---|---|
| generateFieldValue | calls |
| generateFieldValueFromInput | calls |
| generateFormContextValues | calls |