getOrCreateSession function ✓ 81.3%

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

Metrics

LOC: 64 Complexity: 12 Params: 0 Coverage: 81.3% (26/32 lines, 12x executed)

Signature

getOrCreateSession(): : Promise<LanguageModelSession | null>

Architecture violations

View all

  • [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)

graph LR getOrCreateSession["getOrCreateSession"] getLanguageModelApi["getLanguageModelApi"] renderSystemPromptForOptimizer["renderSystemPromptForOptimizer"] getOrCreateSession -->|calls| getLanguageModelApi getOrCreateSession -->|calls| renderSystemPromptForOptimizer style getOrCreateSession fill:#dbeafe,stroke:#2563eb,stroke-width:2px click getOrCreateSession "886f8a1b05bac08e.html" click getLanguageModelApi "410ff2233e0b1dc2.html" click renderSystemPromptForOptimizer "efc89ef287372192.html"

Impact (Incoming)

graph LR getOrCreateSession["getOrCreateSession"] optimizeScript["optimizeScript"] optimizeScript -->|calls| getOrCreateSession style getOrCreateSession fill:#dbeafe,stroke:#2563eb,stroke-width:2px click getOrCreateSession "886f8a1b05bac08e.html" click optimizeScript "5a1335379abb3f1d.html"
SourceType
optimizeScript calls