garbage / toolsProvider.ts

import { tool, Tool } from "@lmstudio/sdk";
import { z } from "zod";
import { executeFileTool } from "./tools/fileTools";
import { executeMemoryTool } from "./tools/memoryTools";
import { executeSystemTool } from "./tools/systemTools";
import { executeWebTool } from "./tools/webTools";
import { executeExcelTool } from "./tools/excelTools";

const TRASANAH_URL = "http://127.0.0.1:5075";

const FALLBACK_TOOL_CATALOG = [
  { name: "getNow", description: "Get current system time and date in ISO and local formats." },
  { name: "readFile", description: "Read full content of a target file (UTF-8)." },
  { name: "writeFile", description: "Create or overwrite a file with given text content." },
  { name: "appendFile", description: "Append text to an existing file." },
  { name: "deleteFile", description: "Permanently delete a specified file." },
  { name: "copyFile", description: "Copy a file to a new target path." },
  { name: "renameFile", description: "Rename or move a file to a new destination." },
  { name: "listFolder", description: "List all files and subdirectories in a directory." },
  { name: "searchFiles", description: "Search for files by name or content recursively." },
  { name: "eagleEye", description: "Perform deep structural, size, and security analysis on a file." },
  { name: "saveSession", description: "Save current conversation session state to persistent memory." },
  { name: "getMemory", description: "Retrieve past memory sessions using keywords or tags." },
  { name: "semanticMemory", description: "Search memory using semantic embeddings." },
  { name: "markAwareness", description: "Record a new cognitive insight or realization." },
  { name: "recallAwareness", description: "Recall previously recorded insights and realizations." },
  { name: "searchWeb", description: "Search the web in real time." },
  { name: "fetchArticle", description: "Extract clean text content from a web article URL." },
  { name: "terminal", description: "Execute a shell command in the local operating system." },
  { name: "runCode", description: "Execute a JavaScript or Python code snippet." },
  { name: "ocrImage", description: "Extract text from an image using OCR." },
  { name: "readExcelSheet", description: "Read tabular rows and columns from an Excel spreadsheet." },
  { name: "appendExcelRow", description: "Append a row of data to an Excel spreadsheet." },
];

type ToolCatalogEntry = {
  name: string;
  description?: string;
  parameters?: Record<string, string>;
};

async function loadToolCatalog(): Promise<ToolCatalogEntry[]> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 1200);
  try {
    const response = await fetch(`${TRASANAH_URL}/tools`, { signal: controller.signal });
    if (!response.ok) throw new Error(`Tool catalog returned HTTP ${response.status}`);
    const data = await response.json() as { descriptions?: Record<string, Omit<ToolCatalogEntry, "name">> };
    const catalog = Object.entries(data.descriptions || {}).map(([name, details]) => ({ name, ...details }));
    return catalog.length ? catalog : FALLBACK_TOOL_CATALOG;
  } catch {
    return FALLBACK_TOOL_CATALOG;
  } finally {
    clearTimeout(timeoutId);
  }
}

function formatToolCatalog(catalog: ToolCatalogEntry[]): string {
  return catalog.map(({ name, description, parameters }) => {
    const parameterList = Object.entries(parameters || {}).map(([key, type]) => `${key}: ${type}`).join(", ");
    return `- ${name}${parameterList ? `(${parameterList})` : ""}: ${description || "No description provided."}`;
  }).join("\n");
}

export interface ToolExecutionContext {
  onToolStart?: (callId: string, name: string, args: any) => void;
  onToolResult?: (callId: string, name: string, result: any, howl: string, elapsedMs: number) => void;
}

// Provide tool definitions for the UI to display in clean English.
export async function toolsProvider(): Promise<any[]> {
  return (await loadToolCatalog()).map(({ name, description }) => ({ name, description }));
}

export function wolfHowl(toolName: string): string {
  const howls: Record<string, string> = {
    readFile: "IO Engine: Reading file contents...",
    writeFile: "IO Engine: Writing data to disk...",
    searchFiles: "IO Engine: Searching directory tree...",
    eagleEye: "Analyzer: Deep inspection of file structure...",
    saveSession: "Memory Engine: Persisting session state...",
    getMemory: "Memory Engine: Searching semantic history...",
    semanticMemory: "Vector Engine: Retrieving embeddings...",
    searchWeb: "Web Engine: Performing live search...",
    fetchArticle: "Web Engine: Scraping article text...",
    terminal: "System Terminal: Executing shell command...",
    runCode: "Runtime: Executing script...",
    markAwareness: "Cognitive Core: Recording insight...",
    getNow: "System Clock: Fetching timestamp...",
  };
  return howls[toolName] || `Executor: Invoking ${toolName}...`;
}

// Normalized mapping of diverse tool call notations
const TOOL_MAPPING: Record<string, string> = {
  getTime: "getNow",
  get_time: "getNow",
  getDate: "getNow",
  get_date: "getNow",
  getNow: "getNow",
  readFile: "readFile",
  read_file: "readFile",
  writeFile: "writeFile",
  write_file: "writeFile",
  appendFile: "appendFile",
  append_file: "appendFile",
  deleteFile: "deleteFile",
  delete_file: "deleteFile",
  copyFile: "copyFile",
  copy_file: "copyFile",
  renameFile: "renameFile",
  rename_file: "renameFile",
  listFolder: "listFolder",
  list_folder: "listFolder",
  runCode: "runCode",
  run_code: "runCode",
  executeCode: "runCode",
  searchFiles: "searchFiles",
  search_files: "searchFiles",
  eagleEye: "eagleEye",
  eagle_eye: "eagleEye",
  ocr: "ocrImage",
  ocrImage: "ocrImage",
  searchWeb: "searchWeb",
  search_web: "searchWeb",
  get_mem: "getMemory",
  getMem: "getMemory",
  getMemory: "getMemory",
  save_mem: "saveSession",
  saveSession: "saveSession",
  memory_search: "semanticMemory",
  semanticMemory: "semanticMemory",
  markAwareness: "markAwareness",
  mark_awareness: "markAwareness",
  terminal: "terminal",
  readExcelSheet: "readExcelSheet",
  appendExcelRow: "appendExcelRow"
};

/**
 * Creates genuine @lmstudio/sdk tools for use in model.act().
 * Each tool uses standard Zod schemas and executes via the local engine or Trasanah,
 * streaming progress via the provided execution context callbacks.
 */
function createLegacySDKTools(context?: ToolExecutionContext): Tool[] {
  const wrap = (name: string, fn: (args: any) => Promise<any>) => {
    return async (args: any) => {
      const callId = `call_${name}_${Date.now()}`;
      context?.onToolStart?.(callId, name, args);
      const start = Date.now();
      try {
        const result = await fn(args);
        const elapsed = Date.now() - start;
        const howl = result?.howl || wolfHowl(name);
        context?.onToolResult?.(callId, name, result, howl, elapsed);
        return typeof result === "object" ? JSON.stringify(result, null, 2) : String(result);
      } catch (err: any) {
        const elapsed = Date.now() - start;
        const errMsg = err?.message || String(err);
        context?.onToolResult?.(callId, name, { error: errMsg }, "Error in tool execution", elapsed);
        return `Error executing ${name}: ${errMsg}`;
      }
    };
  };

  return [
    tool({
      name: "getNow",
      description: "Get current system time and date in ISO and local formats.",
      parameters: {},
      implementation: wrap("getNow", async () => executeTool("getNow", {})),
    }),
    tool({
      name: "readFile",
      description: "Read full content of a target file (UTF-8).",
      parameters: {
        file: z.string().describe("The path of the file to read"),
      },
      implementation: wrap("readFile", async ({ file }) => executeTool("readFile", { file })),
    }),
    tool({
      name: "writeFile",
      description: "Create or overwrite a file with given text content.",
      parameters: {
        file: z.string().describe("The path of the file to write"),
        content: z.string().describe("The text content to write into the file"),
      },
      implementation: wrap("writeFile", async ({ file, content }) => executeTool("writeFile", { file, content })),
    }),
    tool({
      name: "appendFile",
      description: "Append text to an existing file.",
      parameters: {
        file: z.string().describe("The path of the file to append to"),
        content: z.string().describe("The text content to append"),
      },
      implementation: wrap("appendFile", async ({ file, content }) => executeTool("appendFile", { file, content })),
    }),
    tool({
      name: "deleteFile",
      description: "Permanently delete a specified file or directory.",
      parameters: {
        file: z.string().describe("The path of the file or directory to delete"),
      },
      implementation: wrap("deleteFile", async ({ file }) => executeTool("deleteFile", { file })),
    }),
    tool({
      name: "copyFile",
      description: "Copy a file to a new target path.",
      parameters: {
        source: z.string().describe("The path of the source file"),
        destination: z.string().describe("The path of the destination"),
      },
      implementation: wrap("copyFile", async ({ source, destination }) => executeTool("copyFile", { source, destination })),
    }),
    tool({
      name: "renameFile",
      description: "Rename or move a file to a new destination.",
      parameters: {
        oldName: z.string().describe("The current path of the file"),
        newName: z.string().describe("The new path of the file"),
      },
      implementation: wrap("renameFile", async ({ oldName, newName }) => executeTool("renameFile", { oldName, newName })),
    }),
    tool({
      name: "listFolder",
      description: "List all files and subdirectories in a directory.",
      parameters: {
        folder: z.string().optional().describe("Directory path to list (defaults to current folder)"),
      },
      implementation: wrap("listFolder", async (args) => executeTool("listFolder", args)),
    }),
    tool({
      name: "searchFiles",
      description: "Search for files by name or content recursively.",
      parameters: {
        path: z.string().default(".").describe("Search root; relative paths use the configured root, and absolute paths are accepted."),
        query: z.string().describe("File name or content pattern to search for"),
        type: z.enum(["name", "content"]).default("name").describe("Search by file name or file content"),
      },
      implementation: wrap("searchFiles", async ({ path, query, type }) => executeTool("searchFiles", {
        folder: path,
        query,
        type,
      })),
    }),
    tool({
      name: "eagleEye",
      description: "Perform deep structural, size, and security analysis on a file.",
      parameters: {
        file: z.string().describe("Path to the file to inspect"),
      },
      implementation: wrap("eagleEye", async ({ file }) => executeTool("eagleEye", { file })),
    }),
    tool({
      name: "saveSession",
      description: "Save current conversation session state to persistent memory.",
      parameters: {
        title: z.string().describe("Title or headline of the session"),
        summary: z.string().describe("Concise summary of topics and decisions"),
        main_idea: z.string().optional().describe("Core concept or goal"),
        tags: z.array(z.string()).optional().describe("Keywords or categories"),
      },
      implementation: wrap("saveSession", async (args) => executeTool("saveSession", args)),
    }),
    tool({
      name: "getMemory",
      description: "Retrieve past memory sessions using keywords or tags.",
      parameters: {
        query: z.string().describe("Search keywords or query"),
      },
      implementation: wrap("getMemory", async ({ query }) => executeTool("getMemory", { query })),
    }),
    tool({
      name: "semanticMemory",
      description: "Search memory using semantic embeddings (via Vector Server).",
      parameters: {
        query: z.string().describe("Semantic question or topic to search in vector database"),
      },
      implementation: wrap("semanticMemory", async ({ query }) => executeTool("semanticMemory", { query })),
    }),
    tool({
      name: "markAwareness",
      description: "Record a new cognitive insight or realization.",
      parameters: {
        insight: z.string().describe("The realization, rule, or insight to record"),
      },
      implementation: wrap("markAwareness", async ({ insight }) => executeTool("markAwareness", { insight })),
    }),
    tool({
      name: "recallAwareness",
      description: "Recall previously recorded insights and realizations.",
      parameters: {
        topic: z.string().optional().describe("Optional filter topic or keyword"),
      },
      implementation: wrap("recallAwareness", async (args) => executeTool("recallAwareness", args)),
    }),
    tool({
      name: "searchWeb",
      description: "Search the web in real-time via DuckDuckGo.",
      parameters: {
        query: z.string().describe("Keywords to search on the web"),
        maxResults: z.number().optional().describe("Max number of search results to return (default: 5)"),
      },
      implementation: wrap("searchWeb", async (args) => executeTool("searchWeb", args)),
    }),
    tool({
      name: "fetchArticle",
      description: "Extract clean text content from a web article URL.",
      parameters: {
        url: z.string().describe("URL of the webpage to scrape"),
      },
      implementation: wrap("fetchArticle", async ({ url }) => executeTool("fetchArticle", { url })),
    }),
    tool({
      name: "terminal",
      description: "Execute a shell command in the local operating system.",
      parameters: {
        cmd: z.string().describe("Command to run in bash/terminal"),
        cwd: z.string().optional().describe("Working directory for command"),
      },
      implementation: wrap("terminal", async (args) => executeTool("terminal", args)),
    }),
    tool({
      name: "runCode",
      description: "Execute a JavaScript or Python code snippet.",
      parameters: {
        code: z.string().describe("Code to execute"),
        language: z.enum(["javascript", "python", "bash"]).optional().describe("Language to execute"),
      },
      implementation: wrap("runCode", async (args) => executeTool("runCode", args)),
    }),
    tool({
      name: "readExcelSheet",
      description: "Read tabular rows and columns from an Excel spreadsheet.",
      parameters: {
        file: z.string().describe("Path to the .xlsx Excel file"),
        sheet: z.string().optional().describe("Optional name of sheet to read"),
      },
      implementation: wrap("readExcelSheet", async (args) => executeTool("readExcelSheet", args)),
    }),
    tool({
      name: "appendExcelRow",
      description: "Append a row of data to an Excel spreadsheet.",
      parameters: {
        file: z.string().describe("Path to the .xlsx Excel file"),
        sheet: z.string().optional().describe("Optional name of sheet"),
        row: z.array(z.any()).describe("Array of cell values for the row"),
      },
      implementation: wrap("appendExcelRow", async (args) => executeTool("appendExcelRow", args)),
    }),
  ];
}

export async function createSDKTools(context?: ToolExecutionContext): Promise<Tool[]> {
  const catalog = await loadToolCatalog();
  const catalogText = formatToolCatalog(catalog);

  const invokeTool = async ({ name, arguments: args = {} }: { name: string; arguments?: Record<string, unknown> }) => {
    const callId = `call_${name}_${Date.now()}`;
    context?.onToolStart?.(callId, name, args);
    const start = Date.now();
    try {
      const result = await executeTool(name, args);
      const elapsed = Date.now() - start;
      context?.onToolResult?.(callId, name, result, result?.howl || wolfHowl(name), elapsed);
      return typeof result === "object" ? JSON.stringify(result, null, 2) : String(result);
    } catch (err: any) {
      const elapsed = Date.now() - start;
      const errMsg = err?.message || String(err);
      context?.onToolResult?.(callId, name, { error: errMsg }, "Error in tool execution", elapsed);
      return `Error executing ${name}: ${errMsg}`;
    }
  };

  return [tool({
    name: "callTool",
    description: `Execute one tool from the local tool server. Use the exact tool name and pass its arguments as a JSON object. Return to the user only after inspecting the result.\n\nAvailable tools:\n${catalogText}`,
    parameters: {
      name: z.string().describe("Exact name of a tool listed above"),
      arguments: z.record(z.string(), z.unknown()).optional().describe("Arguments required by that tool as a JSON object"),
    },
    implementation: invokeTool,
  })];
}

async function executeViaTrasanah(toolName: string, params: any): Promise<any | null> {
  const remoteNames: Record<string, string> = {
    getNow: "getTime",
    appendFile: "appendToFile",
    listFolder: "listFiles",
    readFile: "readFile",
    writeFile: "writeFile",
    copyFile: "copyFile",
    renameFile: "renameFile",
    semanticMemory: "semanticSearch",
  };
  const remoteName = remoteNames[toolName] || toolName;
  const input = params || {};
  const remoteParams = { ...input };

  if (toolName === "readFile" || toolName === "writeFile") {
    remoteParams.path = remoteParams.path || remoteParams.file;
    delete remoteParams.file;
  } else if (toolName === "appendFile") {
    remoteParams.path = remoteParams.path || remoteParams.file;
    delete remoteParams.file;
  } else if (toolName === "listFolder") {
    remoteParams.path = remoteParams.path || remoteParams.folder || ".";
    delete remoteParams.folder;
  } else if (toolName === "copyFile") {
    remoteParams.from = remoteParams.from || remoteParams.source;
    remoteParams.to = remoteParams.to || remoteParams.destination;
    delete remoteParams.source;
    delete remoteParams.destination;
  } else if (toolName === "renameFile") {
    remoteParams.from = remoteParams.from || remoteParams.oldName;
    remoteParams.to = remoteParams.to || remoteParams.newName;
    delete remoteParams.oldName;
    delete remoteParams.newName;
  } else if (toolName === "eagleEye") {
    remoteParams.path = remoteParams.path || remoteParams.file;
    delete remoteParams.file;
  } else if (toolName === "searchFiles") {
    remoteParams.path = remoteParams.path || remoteParams.folder || ".";
    remoteParams.type = remoteParams.type || "content";
    delete remoteParams.folder;
  } else if (toolName === "saveSession") {
    remoteParams.mainIdea = remoteParams.mainIdea || remoteParams.main_idea;
    remoteParams.rawContent = remoteParams.rawContent || remoteParams.raw_content;
    delete remoteParams.main_idea;
    delete remoteParams.raw_content;
  } else if (toolName === "readRawSession") {
    remoteParams.sessionId = remoteParams.sessionId || remoteParams.session_id;
    delete remoteParams.session_id;
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 1800);
  try {
    const response = await fetch(`${TRASANAH_URL}/tool/${encodeURIComponent(remoteName)}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(remoteParams),
      signal: controller.signal,
    });
    clearTimeout(timeoutId);
    if (response.ok) {
      const data = await response.json() as any;
      if (data.status === "success") {
        return {
          success: true,
          ...data,
          howl: data.howl || wolfHowl(toolName),
          source: "trasanah_5075"
        };
      }
    }
  } catch {
    clearTimeout(timeoutId);
  }
  return null;
}

export async function executeTool(rawToolName: string, args: any = {}): Promise<any> {
  const toolName = TOOL_MAPPING[rawToolName] || rawToolName;
  try {
    // 1. Try via Trasanah first (Arm 1 / 5075)
    const trasanahResult = await executeViaTrasanah(toolName, args);
    if (trasanahResult) {
      return trasanahResult;
    }

    // 2. Local Fallback Engines
    let result = null;
    result = await executeFileTool(toolName, args);
    if (result) return result;

    result = await executeMemoryTool(toolName, args);
    if (result) return result;

    result = await executeSystemTool(toolName, args);
    if (result) return result;

    result = await executeWebTool(toolName, args);
    if (result) return result;

    result = await executeExcelTool(toolName, args);
    if (result) return result;

    return { error: `Tool '${toolName}' has no direct executor registered or is unrecognized.` };

  } catch (err: any) {
    console.error(`Error executing tool '${toolName}':`, err);
    return { error: err?.message || "Execution failure" };
  }
}

export interface ExtractedToolCall {
  name: string;
  arguments: any;
  fullMatch?: string;
  source?: string;
}

/**
 * Universal Multi-Regex Tool Call Sniffer
 * Supports standard JSON-RPC, XML execute_tool, and compact lightweight triggers.
 */
export function extractAllToolsFromText(text: string): ExtractedToolCall[] {
  if (!text) return [];
  const tools: ExtractedToolCall[] = [];

  // Pattern 1: Commentary Call
  const bidoRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|channel\|>commentary\s+json<\|message\|>(\{[\s\S]*?\})<\|call\|>/gi;
  let match: RegExpExecArray | null;
  while ((match = bidoRegex.exec(text)) !== null) {
    try {
      tools.push({
        name: TOOL_MAPPING[match[1]] || match[1],
        arguments: JSON.parse(match[2]),
        fullMatch: match[0],
        source: "Commentary Function Call"
      });
    } catch {}
  }

  // Pattern 2: Constrained JSON Call
  const bidoConstrainRegex = /to=functions\.([a-zA-Z0-9_]+)\s+<\|constrain\|>json<\|message\|>(\{[\s\S]*?\})/gi;
  while ((match = bidoConstrainRegex.exec(text)) !== null) {
    try {
      tools.push({
        name: TOOL_MAPPING[match[1]] || match[1],
        arguments: JSON.parse(match[2]),
        fullMatch: match[0],
        source: "Constrained Function Call"
      });
    } catch {}
  }

  // Pattern 3: XML execute_tool syntax
  const xmlRegex = /<execute_tool\s+name=["']([^"']+)["'](?:\s+params=['"]([^'"]*)['"])?/gi;
  while ((match = xmlRegex.exec(text)) !== null) {
    try {
      let params = {};
      if (match[2]) {
        params = JSON.parse(match[2].replace(/'/g, '"'));
      }
      tools.push({
        name: TOOL_MAPPING[match[1]] || match[1],
        arguments: params,
        fullMatch: match[0],
        source: "XML execute_tool"
      });
    } catch {}
  }

  // Pattern 4: Standard <tool_call>{...}</tool_call>
  const r1Regex = /<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/gi;
  while ((match = r1Regex.exec(text)) !== null) {
    try {
      const parsed = JSON.parse(match[1]);
      if (parsed.name || parsed.tool) {
        const rawName = parsed.name || parsed.tool;
        tools.push({
          name: TOOL_MAPPING[rawName] || rawName,
          arguments: parsed.arguments || parsed.params || {},
          fullMatch: match[0],
          source: "Standard <tool_call>"
        });
      }
    } catch {}
  }

  // Pattern 5: Explicit JSON {"tool": "...", "params": {...}}
  const explicitJsonRegex = /\{\s*"tool"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"params"\s*:\s*(\{[^}]*\})\s*\}/gi;
  while ((match = explicitJsonRegex.exec(text)) !== null) {
    try {
      tools.push({
        name: TOOL_MAPPING[match[1]] || match[1],
        arguments: JSON.parse(match[2]),
        fullMatch: match[0],
        source: "Explicit JSON Tool"
      });
    } catch {}
  }

  // Pattern 6: Standard JSON {"name": "...", "arguments": {...}}
  const standardJsonRegex = /\{\s*"name"\s*:\s*"([a-zA-Z0-9_-]+)"\s*,\s*"arguments"\s*:\s*(\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\})\s*\}/gi;
  while ((match = standardJsonRegex.exec(text)) !== null) {
    try {
      if (!match[0].includes('<tool_call>')) {
        tools.push({
          name: TOOL_MAPPING[match[1]] || match[1],
          arguments: JSON.parse(match[2]),
          fullMatch: match[0],
          source: "Standard JSON Call"
        });
      }
    } catch {}
  }

  // Pattern 7: Ultra-Lightweight trigger @tool:name(...)
  const hamadaRegex = /@tool:([a-zA-Z0-9_]+)\((.*?)\)/gi;
  while ((match = hamadaRegex.exec(text)) !== null) {
    try {
      let argsObj: any = {};
      const inner = match[2].trim();
      if (inner.startsWith('{') && inner.endsWith('}')) {
        argsObj = JSON.parse(inner);
      } else if (inner) {
        const parts = inner.split(',').map(s => s.trim().replace(/^['"]|['"]$/g, ''));
        if (parts.length === 1) argsObj = { path: parts[0], query: parts[0], command: parts[0] };
        else argsObj = { arg1: parts[0], arg2: parts[1] };
      }
      tools.push({
        name: TOOL_MAPPING[match[1]] || match[1],
        arguments: argsObj,
        fullMatch: match[0],
        source: "Ultra-Lightweight Tool Trigger"
      });
    } catch {}
  }

  // Deduplicate preserving precedence
  const unique: ExtractedToolCall[] = [];
  const seen = new Set<string>();
  for (const t of tools) {
    const key = `${t.name}|${JSON.stringify(t.arguments)}`;
    if (!seen.has(key)) {
      seen.add(key);
      unique.push(t);
    }
  }

  return unique;
}