← back to developerlabsai__hybriq-sdk

Function bodies 108 total

All specs Real LLM only Function bodies
main function · typescript · L14-L62 (49 LOC)
examples/cloud-quickstart.ts
async function main(): Promise<void> {
  const sdk = new HybrIQSDK({
    mode: "cloud",
    apiKey: process.env.HYBRIQ_API_KEY!,
    baseUrl: process.env.HYBRIQ_BASE_URL!,
    providers: {
      anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
    },
  });

  console.log("SDK mode:", sdk.mode);

  // --- Check balance ---
  const balance = await sdk.getBalance();
  console.log(`Credits: ${balance.creditBalance} (${balance.plan} plan)`);

  // --- Execute an LLM call ---
  try {
    const result = await sdk.execute({
      model: "claude-sonnet-4-5-20250929",
      messages: [
        { role: "user", content: "What are the three laws of robotics?" },
      ],
      maxTokens: 256,
    });

    console.log("\n--- Response ---");
    console.log(result.response);
    console.log(`\nCache hit: ${result.cacheHit}`);
    console.log(`Tokens: ${result.tokensIn} in / ${result.tokensOut} out`);
    console.log(`Credits charged: ${result.creditsCharged}`);
  } catch (err) {
    if (err ins
main function · typescript · L13-L103 (91 LOC)
examples/local-quickstart.ts
async function main(): Promise<void> {
  const sdk = new HybrIQSDK({
    mode: "local",
    licenseKey: process.env.HYBRIQ_LICENSE_KEY!,
    providers: {
      anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
    },
    cache: {
      semanticMatch: true,
      embeddingProvider: "local",  // Offline TF-IDF, no API needed
      semanticThreshold: 0.92,
    },
  });

  console.log("SDK mode:", sdk.mode);

  // --- Execute first call (cache miss) ---
  try {
    console.log("\n--- First call (cache miss expected) ---");
    const result1 = await sdk.execute({
      model: "claude-sonnet-4-5-20250929",
      messages: [
        { role: "user", content: "Explain what a neural network is in simple terms." },
      ],
      maxTokens: 256,
    });

    console.log(result1.response.slice(0, 200) + "...");
    console.log(`Cache hit: ${result1.cacheHit}`);

    // --- Execute same call again (exact cache hit) ---
    console.log("\n--- Second call (exact cache hit expected) ---");
    co
AgentsModule class · typescript · L12-L89 (78 LOC)
src/agents.ts
export class AgentsModule {
  constructor(private client: HybrIQApiClient) {}


  /**
   * Execute an agent with the given messages.
   *
   * @param agentId - The agent to execute.
   * @param request - Messages, optional webhook/stream/metadata.
   * @returns Typed execution result with response, cost, and cache info.
   *
   * @example
   * ```ts
   * const result = await sdk.agents.run("agent-id", {
   *   messages: [{ role: "user", content: "Summarize this document" }],
   * });
   * console.log(result.response.content);
   * ```
   */
  async run(
    agentId: string,
    request: AgentRunRequest
  ): Promise<AgentExecutionResult> {
    const { messages, webhook, stream, metadata, version } = request;

    const extraHeaders: Record<string, string> = {};
    if (version) {
      extraHeaders["X-Agent-Version"] = version;
    }

    const body = {
      messages,
      ...(webhook ? { webhook } : {}),
      ...(stream !== undefined ? { stream } : {}),
      ...(metadata ? { metada
run method · typescript · L31-L61 (31 LOC)
src/agents.ts
  async run(
    agentId: string,
    request: AgentRunRequest
  ): Promise<AgentExecutionResult> {
    const { messages, webhook, stream, metadata, version } = request;

    const extraHeaders: Record<string, string> = {};
    if (version) {
      extraHeaders["X-Agent-Version"] = version;
    }

    const body = {
      messages,
      ...(webhook ? { webhook } : {}),
      ...(stream !== undefined ? { stream } : {}),
      ...(metadata ? { metadata } : {}),
    };

    const { data, headers } = await this.client.postWithHeaders<AgentExecutionResult>(
      `/api/v1/agents/${encodeURIComponent(agentId)}/run`,
      body,
      Object.keys(extraHeaders).length > 0 ? extraHeaders : undefined
    );

    // Populate cacheHit from X-Cache header if not already set
    if (data.response && headers.get("X-Cache")) {
      data.response.cacheHit = headers.get("X-Cache") === "HIT";
    }

    return data;
  }
getBalance function · typescript · L11-L15 (5 LOC)
src/billing.ts
export async function getBalance(
  apiClient: HybrIQApiClient
): Promise<BalanceInfo> {
  return apiClient.get<BalanceInfo>("/api/v1/billing/balance");
}
getPlans function · typescript · L20-L24 (5 LOC)
src/billing.ts
export async function getPlans(
  apiClient: HybrIQApiClient
): Promise<PlanInfo[]> {
  return apiClient.get<PlanInfo[]>("/api/v1/billing/plans");
}
getUsage function · typescript · L29-L36 (8 LOC)
src/billing.ts
export async function getUsage(
  apiClient: HybrIQApiClient,
  period?: "current" | "previous"
): Promise<UsageReport> {
  const params: Record<string, string> = {};
  if (period) params.period = period;
  return apiClient.get<UsageReport>("/api/v1/billing/usage", params);
}
Want this analysis on your repo? https://repobility.com/scan/
HybrIQApiClient class · typescript · L15-L153 (139 LOC)
src/client.ts
export class HybrIQApiClient {
  /** @internal */
  readonly apiKey: string;
  /** @internal */
  readonly baseUrl: string;

  constructor(config: { apiKey: string; baseUrl: string }) {
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl.replace(/\/$/, "");
  }

  /**
   * POST request to the HybrIQ API.
   */
  async post<T = unknown>(path: string, body: unknown, extraHeaders?: Record<string, string>): Promise<T> {
    const { data } = await this.request<T>("POST", path, body, extraHeaders);
    return data;
  }

  /**
   * POST request returning both data and response headers.
   */
  async postWithHeaders<T = unknown>(path: string, body: unknown, extraHeaders?: Record<string, string>): Promise<{ data: T; headers: Headers }> {
    return this.request<T>("POST", path, body, extraHeaders);
  }

  /**
   * GET request to the HybrIQ API.
   */
  async get<T = unknown>(
    path: string,
    params?: Record<string, string>
  ): Promise<T> {
    let url = path;
    if (param
constructor method · typescript · L21-L24 (4 LOC)
src/client.ts
  constructor(config: { apiKey: string; baseUrl: string }) {
    this.apiKey = config.apiKey;
    this.baseUrl = config.baseUrl.replace(/\/$/, "");
  }
post method · typescript · L29-L32 (4 LOC)
src/client.ts
  async post<T = unknown>(path: string, body: unknown, extraHeaders?: Record<string, string>): Promise<T> {
    const { data } = await this.request<T>("POST", path, body, extraHeaders);
    return data;
  }
get method · typescript · L44-L55 (12 LOC)
src/client.ts
  async get<T = unknown>(
    path: string,
    params?: Record<string, string>
  ): Promise<T> {
    let url = path;
    if (params) {
      const searchParams = new URLSearchParams(params);
      url = `${path}?${searchParams.toString()}`;
    }
    const { data } = await this.request<T>("GET", url);
    return data;
  }
request method · typescript · L69-L75 (7 LOC)
src/client.ts
  private async request<T>(
    method: string,
    path: string,
    body?: unknown,
    extraHeaders?: Record<string, string>,
    attempt = 0
  ): Promise<{ data: T; headers: Headers }> {
usd function · typescript · L32-L34 (3 LOC)
src/cli/stats.ts
function usd(amount: number): string {
  return `$${amount.toFixed(2)}`;
}
pct function · typescript · L39-L41 (3 LOC)
src/cli/stats.ts
function pct(value: number): string {
  return `${(value * 100).toFixed(1)}%`;
}
bar function · typescript · L46-L50 (5 LOC)
src/cli/stats.ts
function bar(value: number, max: number, width: number = 20): string {
  const filled = max > 0 ? Math.round((value / max) * width) : 0;
  const empty = width - filled;
  return `${c.green}${"█".repeat(filled)}${c.dim}${"░".repeat(empty)}${c.reset}`;
}
Repobility · severity-and-effort ranking · https://repobility.com
main function · typescript · L55-L172 (118 LOC)
src/cli/stats.ts
async function main(): Promise<void> {
  const baseDir = process.cwd();
  const configDir = join(baseDir, ".hybriq");

  console.log("");
  console.log(`${c.bold}${c.bgBlue}${c.white} HybrIQ Local Stats ${c.reset}`);
  console.log(`${c.dim}─────────────────────────────────────────${c.reset}`);

  // Check if .hybriq exists
  if (!existsSync(configDir)) {
    console.log(`${c.yellow}No .hybriq/ directory found in ${baseDir}${c.reset}`);
    console.log(`${c.dim}Run your first execution to initialize local mode.${c.reset}`);
    console.log("");
    process.exit(0);
  }

  // === Cache Stats ===
  const cacheDbPath = join(configDir, "cache.db");
  if (existsSync(cacheDbPath)) {
    const cache = new LocalCache(cacheDbPath);
    await cache.init();
    const stats = cache.getStats();
    cache.close();

    console.log("");
    console.log(`${c.bold}${c.cyan}Cache Performance${c.reset}`);
    console.log(`${c.dim}──────────────────${c.reset}`);

    const total = stats.totalHits + stats.t
enrich function · typescript · L17-L70 (54 LOC)
src/enrichment.ts
export async function enrich(
  apiClient: HybrIQApiClient,
  request: EnrichRequest,
  providerCallback?: (req: EnrichRequest) => Promise<Record<string, unknown>>
): Promise<EnrichResult> {
  // First call: check cache
  const response = await apiClient.post<EnrichResponse>("/api/v1/enrich", {
    entityType: request.entityType,
    lookupKey: request.lookupKey,
    provider: request.provider,
    enrichedData: request.enrichedData,
    isolateTenant: request.isolateTenant,
  });

  if (response.cacheHit || response.data) {
    return {
      cacheHit: response.cacheHit,
      data: response.data,
      provider: response.provider ?? request.provider,
      confidence: response.confidence,
      creditsCharged: response.creditsCharged ?? 0,
      executionId: response.executionId,
    };
  }

  // Cache miss without data -- call provider if callback provided
  if (providerCallback && !request.enrichedData) {
    const enrichedData = await providerCallback(request);

    // Second call
resolveProvider function · typescript · L47-L52 (6 LOC)
src/execute.ts
function resolveProvider(model: string): "anthropic" | "openai" {
  if (model.startsWith("claude")) return "anthropic";
  if (model.startsWith("gpt")) return "openai";
  // Default to anthropic
  return "anthropic";
}
execute function · typescript · L57-L183 (127 LOC)
src/execute.ts
export async function execute(
  apiClient: HybrIQApiClient,
  providers: { anthropic?: ProviderConfig; openai?: ProviderConfig },
  request: ExecuteRequest
): Promise<ExecuteResult> {
  const providerName = resolveProvider(request.model);
  const providerConfig = providers[providerName];

  // Step 1: Try to start execution via HybrIQ API
  let startResponse: StartResponse;
  try {
    startResponse = await apiClient.post<StartResponse>(
      "/api/v1/execute/start",
      {
        executionType: "llm_call",
        modelProvider: providerName,
        modelName: request.model,
        systemPrompt: request.systemPrompt,
        messages: request.messages,
        agentId: request.agentId,
        skillId: request.skillId,
        shareable: request.shareable ?? false,
        metadata: request.metadata,
      }
    );
  } catch (err) {
    // Check if this is a network error (API unreachable)
    const hybriqErr = err as HybrIQError;
    if (hybriqErr.statusCode === 0 && hybriqErr.
executeDegraded function · typescript · L188-L226 (39 LOC)
src/execute.ts
async function executeDegraded(
  providerName: "anthropic" | "openai",
  providerConfig: ProviderConfig | undefined,
  request: ExecuteRequest
): Promise<ExecuteResult> {
  console.warn("HybrIQ unreachable — running in degraded mode");

  if (!providerConfig) {
    throw new Error(
      `No ${providerName} provider configured and HybrIQ API is unreachable.`
    );
  }

  const llmRequest: LLMRequest = {
    model: request.model,
    systemPrompt: request.systemPrompt,
    messages: request.messages,
    maxTokens: request.maxTokens,
    temperature: request.temperature,
  };

  const llmResponse =
    providerName === "anthropic"
      ? await callAnthropic(providerConfig, llmRequest)
      : await callOpenAI(providerConfig, llmRequest);

  return {
    executionId: "degraded",
    response: llmResponse.content,
    cacheHit: false,
    tokensIn: llmResponse.tokensIn,
    tokensOut: llmResponse.tokensOut,
    creditsCharged: 0,
    remainingCredits: -1,
    modelProvider: llmResponse
HybrIQSDK class · typescript · L42-L288 (247 LOC)
src/index.ts
export class HybrIQSDK {
  private apiClient!: HybrIQApiClient;
  private providers: {
    anthropic?: ProviderConfig;
    openai?: ProviderConfig;
  };
  private readonly _mode: "cloud" | "local";
  private _license: ValidatedLicense | null = null;
  private _localCache: LocalCache | null = null;
  private _localMetering: LocalMetering | null = null;
  private _localConfig: LocalConfig | null = null;
  private _localInitPromise: Promise<void> | null = null;

  /** Browse and subscribe to the federated library (cloud mode only). */
  readonly library!: LibraryModule;

  /** Execute agents via the agent endpoint (cloud mode only). */
  readonly agents!: AgentsModule;

  constructor(config: HybrIQConfig) {
    this._mode = config.mode ?? "cloud";
    this.providers = config.providers ?? {};

    if (this._mode === "cloud") {
      if (!config.apiKey) {
        throw new Error("Cloud mode requires an API key. Provide `apiKey` in config.");
      }
      if (config.apiKey.startsWith("hiq_o
constructor method · typescript · L61-L90 (30 LOC)
src/index.ts
  constructor(config: HybrIQConfig) {
    this._mode = config.mode ?? "cloud";
    this.providers = config.providers ?? {};

    if (this._mode === "cloud") {
      if (!config.apiKey) {
        throw new Error("Cloud mode requires an API key. Provide `apiKey` in config.");
      }
      if (config.apiKey.startsWith("hiq_oss_")) {
        throw new Error(
          "OSS license keys are for local mode only. Use a tenant API key for cloud mode."
        );
      }
      if (!config.baseUrl) {
        throw new Error("Cloud mode requires a base URL. Provide `baseUrl` in config.");
      }
      this.apiClient = new HybrIQApiClient({
        apiKey: config.apiKey,
        baseUrl: config.baseUrl,
      });
      this.library = new LibraryModule(this.apiClient);
      this.agents = new AgentsModule(this.apiClient);
    } else if (this._mode === "local") {
      if (!config.licenseKey) {
        throw new Error("Local mode requires a license key. Provide `licenseKey` in config.");
      }
 
initLocalMode method · typescript · L96-L116 (21 LOC)
src/index.ts
  private async initLocalMode(licenseKey: string, config: HybrIQConfig): Promise<void> {
    this._license = await validateLicense(licenseKey);

    // Configure semantic cache
    const semanticConfig = config.cache?.semanticMatch
      ? {
          enabled: true,
          embedding: {
            provider: (config.cache.embeddingProvider ?? "local") as "local" | "openai",
            apiKey: config.providers?.openai?.apiKey,
            threshold: config.cache.semanticThreshold ?? 0.92,
          },
        }
      : { enabled: false };

    this._localCache = new LocalCache(".hybriq/cache.db", semanticConfig);
    this._localMetering = new LocalMetering();
    this._localConfig = loadLocalConfig(this._license);
    await this._localCache.init();
    await this._localMetering.init();
  }
Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
ensureLocalInit method · typescript · L121-L126 (6 LOC)
src/index.ts
  private async ensureLocalInit(): Promise<void> {
    if (this._localInitPromise) {
      await this._localInitPromise;
      this._localInitPromise = null;
    }
  }
execute method · typescript · L144-L156 (13 LOC)
src/index.ts
  async execute(request: ExecuteRequest): Promise<ExecuteResult> {
    if (this._mode === "local") {
      await this.ensureLocalInit();
      return executeLocal(
        request,
        this.providers,
        this._license!,
        this._localCache!,
        this._localMetering!
      );
    }
    return execute(this.apiClient, this.providers, request);
  }
usage method · typescript · L178-L184 (7 LOC)
src/index.ts
  async usage(period?: "current" | "all"): Promise<LocalUsageReport> {
    if (this._mode !== "local") {
      throw new Error("usage() is only available in local mode.");
    }
    await this.ensureLocalInit();
    return this._localMetering!.getUsage(period ?? "current");
  }
export method · typescript · L192-L198 (7 LOC)
src/index.ts
  async export(outputPath: string, options?: ExportOptions): Promise<void> {
    if (this._mode !== "local") {
      throw new Error("export() is only available in local mode.");
    }
    await this.ensureLocalInit();
    return exportPack(outputPath, this._license!, this._localCache!, options);
  }
getBalance method · typescript · L203-L206 (4 LOC)
src/index.ts
  async getBalance(): Promise<BalanceInfo> {
    this.requireCloud("getBalance");
    return getBalance(this.apiClient);
  }
getPlans method · typescript · L211-L214 (4 LOC)
src/index.ts
  async getPlans(): Promise<PlanInfo[]> {
    this.requireCloud("getPlans");
    return getPlans(this.apiClient);
  }
getUsage method · typescript · L219-L222 (4 LOC)
src/index.ts
  async getUsage(period?: "current" | "previous"): Promise<UsageReport> {
    this.requireCloud("getUsage");
    return getUsage(this.apiClient, period);
  }
enrich method · typescript · L239-L245 (7 LOC)
src/index.ts
  async enrich(
    request: EnrichRequest,
    providerCallback?: (req: EnrichRequest) => Promise<Record<string, unknown>>
  ): Promise<EnrichResult> {
    this.requireCloud("enrich");
    return enrich(this.apiClient, request, providerCallback);
  }
Repobility (the analyzer behind this table) · https://repobility.com
getLocalConfig method · typescript · L251-L257 (7 LOC)
src/index.ts
  async getLocalConfig(): Promise<LocalConfig> {
    if (this._mode !== "local") {
      throw new Error("getLocalConfig() is only available in local mode.");
    }
    await this.ensureLocalInit();
    return this._localConfig!;
  }
getLocalAgent method · typescript · L262-L265 (4 LOC)
src/index.ts
  async getLocalAgent(agentId: string): Promise<LocalAgentConfig | undefined> {
    const config = await this.getLocalConfig();
    return getAgent(config, agentId);
  }
getLocalSkill method · typescript · L270-L273 (4 LOC)
src/index.ts
  async getLocalSkill(skillId: string): Promise<LocalSkillConfig | undefined> {
    const config = await this.getLocalConfig();
    return getSkill(config, skillId);
  }
scaffold method · typescript · L278-L280 (3 LOC)
src/index.ts
  static scaffold(baseDir?: string): void {
    scaffoldConfig(baseDir);
  }
requireCloud method · typescript · L283-L287 (5 LOC)
src/index.ts
  private requireCloud(method: string): void {
    if (this._mode !== "cloud") {
      throw new Error(`${method}() is only available in cloud mode.`);
    }
  }
LibraryModule class · typescript · L7-L48 (42 LOC)
src/library.ts
export class LibraryModule {
  constructor(private apiClient: HybrIQApiClient) {}

  async browseAgents(params?: { category?: string; search?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.category) query.category = params.category;
    if (params?.search) query.search = params.search;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/agents", query);
  }

  async browseSkills(params?: { category?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.category) query.category = params.category;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/skills", query);
  }

  async browseSpecialties(params?: { domain?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.domain) query.domain = params.domain;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/specialties", query);
  }

  async browseClusters(): Promise<Lib
browseAgents method · typescript · L10-L15 (6 LOC)
src/library.ts
  async browseAgents(params?: { category?: string; search?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.category) query.category = params.category;
    if (params?.search) query.search = params.search;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/agents", query);
  }
browseSkills method · typescript · L17-L21 (5 LOC)
src/library.ts
  async browseSkills(params?: { category?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.category) query.category = params.category;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/skills", query);
  }
Want this analysis on your repo? https://repobility.com/scan/
browseSpecialties method · typescript · L23-L27 (5 LOC)
src/library.ts
  async browseSpecialties(params?: { domain?: string }): Promise<LibraryItem[]> {
    const query: Record<string, string> = {};
    if (params?.domain) query.domain = params.domain;
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/specialties", query);
  }
browseClusters method · typescript · L29-L31 (3 LOC)
src/library.ts
  async browseClusters(): Promise<LibraryItem[]> {
    return this.apiClient.get<LibraryItem[]>("/api/v1/library/clusters");
  }
subscribe method · typescript · L33-L39 (7 LOC)
src/library.ts
  async subscribe(itemType: string, itemId: string, overrides?: Record<string, unknown>): Promise<SubscriptionInfo> {
    return this.apiClient.post<SubscriptionInfo>("/api/v1/library/subscribe", {
      itemType,
      itemId,
      configOverrides: overrides,
    });
  }
unsubscribe method · typescript · L41-L43 (3 LOC)
src/library.ts
  async unsubscribe(subscriptionId: string): Promise<void> {
    await this.apiClient.delete(`/api/v1/library/subscribe/${subscriptionId}`);
  }
listSubscriptions method · typescript · L45-L47 (3 LOC)
src/library.ts
  async listSubscriptions(): Promise<SubscriptionInfo[]> {
    return this.apiClient.get<SubscriptionInfo[]>("/api/v1/library/subscriptions");
  }
InvalidLicenseError class · typescript · L32-L37 (6 LOC)
src/license/validator.ts
export class InvalidLicenseError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "InvalidLicenseError";
  }
}
constructor method · typescript · L33-L36 (4 LOC)
src/license/validator.ts
  constructor(message: string) {
    super(message);
    this.name = "InvalidLicenseError";
  }
validateLicense function · typescript · L49-L110 (62 LOC)
src/license/validator.ts
export async function validateLicense(
  licenseKey: string
): Promise<ValidatedLicense> {
  // Check prefix
  if (!licenseKey.startsWith("hiq_oss_")) {
    throw new InvalidLicenseError(
      "Invalid license key format. Expected prefix 'hiq_oss_'."
    );
  }

  // Decode base64url payload
  const base64Part = licenseKey.slice("hiq_oss_".length);
  let combined: Uint8Array;
  try {
    combined = Uint8Array.from(Buffer.from(base64Part, "base64url"));
  } catch {
    throw new InvalidLicenseError("Invalid license key encoding.");
  }

  if (combined.length <= SIGNATURE_LENGTH) {
    throw new InvalidLicenseError(
      "License key is too short — missing payload or signature."
    );
  }

  // Split payload and signature
  const payloadBytes = combined.slice(0, combined.length - SIGNATURE_LENGTH);
  const signature = combined.slice(combined.length - SIGNATURE_LENGTH);

  // Verify Ed25519 signature
  const publicKeyBytes = Uint8Array.from(Buffer.from(PUBLIC_KEY, "base64"));
  let val
Repobility · severity-and-effort ranking · https://repobility.com
checkFeatureAccess function · typescript · L123-L142 (20 LOC)
src/license/validator.ts
export function checkFeatureAccess(
  license: ValidatedLicense,
  feature: "agent" | "skill",
  currentCount: number
): boolean {
  const { entitlements } = license.payload;

  if (feature === "agent") {
    // -1 means unlimited
    if (entitlements.maxAgents === -1) return true;
    return currentCount < entitlements.maxAgents;
  }

  if (feature === "skill") {
    if (entitlements.maxSkills === -1) return true;
    return currentCount < entitlements.maxSkills;
  }

  return false;
}
LocalCache class · typescript · L58-L412 (355 LOC)
src/local/cache.ts
export class LocalCache {
  private db: Database | null = null;
  private dbPath: string;
  private hits = 0;
  private misses = 0;
  private semanticHits = 0;
  private exactHits = 0;
  private estimatedSavingsUsd = 0;
  private semanticConfig: SemanticCacheConfig;

  constructor(
    dbPath: string = ".hybriq/cache.db",
    semanticConfig?: SemanticCacheConfig
  ) {
    this.dbPath = dbPath;
    this.semanticConfig = semanticConfig ?? { enabled: false };
  }

  /**
   * Initialize the SQLite database.
   * Creates cache tables (exact + semantic) if they don't exist.
   */
  async init(): Promise<void> {
    const SQL = await initSqlJs();

    const dir = dirname(this.dbPath);
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true });
    }

    if (existsSync(this.dbPath)) {
      const buffer = readFileSync(this.dbPath);
      this.db = new SQL.Database(buffer);
    } else {
      this.db = new SQL.Database();
    }

    // Exact match table
    this.db.run(`
      CREAT
constructor method · typescript · L68-L74 (7 LOC)
src/local/cache.ts
  constructor(
    dbPath: string = ".hybriq/cache.db",
    semanticConfig?: SemanticCacheConfig
  ) {
    this.dbPath = dbPath;
    this.semanticConfig = semanticConfig ?? { enabled: false };
  }
page 1 / 3next ›