/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// node_modules/ollama-node/lib/utility.js
var require_utility = __commonJS({
  "node_modules/ollama-node/lib/utility.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.streamingPost = exports.requestPost = exports.requestDelete = exports.requestShowInfo = exports.requestList = void 0;
    var http_1 = require("http");
    function requestList(options) {
      return new Promise((resolve, reject) => {
        const req = (0, http_1.request)(options, (response) => {
          const statusCode = response.statusCode || 0;
          if (statusCode < 200 || statusCode > 299) {
            return reject(new Error(`Failed with status code: ${response.statusCode}`));
          }
          const body = [];
          response.on("data", (chunk) => body.push(chunk));
          response.on("end", () => {
            const joined = body.join("");
            const parsed = JSON.parse(joined);
            resolve(parsed);
          });
        });
        req.on("error", reject);
        req.end();
      });
    }
    exports.requestList = requestList;
    function requestShowInfo(options, model) {
      return new Promise((resolve, reject) => {
        const req = (0, http_1.request)(options, (response) => {
          const statusCode = response.statusCode || 0;
          if (statusCode < 200 || statusCode > 299) {
            return reject(new Error(`Failed with status code: ${response.statusCode}`));
          }
          const body = [];
          response.on("data", (chunk) => body.push(chunk));
          response.on("end", () => {
            const joined = body.join("");
            const parsed = JSON.parse(joined);
            resolve(parsed);
          });
        });
        req.write(JSON.stringify({ "name": model }));
        req.on("error", reject);
        req.end();
      });
    }
    exports.requestShowInfo = requestShowInfo;
    function requestDelete(options, model) {
      return new Promise((resolve, reject) => {
        const req = (0, http_1.request)(options, (response) => {
          const statusCode = response.statusCode || 0;
          if (statusCode < 200 || statusCode > 299) {
            return reject(new Error(`Failed with status code: ${response.statusCode}`));
          }
          const body = [];
          response.on("data", (chunk) => body.push(chunk));
          response.on("end", () => {
            const joined = body.join("");
            const parsed = JSON.parse(joined);
            resolve(parsed);
          });
        });
        req.write('{"name": "' + model + '"}');
        req.on("error", reject);
        req.end();
      });
    }
    exports.requestDelete = requestDelete;
    function requestPost(target, options, databody) {
      let body = [];
      return new Promise((resolve, reject) => {
        const req = (0, http_1.request)(options, (response) => {
          const statusCode = response.statusCode || 0;
          if (statusCode < 200 || statusCode > 299) {
            return reject(new Error(`Failed with status code: ${response.statusCode}`));
          }
          response.on("data", (chunk) => {
            if (target === "embed") {
              body.push(chunk.toString("utf8"));
            } else {
              body.push(JSON.parse(chunk));
            }
          });
          response.on("end", () => {
            if (target === "embed") {
              resolve({ messages: [], final: JSON.parse(body.join("")) });
            } else {
              const final = body[body.length - 1];
              const messages = body.splice(0, body.length - 1);
              resolve({ messages, final });
            }
          });
        });
        req.write(JSON.stringify(databody));
        req.on("error", reject);
        req.end();
      });
    }
    exports.requestPost = requestPost;
    function streamingPost(target, options, databody, callback) {
      const req = (0, http_1.request)(options, (res) => {
        res.on("data", (chunk) => {
          const chunkStr = chunk.toString();
          const items = chunkStr.split("\n").filter(Boolean);
          for (const item of items) {
            callback(item);
            if (item.includes("error")) {
              console.log(`Error: ${JSON.parse(item).error}`);
            }
          }
        });
        res.on("error", (error) => {
          console.error(`Response error: ${error.message}`);
        });
        res.on("end", () => {
        });
      });
      req.on("error", (error) => {
        console.error(`Request error: ${error.message}`);
      });
      req.write(JSON.stringify(databody));
      req.end();
    }
    exports.streamingPost = streamingPost;
  }
});

// node_modules/ollama-node/lib/ollama.js
var require_ollama = __commonJS({
  "node_modules/ollama-node/lib/ollama.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Ollama = void 0;
    var utility_1 = require_utility();
    var Ollama2 = class {
      constructor(...args) {
        __publicField(this, "Host");
        __publicField(this, "Port", 11434);
        __publicField(this, "Model", "");
        __publicField(this, "SystemPrompt", "");
        __publicField(this, "Template", "");
        __publicField(this, "Parameters", {});
        __publicField(this, "Context", []);
        __publicField(this, "JSONFormat", false);
        if (args.length === 0) {
          this.Host = "127.0.0.1";
        } else {
          if (args[0] === "localhost") {
            this.Host = "127.0.0.1";
          } else {
            this.Host = args[0];
          }
        }
      }
      numberIfNumber(value) {
        const isOnlyNumbers = /^\d+$/.test(value);
        if (isOnlyNumbers) {
          return parseInt(value, 10);
        }
        return value;
      }
      async parseParams() {
        var _a;
        let options = {};
        const info = await this.showModelInfo();
        const params = (_a = info.parameters) == null ? void 0 : _a.split("\n").forEach((line) => {
          const [name, value] = line.split(/\s+/).filter(Boolean);
          const parsedvalue = this.numberIfNumber(value);
          if (name === "stop") {
            if (!options.stop) {
              options.stop = [];
            }
            options.stop.push(parsedvalue);
          } else {
            options[name] = parsedvalue;
          }
        });
        return options;
      }
      async localModelExists(model) {
        const localmodels = await this.listModels();
        if (model.includes(":")) {
          return localmodels.models.includes(model);
        } else {
          const basemodels = localmodels.models.map((m) => m.split(":")[0]);
          return basemodels.includes(model);
        }
      }
      setContext(context) {
        this.Context = context;
      }
      showHost() {
        return this.Host;
      }
      setJSONFormat(useJSON) {
        this.JSONFormat = useJSON;
      }
      async setModel(model) {
        if (await this.localModelExists(model)) {
          this.Model = model;
          const info = await this.showModelInfo();
          this.Parameters = await this.parseParams();
          this.Template = info.template || "";
          this.SystemPrompt = info.system || "";
        } else {
          throw new Error(`Model ${model} not found.`);
        }
      }
      setTemplate(template) {
        this.Template = template;
      }
      setSystemPrompt(systemPrompt) {
        this.SystemPrompt = systemPrompt;
      }
      addParameter(name, value) {
        name = name.toLowerCase();
        if (name === "stop") {
          if (!this.Parameters.stop) {
            this.Parameters.stop = [];
          }
          this.Parameters.stop.push(value);
        } else {
          this.Parameters[name] = value;
        }
      }
      deleteParameter(name, value) {
        if (name === "stop") {
          const stops = this.Parameters.stop;
          if (stops.includes(value)) {
            stops.splice(stops.indexOf(value));
            this.Parameters.stop = stops;
          }
        } else {
          this.Parameters[name] = void 0;
        }
      }
      deleteParameterByName(name) {
        this.Parameters[name] = void 0;
      }
      deleteAllParameters() {
        this.Parameters = {};
      }
      showParameters() {
        return this.Parameters;
      }
      async showSystemPrompt() {
        return this.SystemPrompt;
      }
      showTemplate() {
        return this.Template;
      }
      showModel() {
        return this.Model;
      }
      async showModelInfo() {
        const options = {
          hostname: this.Host,
          port: this.Port,
          method: "POST",
          path: "/api/show"
        };
        return await (0, utility_1.requestShowInfo)(options, this.Model);
      }
      async listModels() {
        const options = {
          hostname: this.Host,
          port: this.Port,
          path: "/api/tags",
          method: "GET"
        };
        const getResponse = await (0, utility_1.requestList)(options);
        const complete = getResponse.models;
        const models = complete.map((m) => m.name);
        return { models, complete };
      }
      async generate(prompt) {
        const generateOptions = {
          hostname: this.Host,
          port: 11434,
          method: "POST",
          path: "/api/generate"
        };
        const body = {
          model: this.Model,
          prompt,
          system: this.SystemPrompt,
          template: this.Template,
          options: this.Parameters,
          context: this.Context
        };
        if (this.JSONFormat) {
          body.format = "json";
        }
        let genoutput, final, messages;
        try {
          genoutput = await (0, utility_1.requestPost)("generate", generateOptions, body);
          final = genoutput.final;
          messages = genoutput.messages;
        } catch (error) {
          console.log(`There was a problem generating output from ${this.Model} with the prompt ${prompt}: ${error}`);
          return { output: "", stats: {} };
        }
        this.Context = final.context;
        const output = messages.map((m) => m.response).join("");
        return { output, stats: final };
      }
      streamingGenerate(prompt, responseOutput = null, contextOutput = null, fullResponseOutput = null, statsOutput = null) {
        return new Promise((resolve, reject) => {
          const options = {
            hostname: this.Host,
            port: 11434,
            method: "POST",
            path: "/api/generate"
          };
          const body = {
            model: this.Model,
            prompt,
            system: this.SystemPrompt,
            template: this.Template,
            options: this.Parameters,
            context: this.Context
          };
          if (this.JSONFormat) {
            body.format = "json";
          }
          (0, utility_1.streamingPost)("generate", options, body, (chunk) => {
            const jchunk = JSON.parse(chunk);
            if (Object.hasOwn(jchunk, "response")) {
              fullResponseOutput && fullResponseOutput(JSON.stringify(jchunk));
              responseOutput && responseOutput(jchunk.response);
            } else {
              if (Object.hasOwn(jchunk, "context")) {
                statsOutput && statsOutput(JSON.stringify(jchunk));
                contextOutput && contextOutput(jchunk.context.toString());
                this.Context = jchunk.context;
                resolve();
              }
            }
          });
        });
      }
      // async delete(modelName: string) {
      //   const options: RequestOptions = {
      //     hostname: this.Host,
      //     port: 11434,
      //     method: 'DELETE',
      //     path: '/api/delete',
      //   }
      //   const genoutput = await requestDelete(options, modelName);
      //   console.log(genoutput);
      // }
      async create(modelName, modelPath) {
        const createOptions = {
          hostname: this.Host,
          port: 11434,
          method: "POST",
          path: "/api/create"
        };
        const createBody = {
          name: modelName,
          path: modelPath
        };
        const genoutput = await (0, utility_1.requestPost)("create", createOptions, createBody);
        const messages = genoutput.messages;
        return messages.map((m) => m.status);
      }
      async generateEmbed(modelName, input) {
        const options = {
          hostname: this.Host,
          port: 11434,
          method: "POST",
          path: "/api/embeddings"
        };
        const body = {
          model: modelName,
          prompt: input
        };
        const genoutput = await (0, utility_1.requestPost)("embed", options, body);
        return genoutput.final.embedding;
      }
      streamingCreate(modelName, modelPath, responseOutput = null) {
        return new Promise((resolve, reject) => {
          const options = {
            hostname: this.Host,
            port: 11434,
            method: "POST",
            path: "/api/create"
          };
          const body = {
            name: modelName,
            path: modelPath
          };
          (0, utility_1.streamingPost)("create", options, body, async (chunk) => {
            const jchunk = JSON.parse(chunk);
            if (Object.hasOwn(jchunk, "status")) {
              responseOutput && responseOutput(jchunk.status);
              if (jchunk.status === "success") {
                resolve();
              }
            } else {
              responseOutput && responseOutput(jchunk);
            }
          });
        });
      }
      async streamingPull(modelName, responseOutput = null) {
        return new Promise((resolve, reject) => {
          const options = {
            hostname: this.Host,
            port: 11434,
            method: "POST",
            path: "/api/pull"
          };
          const body = {
            name: modelName
          };
          (0, utility_1.streamingPost)("pull", options, body, async (chunk) => {
            const jchunk = JSON.parse(chunk);
            let percent = "";
            if (Object.hasOwn(jchunk, "completed")) {
              percent = `downloading - ${(100 * (jchunk.completed / jchunk.total)).toFixed(2)} % complete`;
              responseOutput && responseOutput(`${percent}`);
            } else if (Object.hasOwn(jchunk, "status")) {
              responseOutput && responseOutput(jchunk.status);
            } else {
              responseOutput && responseOutput(jchunk);
            }
            if (jchunk.status === "success") {
              resolve();
            }
          });
        });
      }
      async streamingPush(modelName, responseOutput = null) {
        return new Promise((resolve, reject) => {
          const options = {
            hostname: this.Host,
            port: 11434,
            method: "POST",
            path: "/api/push"
          };
          const body = {
            name: modelName
          };
          (0, utility_1.streamingPost)("push", options, body, async (chunk) => {
            const jchunk = JSON.parse(chunk);
            if (Object.hasOwn(jchunk, "status")) {
              responseOutput && responseOutput(jchunk.status);
            } else {
              responseOutput && responseOutput(jchunk);
            }
          });
        });
      }
      async copy(sourceName, destinationName) {
        const options = {
          hostname: this.Host,
          port: 11434,
          method: "POST",
          path: "/api/copy"
        };
        const body = {
          source: sourceName,
          destination: destinationName
        };
        if (await this.localModelExists(sourceName)) {
          (0, utility_1.requestPost)("copy", options, body);
        } else {
          return Promise.reject(new Error("Model not found"));
        }
      }
      cbPrintword(chunk) {
        process.stdout.write(chunk);
      }
      cbPrintLine(chunk) {
        console.log(chunk);
      }
    };
    exports.Ollama = Ollama2;
  }
});

// main.ts
var main_exports = {};
__export(main_exports, {
  ExampleView: () => ExampleView,
  VIEW_TYPE_EXAMPLE: () => VIEW_TYPE_EXAMPLE,
  default: () => llmPlugin
});
module.exports = __toCommonJS(main_exports);
var fs = __toESM(require("fs"));
var import_obsidian = require("obsidian");
var import_ollama_node = __toESM(require_ollama());
var absPath = app.vault.adapter.basePath;
function readSettings(pluginId) {
  const dataFilePath = `${absPath}/.obsidian/plugins/${pluginId}/data.json`;
  try {
    const fileContent = fs.readFileSync(dataFilePath, "utf-8");
    const dataObject = JSON.parse(fileContent);
    const endpoint = dataObject["ollama_endpoint"];
    return endpoint;
  } catch (error) {
    new import_obsidian.Notice("Could not read data.json settings file");
    new import_obsidian.Notice(
      "Select a model within the settings tab and it will be created automatically"
    );
    return false;
  }
}
var llm_endpoint = readSettings("ai_llm");
if (llm_endpoint === false) {
  llm_endpoint = "127.0.0.1";
}
async function checkConnection(passedEndpoint) {
  const checkUrl = `http://${passedEndpoint}:11434/api/ps`;
  let res;
  try {
    const req = await (0, import_obsidian.requestUrl)(checkUrl).then((dat) => {
      return dat.status;
    }).catch((e) => {
      return false;
    });
    return req;
  } catch (error) {
    return false;
  }
}
var ollama;
try {
  if (llm_endpoint !== false && llm_endpoint !== "127.0.0.1") {
    try {
      new import_obsidian.Notice(
        `Ollama endpoint: ${llm_endpoint}, trying to initiate !`
      );
      checkConnection(llm_endpoint).then((data) => {
        if (String(data) === "200" && String(data) !== "false") {
          new import_obsidian.Notice(`Passed custom endpoint check: Success ! \u{1F973}`);
          ollama = new import_ollama_node.Ollama(llm_endpoint);
        } else {
          if (String(data) === "false") {
            new import_obsidian.Notice(
              `Passed custom endpoint ${llm_endpoint} check: No, status ${data} \u{1F979}`
            );
            new import_obsidian.Notice(
              `Initiating default endpoint instead, double check your custom endpoint \u{1F50E}`
            );
            ollama = new import_ollama_node.Ollama();
          }
        }
      });
    } catch (error) {
      new import_obsidian.Notice(`Error: ${error} !`);
    }
  } else {
    try {
      checkConnection(llm_endpoint).then((data) => {
        if (String(data) === "200" && String(data) !== "false") {
          new import_obsidian.Notice(
            `Passed ${llm_endpoint} endpoint check: Success ! \u{1F973}`
          );
          ollama = new import_ollama_node.Ollama(llm_endpoint);
        }
      }).catch((e) => {
        new import_obsidian.Notice(`Error: ${e} !`);
      });
    } catch (error) {
      new import_obsidian.Notice(`Error encountered: ${error} !`);
    }
  }
} catch (e) {
  new import_obsidian.Notice(`Error encountered: ${e} !`);
}
var DEFAULT_SETTINGS = {
  ollama_endpoint: "127.0.0.1",
  model: "tinyllama",
  botRole: "You are a helpful assistant providing only short answers"
};
async function reloadPlugin(plugin) {
  const plugins = app.plugins;
  const enabled = plugins.enabledPlugins;
  enabled.forEach(async (element) => {
    if (String(plugin) === String(element)) {
      await plugins.disablePlugin(plugin);
      new import_obsidian.Notice(`Llm plugin was disabled \u{1F642}\u{1F44D}\uFE0F!`);
      await plugins.enablePlugin(plugin);
      new import_obsidian.Notice(`Plugin was re-enabled. \u{1F4BB}\uFE0F!`);
    }
  });
}
async function streamingResponse(editor, set, userRequest, selection) {
  const llmSettings = set;
  const llmModel = llmSettings.model;
  const selectedArea = selection;
  await ollama.setModel(llmModel);
  editor.replaceSelection(`${selectedArea}

`);
  const print = (word) => {
    editor.replaceSelection(word);
  };
  await ollama.streamingGenerate(userRequest, print).catch((e) => {
    new import_obsidian.Notice(`Error ${e}`);
  });
}
var VIEW_TYPE_EXAMPLE = "example-view";
var ExampleView = class extends import_obsidian.ItemView {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  constructor(leaf, settings) {
    super(leaf);
    this.settings = settings;
  }
  getViewType() {
    return VIEW_TYPE_EXAMPLE;
  }
  getDisplayText() {
    return "Chat View";
  }
  async onOpen() {
    let set = this.settings;
    const container = this.containerEl.children[1];
    container.empty();
    container.createEl("div", {
      attr: {
        id: "chat_box",
        style: "white-space: pre-wrap;font-size:1.2rem;overflow:scroll;width:95%;padding:2.5px;border-radius:8px;height:400px;display:block;margin-top:2rem;margin-bottom:0;border:1px solid white;"
      }
    });
    container.createEl("input", {
      placeholder: this.settings.botRole,
      value: set.botRole,
      attr: {
        id: "stop_stream_button",
        style: "width:95%;padding:2px;border-radius:8px;height:2rem;font-size:1.2rem;display:block;margin-top:1rem;margin-bottom:0;border:1px solid white;"
      }
    });
    container.createEl("input", {
      attr: {
        id: "input_field",
        placeholder: "Write your text here",
        style: "width:95%;padding:2px;border-radius:8px;height:3rem;font-size:1.2rem;display:block;margin-top:1rem;margin-bottom:0;border:1px solid white;"
      }
    });
    container.createEl("button", {
      text: "Ask local LLM",
      attr: {
        id: "submit_button",
        style: "width:95%;padding:2.5px;border-radius:8px;display:block;font-size:1.2rem;margin-top:0.5rem;margin-bottom:0;border:1px solid white;"
      }
    });
    container.createEl("button", {
      text: "Clean chat",
      attr: {
        id: "clean_button",
        style: "margin-top:1rem;width:95%;padding:2.5px;border-radius:8px;display:block;font-size:1.2rem;margin-top:1rem;margin-bottom:0;border:1px solid white;"
      }
    });
    const inputSelector = container.querySelector("#input_field");
    const buttonSelector = container.querySelector("#submit_button");
    const chatboxSelector = container.querySelector("#chat_box");
    const cleanSelector = container.querySelector("#clean_button");
    const templateSelector = container.querySelector("#template_box");
    let inputvalue;
    let templateValue;
    const paragraph = document.createElement("p");
    paragraph.textContent = "Local LLM chat";
    inputSelector == null ? void 0 : inputSelector.addEventListener("keyup", (event) => {
      const target = event.target;
      if (target) {
        inputvalue = target.value;
      }
    });
    templateSelector == null ? void 0 : templateSelector.addEventListener("keyup", (event) => {
      const target = event.target;
      if (target) {
        templateValue = target.value;
      }
    });
    buttonSelector == null ? void 0 : buttonSelector.addEventListener("click", async () => {
      let passingValue = inputvalue;
      let tempValue = templateValue;
      const waitingForAnswer = `

Waiting for answer to prompt: ${passingValue}

`;
      if (chatboxSelector) {
        chatboxSelector.textContent += waitingForAnswer;
      }
      new import_obsidian.Notice("Trying to send a request to LLM !\n\nPatience !");
      const llmSettings = set;
      const llmModel = llmSettings.model;
      const temp = tempValue;
      await ollama.setModel(llmModel);
      await ollama.setTemplate(temp);
      if (chatboxSelector) {
        chatboxSelector.textContent += `

`;
      }
      const print = (word) => {
        if (chatboxSelector) {
          chatboxSelector.textContent += `${word}`;
        }
      };
      await ollama.streamingGenerate(passingValue, print);
      if (chatboxSelector) {
        chatboxSelector.textContent += `

`;
      }
    });
    if (cleanSelector) {
      cleanSelector.addEventListener("click", () => {
        if (chatboxSelector) {
          chatboxSelector.textContent = "";
        }
      });
    }
  }
  async onClose() {
  }
};
var llmPlugin = class extends import_obsidian.Plugin {
  async onload() {
    const settings = await this.loadSettings();
    this.registerView(
      VIEW_TYPE_EXAMPLE,
      (leaf) => new ExampleView(leaf, settings)
    );
    const ribbonIconEl = this.addRibbonIcon(
      "star",
      "Local LLM Chat",
      (evt) => {
        this.activateView();
      }
    );
    this.addCommand({
      id: "reload-llm",
      name: "Reload llm plugin",
      callback: () => {
        reloadPlugin("ai_llm");
      },
      hotkeys: []
    });
    this.addCommand({
      id: "send-request-to-llm",
      name: "Ask llm",
      editorCallback: (editor) => {
        const selection = editor.getSelection();
        const userRequest = selection;
        new import_obsidian.Notice("Trying to send a request to LLM !\n\nPatience !");
        streamingResponse(editor, settings, userRequest, userRequest);
      }
    });
    this.addCommand({
      id: "continue-my-story",
      name: "Continue my story and make it better",
      editorCallback: (editor) => {
        const userRequest = editor.getSelection();
        const continueRequest = `Continue my story and make it better: ${userRequest}`;
        streamingResponse(
          editor,
          settings,
          continueRequest,
          userRequest
        );
      }
    });
    this.addCommand({
      id: "make-a-story",
      name: "Make a story from my text",
      editorCallback: (editor) => {
        const userRequest = editor.getSelection();
        const storyRequest = `Make a story from my text: ${userRequest}`;
        streamingResponse(editor, settings, storyRequest, userRequest);
      }
    });
    this.addCommand({
      id: "summarize-my-text",
      name: "Summarize my text ",
      editorCallback: (editor) => {
        const userRequest = editor.getSelection();
        const summaryRequest = `Make a summary from provided text: ${userRequest}`;
        streamingResponse(
          editor,
          settings,
          summaryRequest,
          userRequest
        );
      }
    });
    this.addSettingTab(new llmSettingsTab(this.app, this, settings));
  }
  onunload() {
  }
  async activateView() {
    const { workspace } = this.app;
    let leaf = null;
    const leaves = workspace.getLeavesOfType(VIEW_TYPE_EXAMPLE);
    if (leaves.length > 0) {
      leaf = leaves[0];
    } else {
      leaf = workspace.getRightLeaf(false);
      if (leaf) {
        await leaf.setViewState({
          type: VIEW_TYPE_EXAMPLE,
          active: true
        });
        workspace.revealLeaf(leaf);
      }
    }
  }
  async loadSettings() {
    this.settings = Object.assign(
      {},
      DEFAULT_SETTINGS,
      await this.loadData()
    );
    return this.settings;
  }
  async saveSettings() {
    await this.saveData(this.settings);
  }
};
var llmSettingsTab = class extends import_obsidian.PluginSettingTab {
  constructor(app2, plugin, settings) {
    super(app2, plugin);
    this.plugin = plugin;
    this.settings = settings;
  }
  async getModels() {
    let modelList = await ollama.listModels().then((data) => {
      return data.models;
    });
    return modelList;
  }
  async display() {
    const { containerEl } = this;
    let modelOptions = await this.getModels();
    containerEl.empty();
    new import_obsidian.Setting(containerEl).setName("Ollama endpoint").setDesc("Ollama API URL").addText(
      (text) => text.setPlaceholder("Enter your endpoint url").setValue(this.plugin.settings.ollama_endpoint).onChange(async (value) => {
        this.plugin.settings.ollama_endpoint = value;
        await this.plugin.saveSettings();
      })
    );
    if (this.settings.model !== null && this.settings.model !== "") {
      new import_obsidian.Setting(containerEl).setName("LLM model").setDesc(
        "Choose a model, remember that you should download ollama and needed models first !"
      ).addDropdown((dropdown) => {
        dropdown;
        modelOptions.forEach((model) => {
          dropdown.addOption(model, model);
        });
        dropdown.setValue(this.settings.model).onChange(async (value) => {
          this.plugin.settings.model = value;
          await this.plugin.saveSettings();
        });
      });
      new import_obsidian.Setting(containerEl).setName("Default bot role").setDesc("Define a bot role").addTextArea(
        (text) => text.setPlaceholder(
          "Bot role: for example, you are a helpful assistant providing only short answers"
        ).setValue(this.plugin.settings.botRole).onChange(async (value) => {
          this.plugin.settings.botRole = value;
          await this.plugin.saveSettings();
        })
      );
    } else {
      new import_obsidian.Setting(containerEl).setName("LLM model").setDesc(
        "Choose a model, remember that you should download ollama and needed models first !"
      ).addDropdown((dropdown) => {
        modelOptions.forEach((model) => {
          dropdown.addOption(model, model);
        });
        dropdown.setValue(modelOptions[0]).onChange(async (value) => {
          this.plugin.settings.model = value;
          await this.plugin.saveSettings();
        });
      });
      new import_obsidian.Setting(containerEl).setName("Default bot role").setDesc("Define a bot role").addTextArea(
        (text) => text.setPlaceholder(
          "Bot role: for example, you are a helpful assistant providing only short answers"
        ).setValue(
          "You are a helpful assistant providing only short answers"
        ).onChange(async (value) => {
          this.plugin.settings.botRole = value;
          await this.plugin.saveSettings();
        })
      );
    }
  }
};

/* nosourcemap */