User: 

You are given access to make searches on the Internet. The format for making a search is:
1. After the user sends a message, you will decide whether to make a search. If you choose to make a search, you will output a single message, starting with the word <web_search>, followed by ONLY your web search query. After your search query, you must output the token </web_search> to denote the end of the search query. Keep your search query very concise.
2. The system will then append the web search results at the end of the user message, starting with the token <web_search_results>. Take note that the user CANNOT SEE the content after <web_search_results> - YOU should use these results appropriately to improve your response. Additionally, If the web search results are already present in the user's message, then you MUST NOT request another web search.

IMPORTANT! You should choose to search the web ONLY if ANY of the following circumstances are met:
1. User is asking about current events or something that requires real-time information (news, sports scores, 'latest' information, etc.)
2. User is asking about some term you are unfamiliar with (e.g. if it's a little-known term, if it's a person you don't know well, etc.)
3. User is asking about anything that involves numerical facts (e.g. distances between places, population count, sizes, date and time, etc.)
4. User explicitly asks you to search or provide links to references.
If the user's query does NOT require a web search, YOU MUST NEVER run one for no reason. However, you must not refuse to search the web if the user asks you to do so.
If you are highly unsure about whether to make a search (e.g. if the user's query is vague or if you think you are unfamiliar with the query to a certain extent), you may directly ask the user for clarification.

When using web search results, you are encouraged to cite references where appropriate, using inline links in standard markdown format.
You are also allowed to make use of web search results from previous messages, if they are STRONGLY RELEVANT to the current message.

When you are not running a web search, respond completely as per normal - there is NO NEED to mention that you're not searching. 
Remember that you MUST NOT make up any false information.
Assistant: Understood. I will strictly follow these instructions in this conversation.
User: ---
File: /Users/alexeykotomin/node_modules/lsd/node_modules/dictionary-search/server/index.js

// server/index.js
const express = require("express");
const fetch = require("node-fetch");
const cheerio = require("cheerio");
const TurndownService = require("turndown");
const LRU = require("lru-cache");

// Настройка сервера
const app = express();
const PORT = process.env.PORT || 3000;

// Инициализация Turndown для конвертации HTML в Markdown
const turndownService = new TurndownService({
  headingStyle: "atx",
  codeBlockStyle: "fenced",
});

// Простое локальное кеширование в памяти (можно заменить на redis или файловый кеш)
const cache = new LRU.LRUCache({
  max: 500,           // макс. количество элементов
  ttl: 1000 * 60 * 30 // время жизни кеша - 30 минут
});

app.get("/search", async (req, res) => {
  const queryRaw = req.query.q?.trim();
  if (!queryRaw) {
    return res.status(400).json({ error: "Query parameter 'q' is required" });
  }

  // Кешируем по районированному ключу
  const cacheKey = queryRaw.toLowerCase();
  if (cache.has(cacheKey)) {
    return res.json(cache.get(cacheKey));
  }

  try {
    const searchUrl = `https://lsj.gr/index.php?search=${encodeURIComponent(queryRaw)}&title=Special%3ASearch`;

    const response = await fetch(searchUrl, {
      headers: {
        "User-Agent": "Mozilla/5.0 (compatible; RaycastBot/1.0)",
        "Accept-Language": "en-US,en;q=0.9",
      },
    });

    if (!response.ok) {
      return res.status(response.status).json({ error: `Server returned ${response.status}` });
    }

    const html = await response.text();

    const $ = cheerio.load(html);

    // Если есть результаты поиска
    if ($(".mw-search-results").length > 0) {
      const results = [];
      $(".mw-search-result").each((i, el) => {
        const heading = $(el).find(".mw-search-result-heading a");
        if (!heading.length) return;

        results.push({
          title: heading.text().trim(),
          url: "https://lsj.gr" + heading.attr("href"),
          description: $(el).find(".searchresult").text().trim(),
        });
      });

      const resultJson = { query: queryRaw, type: "search", results };
      cache.set(cacheKey, resultJson);
      return res.json(resultJson);
    }

    // Если статья с заголовком

    if ($("#firstHeading").length > 0) {
      const title = $("#firstHeading").text().trim();

      // Берём весь HTML содержимого статьи
      let contentHtml = $("#mw-content-text").html() || "";

      // Обрабатываем все ссылки в тексте (произвольные внутренние или внешние)
      const $content = cheerio.load(contentHtml);
      $content("a").each((i, el) => {
        const href = $content(el).attr("href");
        if (href) {
          if (href.startsWith("/wiki/")) {
            // Преобразуем внутренние ссылки в полные URL и добавляем target="_blank"
            $content(el).attr("href", `https://lsj.gr${href}`);
            $content(el).attr("target", "_blank");
          } else if (href.startsWith("#")) {
            // Якорные ссылки оставляем, добавлять ничего не нужно
          } else if (!href.startsWith("http")) {
            // Относительные ссылки - если есть, превращаем в абсолютные тоже
            $content(el).attr("href", `https://lsj.gr${href}`);
            $content(el).attr("target", "_blank");
          } else {
            // Внешние ссылки - просто открываем в новой вкладке
            $content(el).attr("target", "_blank");
          }
        }
      });
      contentHtml = $content.html();

      // Конвертируем HTML статьи в Markdown для удобного рендера в Raycast
      const contentMarkdown = turndownService.turndown(contentHtml);

      // Сниппет из Markdown (первые 800 символов)
      const snippet = contentMarkdown.substring(0, 800) + (contentMarkdown.length > 800 ? "…" : "");

      // Парсим оглавление
      const tocItems = [];
      $("#toc li.toclevel-1 a").each((i, el) => {
        const anchor = $(el);
        tocItems.push({
          number: anchor.find(".tocnumber").text(),
          text: anchor.find(".toctext").text(),
          href: anchor.attr("href"),
        });
      });

      const resultJson = {
        query: queryRaw,
        type: "article",
        result: {
          title,
          snippet,
          toc: tocItems,
          url: `https://lsj.gr/wiki/${encodeURIComponent(title)}`, // чтобы точнее ссылку всегда
          markdown: contentMarkdown,
        },
      };

      cache.set(cacheKey, resultJson);
      return res.json(resultJson);
    }

    // Нет данных - пустой ответ
    const noResults = { query: queryRaw, results: [], message: "No results found" };
    cache.set(cacheKey, noResults);
    return res.json(noResults);
  } catch (error) {
    console.error("Error fetching or parsing:", error);
    return res.status(500).json({ error: "Error fetching or parsing data" });
  }
});

app.listen(PORT, () => {
  console.log(`Server started at http://localhost:${PORT}`);
});


Assistant: [system: file uploaded]
User: ---
File: /Users/alexeykotomin/node_modules/lsd/node_modules/dictionary-search/src/search.tsx

import React, { useState, useEffect } from "react";
import {
  ActionPanel,
  CopyToClipboardAction,
  List,
  OpenInBrowserAction,
  showToast,
  ToastStyle,
  Detail,
} from "@raycast/api";

interface SearchResult {
  title: string;
  description: string;
  url: string;
}

interface TocItem {
  number: string;
  text: string;
  href: string;
}

interface Article {
  title: string;
  snippet: string;
  toc: TocItem[];
  url: string;
  markdown: string;
}

export default function Command() {
  const [query, setQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
  const [article, setArticle] = useState<Article | null>(null);
  const [viewingDetail, setViewingDetail] = useState(false);

  useEffect(() => {
    if (!query) {
      setSearchResults([]);
      setArticle(null);
      setViewingDetail(false);
      setIsLoading(false);
      return;
    }

    async function fetchData() {
      setIsLoading(true);
      try {
        const resp = await fetch(`http://127.0.0.1:3000/search?q=${encodeURIComponent(query)}`);
        if (!resp.ok) throw new Error(`Error ${resp.status}`);
        const data = await resp.json();

        if (data.type === "search") {
          setSearchResults(data.results || []);
          setArticle(null);
          setViewingDetail(false);
        } else if (data.type === "article") {
          setArticle(data.result);
          setSearchResults([]);
          setViewingDetail(true);
        } else {
          setSearchResults([]);
          setArticle(null);
          setViewingDetail(false);
        }
      } catch (error) {
        await showToast(ToastStyle.Failure, "Search failed", String(error));
        setSearchResults([]);
        setArticle(null);
        setViewingDetail(false);
      } finally {
        setIsLoading(false);
      }
    }

    fetchData();
  }, [query]);

  // Показать список результатов
  if (!viewingDetail) {
    return (
      <List
        isLoading={isLoading}
        onSearchTextChange={setQuery}
        searchBarPlaceholder="Search LSJ dictionary"
      >
        {searchResults.length > 0 &&
          searchResults.map((item, index) => (
            <List.Item
              key={index}
              title={item.title}
              subtitle={item.description || undefined}
              actions={
                <ActionPanel>
                  <OpenInBrowserAction url={item.url} />
                  <CopyToClipboardAction title="Copy word" content={item.title} />
                </ActionPanel>
              }
              onAction={() => {
                // По клику на результат можно сразу выполнить переход к статье
                setQuery(item.title);
              }}
            />
          ))}

        {searchResults.length === 0 && !isLoading && <List.EmptyView title="No results" />}
      </List>
    );
  }

  // Детальный просмотр статьи с Markdown
  if (article) {
    return (
      <Detail
        navigationTitle={article.title}
        markdown={article.markdown}
        actions={
          <ActionPanel>
            <OpenInBrowserAction url={article.url} />
            <CopyToClipboardAction title="Copy title" content={article.title} />
            <ActionPanel.Item
              title="Back to Results"
              onAction={() => {
                setViewingDetail(false);
              }}
            />
          </ActionPanel>
        }
      />
    );
  }

  return null;
}


Assistant: [system: file uploaded]
User: ---
File: /Users/alexeykotomin/node_modules/lsd/node_modules/dictionary-search/server/package.json

{
  "name": "lsj-proxy-server",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "cheerio": "^1.1.0",
    "express": "^4.21.2",
    "lru-cache": "^11.1.0",
    "node-fetch": "^2.7.0",
    "turndown": "^7.2.0"
  },
  "scripts": {
    "start": "node index.js"
  }
}

Assistant: [system: file uploaded]
User: не дает допечатать поисковый запрос и сразу выводит информацию после ввода 1 буквы

Assistant: