getSession function exported ✓ 80.0%

Last updated: 2026-03-03T18:32:34.140Z

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)

graph LR getSession["getSession"] getLanguageModelApi["getLanguageModelApi"] getSession -->|calls| getLanguageModelApi style getSession fill:#dbeafe,stroke:#2563eb,stroke-width:2px click getSession "59bdb203dfc665ba.html" click getLanguageModelApi "410ff2233e0b1dc2.html"
TargetType
getLanguageModelApi calls

Impact (Incoming)

graph LR getSession["getSession"] generateFieldValue["generateFieldValue"] generateFieldValueFromInput["generateFieldValueFromInput"] generateFormContextValues["generateFormContextValues"] generateFieldValue -->|calls| getSession generateFieldValueFromInput -->|calls| getSession generateFormContextValues -->|calls| getSession style getSession fill:#dbeafe,stroke:#2563eb,stroke-width:2px click getSession "59bdb203dfc665ba.html" click generateFieldValue "2fb9e83e355e13d0.html" click generateFieldValueFromInput "28d34d36b97d981e.html" click generateFormContextValues "599bada0365a8514.html"