src / toolsProvider.ts

import { tool, type ToolsProviderController } from "@lmstudio/sdk";
import { z } from "zod";

const do_tools: any[] = [];

async function toolsProvider(ctl: ToolsProviderController) {
  // -1
  const getDateTimeTool = tool({
    name: "get_date_time",
    description: "Returns current date and time. Use only on explicit time request.",
    parameters: {},
    implementation: async () => {
      return new Date().toISOString();
    }
  });
  do_tools.push(getDateTimeTool);

  //--2
  const CWTool = tool({
    name: "count_letters",
    description: "Counts occurrences of a character in a string.",
    parameters: {
      word: z.string(),
      letr: z.string().length(1)
    },
    implementation: async ({ word, letr }) => {
      return [...word].filter(c => c === letr).length;
    }
  });
  do_tools.push(CWTool);

  //--3
  const getLengthTool = tool({
    name: "get_word_length",
    description: "Returns the length of the input string.",
    parameters: {
      word: z.string()
    },
    implementation: async ({ word }) => {
      return { length: word.length };
    }
  });
  do_tools.push(getLengthTool);

  //--4
  const getMyIPTool = tool({
    name: "get_myip",
    description: "Returns user's public IP address.",
    parameters: {},
    implementation: async () => {
      const response = await fetch("https://ifconfig.me/ip");
      const ip = (await response.text()).trim();
      return { ip };
    }
  });
  do_tools.push(getMyIPTool);

  //--5
  const getAnagramTool = tool({
    name: "get_anagram",
    description: "Returns anagram of the input string/word.",
    parameters: {
      word: z.string()
    },
    implementation: async (params) => {
      const w = params.word;
      const c = [...w];
      const crypto = await import('crypto');
      //const { randomInt } = await import('crypto'); |\_ _ _ _ _just_option____
      //const j = randomInt(0, i + 1);                |/
      console.log(`Input W: "${w}", length W: ${w.length}`);
      console.log(`Input C: "${c}", length C: ${c.length}`);
      console.log(`Bytes: ${c.map(x => x.codePointAt(0))}`);
      for (let i = c.length - 1; i > 0; i--) {
        const j = crypto.randomInt(0, i +1);  //
        [c[i], c[j]] = [c[j], c[i]];          //xchg letters - (Fisher-Yates shuffle)
        console.log(`${i}:${j} C: "${c}", length: "${c.length}"`);
      }
     console.log(`result C: ${c.join("")}`);
     return { anagram: c.join('') };
     
     const result = c.join('');
     // Validity of result
     const inputSorted = [...w].sort().join('');
     const outputSorted = [...result].sort().join('');

     if (inputSorted !== outputSorted) {
       throw new Error(`Anagram validation failed: ${inputSorted} !== ${outputSorted}`);
     }

     return { anagram: result };
     }
  });
  do_tools.push(getAnagramTool);

  //--
  return do_tools;
}

export { toolsProvider };