Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

1.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

export type MentionToken = { start: number; end: number; query: string };

// The @name token around the caret; accepting replaces all of it, not just up to the caret.
export function mentionTokenAt(text: string, caret: number): MentionToken | null {
  const prefix = text.slice(0, caret);
  const match = /(?:^|\s)@([a-z0-9-]*)$/i.exec(prefix);
  if (!match) return null;
  const tail = /^[a-z0-9-]*/i.exec(text.slice(caret))?.[0] ?? "";
  return { start: prefix.lastIndexOf("@"), end: caret + tail.length, query: match[1] ?? "" };
}

export function replaceMentionToken(
  text: string,
  token: MentionToken,
  directive: string,
): { text: string; caret: number } {
  const after = text.slice(token.end);
  return {
    text: `${text.slice(0, token.start)}${directive} ${after.startsWith(" ") ? after.slice(1) : after}`,
    caret: token.start + directive.length + 1,
  };
}

type MentionSkill = {
  name: string;
  description: string;
  valid: boolean;
  shadowed: boolean;
  enabled: boolean;
};

export function mentionableSkills<T extends MentionSkill>(skills: readonly T[]): T[] {
  return skills.filter((skill) => skill.valid && !skill.shadowed && skill.enabled);
}

// preserve catalog order within the name-prefix, name-substring, and description-match tiers.
export function rankMentionSkills<T extends MentionSkill>(
  skills: readonly T[],
  query: string,
  limit: number,
): T[] {
  const needle = query.toLowerCase();
  const tiers: T[][] = [[], [], []];
  for (const skill of skills) {
    const name = skill.name.toLowerCase();
    if (name.startsWith(needle)) tiers[0].push(skill);
    else if (name.includes(needle)) tiers[1].push(skill);
    else if (skill.description.toLowerCase().includes(needle)) tiers[2].push(skill);
  }
  return tiers.flat().slice(0, limit);
}