const normalizeLine = line => {
  if (line.startsWith('Error: ')) {
    return line.slice('Error: '.length);
  }
  if (line.startsWith('VError: ')) {
    return line.slice('VError: '.length);
  }
  return line;
};
const getCombinedMessage = (error, message) => {
  const stringifiedError = normalizeLine(`${error}`);
  if (message) {
    return `${message}: ${stringifiedError}`;
  }
  return stringifiedError;
};
const NewLine$2 = '\n';
const getNewLineIndex$1 = (string, startIndex = undefined) => {
  return string.indexOf(NewLine$2, startIndex);
};
const mergeStacks = (parent, child) => {
  if (!child) {
    return parent;
  }
  const parentNewLineIndex = getNewLineIndex$1(parent);
  const childNewLineIndex = getNewLineIndex$1(child);
  if (childNewLineIndex === -1) {
    return parent;
  }
  const parentFirstLine = parent.slice(0, parentNewLineIndex);
  const childRest = child.slice(childNewLineIndex);
  const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
  if (parentFirstLine.includes(childFirstLine)) {
    return parentFirstLine + childRest;
  }
  return child;
};
class VError extends Error {
  constructor(error, message) {
    const combinedMessage = getCombinedMessage(error, message);
    super(combinedMessage);
    this.name = 'VError';
    if (error instanceof Error) {
      this.stack = mergeStacks(this.stack, error.stack);
    }
    if (error.codeFrame) {
      // @ts-ignore
      this.codeFrame = error.codeFrame;
    }
    if (error.code) {
      // @ts-ignore
      this.code = error.code;
    }
  }
}

const isMessagePort = value => {
  return value && value instanceof MessagePort;
};
const isMessagePortMain = value => {
  return value && value.constructor && value.constructor.name === 'MessagePortMain';
};
const isOffscreenCanvas = value => {
  return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
};
const isInstanceOf = (value, constructorName) => {
  return value?.constructor?.name === constructorName;
};
const isSocket = value => {
  return isInstanceOf(value, 'Socket');
};
const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
const isTransferrable = value => {
  for (const fn of transferrables) {
    if (fn(value)) {
      return true;
    }
  }
  return false;
};
const walkValue = (value, transferrables, isTransferrable) => {
  if (!value) {
    return;
  }
  if (isTransferrable(value)) {
    transferrables.push(value);
    return;
  }
  if (Array.isArray(value)) {
    for (const item of value) {
      walkValue(item, transferrables, isTransferrable);
    }
    return;
  }
  if (typeof value === 'object') {
    for (const property of Object.values(value)) {
      walkValue(property, transferrables, isTransferrable);
    }
    return;
  }
};
const getTransferrables = value => {
  const transferrables = [];
  walkValue(value, transferrables, isTransferrable);
  return transferrables;
};
const attachEvents = that => {
  const handleMessage = (...args) => {
    const data = that.getData(...args);
    that.dispatchEvent(new MessageEvent('message', {
      data
    }));
  };
  that.onMessage(handleMessage);
  const handleClose = event => {
    that.dispatchEvent(new Event('close'));
  };
  that.onClose(handleClose);
};
class Ipc extends EventTarget {
  constructor(rawIpc) {
    super();
    this._rawIpc = rawIpc;
    attachEvents(this);
  }
}
const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
const NewLine$1 = '\n';
const joinLines$1 = lines => {
  return lines.join(NewLine$1);
};
const RE_AT = /^\s+at/;
const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
const isNormalStackLine = line => {
  return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
};
const getDetails = lines => {
  const index = lines.findIndex(isNormalStackLine);
  if (index === -1) {
    return {
      actualMessage: joinLines$1(lines),
      rest: []
    };
  }
  let lastIndex = index - 1;
  while (++lastIndex < lines.length) {
    if (!isNormalStackLine(lines[lastIndex])) {
      break;
    }
  }
  return {
    actualMessage: lines[index - 1],
    rest: lines.slice(index, lastIndex)
  };
};
const splitLines$1 = lines => {
  return lines.split(NewLine$1);
};
const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
const isMessageCodeBlockStartIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_START.test(line);
};
const isMessageCodeBlockEndIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_END.test(line);
};
const getMessageCodeBlock = stderr => {
  const lines = splitLines$1(stderr);
  const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
  const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
  const relevantLines = lines.slice(startIndex, endIndex);
  const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
  return relevantMessage;
};
const isModuleNotFoundMessage = line => {
  return line.includes('[ERR_MODULE_NOT_FOUND]');
};
const getModuleNotFoundError = stderr => {
  const lines = splitLines$1(stderr);
  const messageIndex = lines.findIndex(isModuleNotFoundMessage);
  const message = lines[messageIndex];
  return {
    code: ERR_MODULE_NOT_FOUND,
    message
  };
};
const isModuleNotFoundError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('ERR_MODULE_NOT_FOUND');
};
const isModulesSyntaxError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('SyntaxError: Cannot use import statement outside a module');
};
const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
const isUnhelpfulNativeModuleError = stderr => {
  return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
};
const getNativeModuleErrorMessage = stderr => {
  const message = getMessageCodeBlock(stderr);
  return {
    code: E_INCOMPATIBLE_NATIVE_MODULE,
    message: `Incompatible native node module: ${message}`
  };
};
const getModuleSyntaxError = () => {
  return {
    code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
    message: `ES Modules are not supported in electron`
  };
};
const getHelpfulChildProcessError = (stdout, stderr) => {
  if (isUnhelpfulNativeModuleError(stderr)) {
    return getNativeModuleErrorMessage(stderr);
  }
  if (isModulesSyntaxError(stderr)) {
    return getModuleSyntaxError();
  }
  if (isModuleNotFoundError(stderr)) {
    return getModuleNotFoundError(stderr);
  }
  const lines = splitLines$1(stderr);
  const {
    actualMessage,
    rest
  } = getDetails(lines);
  return {
    code: '',
    message: actualMessage,
    stack: rest
  };
};
class IpcError extends VError {
  // @ts-ignore
  constructor(betterMessage, stdout = '', stderr = '') {
    if (stdout || stderr) {
      // @ts-ignore
      const {
        code,
        message,
        stack
      } = getHelpfulChildProcessError(stdout, stderr);
      const cause = new Error(message);
      // @ts-ignore
      cause.code = code;
      cause.stack = stack;
      super(cause, betterMessage);
    } else {
      super(betterMessage);
    }
    // @ts-ignore
    this.name = 'IpcError';
    // @ts-ignore
    this.stdout = stdout;
    // @ts-ignore
    this.stderr = stderr;
  }
}
const readyMessage = 'ready';
const getData$2 = event => {
  return event.data;
};
const listen$7 = () => {
  // @ts-ignore
  if (typeof WorkerGlobalScope === 'undefined') {
    throw new TypeError('module is not in web worker scope');
  }
  return globalThis;
};
const signal$8 = global => {
  global.postMessage(readyMessage);
};
class IpcChildWithModuleWorker extends Ipc {
  getData(event) {
    return getData$2(event);
  }
  send(message) {
    // @ts-ignore
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    // @ts-ignore
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    // ignore
  }
  onClose(callback) {
    // ignore
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
}
const wrap$f = global => {
  return new IpcChildWithModuleWorker(global);
};
const IpcChildWithModuleWorker$1 = {
  __proto__: null,
  listen: listen$7,
  signal: signal$8,
  wrap: wrap$f
};
const Error$3 = 1;
const Open = 2;
const Close = 3;
const addListener = (emitter, type, callback) => {
  if ('addEventListener' in emitter) {
    emitter.addEventListener(type, callback);
  } else {
    emitter.on(type, callback);
  }
};
const removeListener = (emitter, type, callback) => {
  if ('removeEventListener' in emitter) {
    emitter.removeEventListener(type, callback);
  } else {
    emitter.off(type, callback);
  }
};
const getFirstEvent = (eventEmitter, eventMap) => {
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  const listenerMap = Object.create(null);
  const cleanup = value => {
    for (const event of Object.keys(eventMap)) {
      removeListener(eventEmitter, event, listenerMap[event]);
    }
    resolve(value);
  };
  for (const [event, type] of Object.entries(eventMap)) {
    const listener = event => {
      cleanup({
        event,
        type
      });
    };
    addListener(eventEmitter, event, listener);
    listenerMap[event] = listener;
  }
  return promise;
};
const Message$1 = 3;
const create$5$1 = async ({
  isMessagePortOpen,
  messagePort
}) => {
  if (!isMessagePort(messagePort)) {
    throw new IpcError('port must be of type MessagePort');
  }
  if (isMessagePortOpen) {
    return messagePort;
  }
  const eventPromise = getFirstEvent(messagePort, {
    message: Message$1
  });
  messagePort.start();
  const {
    event,
    type
  } = await eventPromise;
  if (type !== Message$1) {
    throw new IpcError('Failed to wait for ipc message');
  }
  if (event.data !== readyMessage) {
    throw new IpcError('unexpected first message');
  }
  return messagePort;
};
const signal$1 = messagePort => {
  messagePort.start();
};
class IpcParentWithMessagePort extends Ipc {
  getData = getData$2;
  send(message) {
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    this._rawIpc.close();
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
  onClose(callback) {}
}
const wrap$5 = messagePort => {
  return new IpcParentWithMessagePort(messagePort);
};
const IpcParentWithMessagePort$1 = {
  __proto__: null,
  create: create$5$1,
  signal: signal$1,
  wrap: wrap$5
};
const stringifyCompact = value => {
  return JSON.stringify(value);
};
const parse = content => {
  if (content === 'undefined') {
    return null;
  }
  try {
    return JSON.parse(content);
  } catch (error) {
    throw new VError(error, 'failed to parse json');
  }
};
const waitForWebSocketToBeOpen = webSocket => {
  return getFirstEvent(webSocket, {
    close: Close,
    error: Error$3,
    open: Open
  });
};
const create$c = async ({
  webSocket
}) => {
  const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
  if (firstWebSocketEvent.type === Error$3) {
    throw new IpcError(`WebSocket connection error`);
  }
  if (firstWebSocketEvent.type === Close) {
    throw new IpcError('Websocket connection was immediately closed');
  }
  return webSocket;
};
class IpcParentWithWebSocket extends Ipc {
  getData(event) {
    return parse(event.data);
  }
  send(message) {
    this._rawIpc.send(stringifyCompact(message));
  }
  sendAndTransfer(message) {
    throw new Error('sendAndTransfer not supported');
  }
  dispose() {
    this._rawIpc.close();
  }
  onClose(callback) {
    this._rawIpc.addEventListener('close', callback);
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
}
const wrap = webSocket => {
  return new IpcParentWithWebSocket(webSocket);
};
const IpcParentWithWebSocket$1 = {
  __proto__: null,
  create: create$c,
  wrap
};

class CommandNotFoundError extends Error {
  constructor(command) {
    super(`Command not found ${command}`);
    this.name = 'CommandNotFoundError';
  }
}
const commands = Object.create(null);
const register = commandMap => {
  Object.assign(commands, commandMap);
};
const getCommand = key => {
  return commands[key];
};
const execute = (command, ...args) => {
  const fn = getCommand(command);
  if (!fn) {
    throw new CommandNotFoundError(command);
  }
  return fn(...args);
};

const Two$1 = '2.0';
const callbacks = Object.create(null);
const get$1 = id => {
  return callbacks[id];
};
const remove$1 = id => {
  delete callbacks[id];
};
class JsonRpcError extends Error {
  constructor(message) {
    super(message);
    this.name = 'JsonRpcError';
  }
}
const NewLine = '\n';
const DomException = 'DOMException';
const ReferenceError$1 = 'ReferenceError';
const SyntaxError$1 = 'SyntaxError';
const TypeError$1 = 'TypeError';
const getErrorConstructor = (message, type) => {
  if (type) {
    switch (type) {
      case DomException:
        return DOMException;
      case ReferenceError$1:
        return ReferenceError;
      case SyntaxError$1:
        return SyntaxError;
      case TypeError$1:
        return TypeError;
      default:
        return Error;
    }
  }
  if (message.startsWith('TypeError: ')) {
    return TypeError;
  }
  if (message.startsWith('SyntaxError: ')) {
    return SyntaxError;
  }
  if (message.startsWith('ReferenceError: ')) {
    return ReferenceError;
  }
  return Error;
};
const constructError = (message, type, name) => {
  const ErrorConstructor = getErrorConstructor(message, type);
  if (ErrorConstructor === DOMException && name) {
    return new ErrorConstructor(message, name);
  }
  if (ErrorConstructor === Error) {
    const error = new Error(message);
    if (name && name !== 'VError') {
      error.name = name;
    }
    return error;
  }
  return new ErrorConstructor(message);
};
const joinLines = lines => {
  return lines.join(NewLine);
};
const splitLines = lines => {
  return lines.split(NewLine);
};
const getCurrentStack = () => {
  const stackLinesToSkip = 3;
  const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
  return currentStack;
};
const getNewLineIndex = (string, startIndex = undefined) => {
  return string.indexOf(NewLine, startIndex);
};
const getParentStack = error => {
  let parentStack = error.stack || error.data || error.message || '';
  if (parentStack.startsWith('    at')) {
    parentStack = error.message + NewLine + parentStack;
  }
  return parentStack;
};
const MethodNotFound = -32601;
const Custom = -32001;
const restoreJsonRpcError = error => {
  const currentStack = getCurrentStack();
  if (error && error instanceof Error) {
    if (typeof error.stack === 'string') {
      error.stack = error.stack + NewLine + currentStack;
    }
    return error;
  }
  if (error && error.code && error.code === MethodNotFound) {
    const restoredError = new JsonRpcError(error.message);
    const parentStack = getParentStack(error);
    restoredError.stack = parentStack + NewLine + currentStack;
    return restoredError;
  }
  if (error && error.message) {
    const restoredError = constructError(error.message, error.type, error.name);
    if (error.data) {
      if (error.data.stack && error.data.type && error.message) {
        restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
      } else if (error.data.stack) {
        restoredError.stack = error.data.stack;
      }
      if (error.data.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.data.codeFrame;
      }
      if (error.data.code) {
        // @ts-ignore
        restoredError.code = error.data.code;
      }
      if (error.data.type) {
        // @ts-ignore
        restoredError.name = error.data.type;
      }
    } else {
      if (error.stack) {
        const lowerStack = restoredError.stack || '';
        // @ts-ignore
        const indexNewLine = getNewLineIndex(lowerStack);
        const parentStack = getParentStack(error);
        // @ts-ignore
        restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
      }
      if (error.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.codeFrame;
      }
    }
    return restoredError;
  }
  if (typeof error === 'string') {
    return new Error(`JsonRpc Error: ${error}`);
  }
  return new Error(`JsonRpc Error: ${error}`);
};
const unwrapJsonRpcResult = responseMessage => {
  if ('error' in responseMessage) {
    const restoredError = restoreJsonRpcError(responseMessage.error);
    throw restoredError;
  }
  if ('result' in responseMessage) {
    return responseMessage.result;
  }
  throw new JsonRpcError('unexpected response message');
};
const warn = (...args) => {
  console.warn(...args);
};
const resolve = (id, response) => {
  const fn = get$1(id);
  if (!fn) {
    console.log(response);
    warn(`callback ${id} may already be disposed`);
    return;
  }
  fn(response);
  remove$1(id);
};
const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
const getErrorType = prettyError => {
  if (prettyError && prettyError.type) {
    return prettyError.type;
  }
  if (prettyError && prettyError.constructor && prettyError.constructor.name) {
    return prettyError.constructor.name;
  }
  return undefined;
};
const isAlreadyStack = line => {
  return line.trim().startsWith('at ');
};
const getStack = prettyError => {
  const stackString = prettyError.stack || '';
  const newLineIndex = stackString.indexOf('\n');
  if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
    return stackString.slice(newLineIndex + 1);
  }
  return stackString;
};
const getErrorProperty = (error, prettyError) => {
  if (error && error.code === E_COMMAND_NOT_FOUND) {
    return {
      code: MethodNotFound,
      data: error.stack,
      message: error.message
    };
  }
  return {
    code: Custom,
    data: {
      code: prettyError.code,
      codeFrame: prettyError.codeFrame,
      name: prettyError.name,
      stack: getStack(prettyError),
      type: getErrorType(prettyError)
    },
    message: prettyError.message
  };
};
const create$1$1 = (id, error) => {
  return {
    error,
    id,
    jsonrpc: Two$1
  };
};
const getErrorResponse = (id, error, preparePrettyError, logError) => {
  const prettyError = preparePrettyError(error);
  logError(error, prettyError);
  const errorProperty = getErrorProperty(error, prettyError);
  return create$1$1(id, errorProperty);
};
const create$b = (message, result) => {
  return {
    id: message.id,
    jsonrpc: Two$1,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$b(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    error: {
      code: Custom,
      data: error,
      // @ts-ignore
      message: error.message
    },
    id,
    jsonrpc: Two$1
  };
};
const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
  try {
    const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
    return getSuccessResponse(message, result);
  } catch (error) {
    if (ipc.canUseSimpleErrorResponse) {
      return getErrorResponseSimple(message.id, error);
    }
    return getErrorResponse(message.id, error, preparePrettyError, logError);
  }
};
const defaultPreparePrettyError = error => {
  return error;
};
const defaultLogError = () => {
  // ignore
};
const defaultRequiresSocket = () => {
  return false;
};
const defaultResolve = resolve;

// TODO maybe remove this in v6 or v7, only accept options object to simplify the code
const normalizeParams = args => {
  if (args.length === 1) {
    const options = args[0];
    return {
      execute: options.execute,
      ipc: options.ipc,
      logError: options.logError || defaultLogError,
      message: options.message,
      preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
      requiresSocket: options.requiresSocket || defaultRequiresSocket,
      resolve: options.resolve || defaultResolve
    };
  }
  return {
    execute: args[2],
    ipc: args[0],
    logError: args[5],
    message: args[1],
    preparePrettyError: args[4],
    requiresSocket: args[6],
    resolve: args[3]
  };
};
const handleJsonRpcMessage = async (...args) => {
  const options = normalizeParams(args);
  const {
    execute,
    ipc,
    logError,
    message,
    preparePrettyError,
    requiresSocket,
    resolve
  } = options;
  if ('id' in message) {
    if ('method' in message) {
      const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
      try {
        ipc.send(response);
      } catch (error) {
        const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
        ipc.send(errorResponse);
      }
      return;
    }
    resolve(message.id, message);
    return;
  }
  if ('method' in message) {
    await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
    return;
  }
  throw new JsonRpcError('unexpected message');
};

const Two = '2.0';

const create$a = (method, params) => {
  return {
    jsonrpc: Two,
    method,
    params
  };
};

const create$9 = (id, method, params) => {
  const message = {
    id,
    jsonrpc: Two,
    method,
    params
  };
  return message;
};

let id = 0;
const create$8 = () => {
  return ++id;
};

const registerPromise = map => {
  const id = create$8();
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  map[id] = resolve;
  return {
    id,
    promise
  };
};

const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$9(id, method, params);
  if (useSendAndTransfer && ipc.sendAndTransfer) {
    ipc.sendAndTransfer(message);
  } else {
    ipc.send(message);
  }
  const responseMessage = await promise;
  return unwrapJsonRpcResult(responseMessage);
};
const createRpc = ipc => {
  const callbacks = Object.create(null);
  ipc._resolve = (id, response) => {
    const fn = callbacks[id];
    if (!fn) {
      console.warn(`callback ${id} may already be disposed`);
      return;
    }
    fn(response);
    delete callbacks[id];
  };
  const rpc = {
    async dispose() {
      await ipc?.dispose();
    },
    invoke(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, false);
    },
    invokeAndTransfer(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, true);
    },
    // @ts-ignore
    ipc,
    /**
     * @deprecated
     */
    send(method, ...params) {
      const message = create$a(method, params);
      ipc.send(message);
    }
  };
  return rpc;
};

const requiresSocket = () => {
  return false;
};
const preparePrettyError = error => {
  return error;
};
const logError = () => {
  // handled by renderer worker
};
const handleMessage = event => {
  const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
  const actualExecute = event?.target?.execute || execute;
  return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
};

const handleIpc = ipc => {
  if ('addEventListener' in ipc) {
    ipc.addEventListener('message', handleMessage);
  } else if ('on' in ipc) {
    // deprecated
    ipc.on('message', handleMessage);
  }
};

const listen$1 = async (module, options) => {
  const rawIpc = await module.listen(options);
  if (module.signal) {
    module.signal(rawIpc);
  }
  const ipc = module.wrap(rawIpc);
  return ipc;
};

const create$7 = async ({
  commandMap,
  isMessagePortOpen = true,
  messagePort
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithMessagePort$1.create({
    isMessagePortOpen,
    messagePort
  });
  const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  messagePort.start();
  return rpc;
};

const create$6 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  const {
    port1,
    port2
  } = new MessageChannel();
  await send(port1);
  return create$7({
    commandMap,
    isMessagePortOpen,
    messagePort: port2
  });
};

const createSharedLazyRpc = factory => {
  let rpcPromise;
  const getOrCreate = () => {
    if (!rpcPromise) {
      rpcPromise = factory();
    }
    return rpcPromise;
  };
  return {
    async dispose() {
      const rpc = await getOrCreate();
      await rpc.dispose();
    },
    async invoke(method, ...params) {
      const rpc = await getOrCreate();
      return rpc.invoke(method, ...params);
    },
    async invokeAndTransfer(method, ...params) {
      const rpc = await getOrCreate();
      return rpc.invokeAndTransfer(method, ...params);
    },
    async send(method, ...params) {
      const rpc = await getOrCreate();
      rpc.send(method, ...params);
    }
  };
};

const create$5 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  return createSharedLazyRpc(() => {
    return create$6({
      commandMap,
      isMessagePortOpen,
      send
    });
  });
};

const Https = 'https:';
const Ws = 'ws:';
const Wss = 'wss:';

const getWebSocketProtocol = locationProtocol => {
  return locationProtocol === Https ? Wss : Ws;
};

const getWebSocketUrl = (type, host, locationProtocol) => {
  const wsProtocol = getWebSocketProtocol(locationProtocol);
  return `${wsProtocol}//${host}/websocket/${type}`;
};

const getHost = () => {
  return location.host;
};
const getProtocol = () => {
  return location.protocol;
};

const create$4 = async ({
  commandMap,
  webSocket
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithWebSocket$1.create({
    webSocket
  });
  const ipc = IpcParentWithWebSocket$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};

const create$3 = async ({
  commandMap,
  type
}) => {
  const host = getHost();
  const protocol = getProtocol();
  const wsUrl = getWebSocketUrl(type, host, protocol);
  const webSocket = new WebSocket(wsUrl);
  const rpc = await create$4({
    commandMap,
    webSocket
  });
  return rpc;
};

const create$2 = async ({
  commandMap,
  type
}) => {
  return createSharedLazyRpc(() => {
    return create$3({
      commandMap,
      type
    });
  });
};

const create$1 = async ({
  commandMap
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const ipc = await listen$1(IpcChildWithModuleWorker$1);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};

const createMockRpc = ({
  commandMap
}) => {
  const invocations = [];
  const invoke = (method, ...params) => {
    invocations.push([method, ...params]);
    const command = commandMap[method];
    if (!command) {
      throw new Error(`command ${method} not found`);
    }
    return command(...params);
  };
  const mockRpc = {
    invocations,
    invoke,
    invokeAndTransfer: invoke
  };
  return mockRpc;
};

const rpcs = Object.create(null);
const set$4 = (id, rpc) => {
  rpcs[id] = rpc;
};
const get = id => {
  return rpcs[id];
};
const remove = id => {
  delete rpcs[id];
};

/* eslint-disable  @typescript-eslint/explicit-function-return-type */
const create = rpcId => {
  return {
    async dispose() {
      const rpc = get(rpcId);
      await rpc.dispose();
    },
    // @ts-ignore
    invoke(method, ...params) {
      const rpc = get(rpcId);
      // @ts-ignore
      return rpc.invoke(method, ...params);
    },
    // @ts-ignore
    invokeAndTransfer(method, ...params) {
      const rpc = get(rpcId);
      // @ts-ignore
      return rpc.invokeAndTransfer(method, ...params);
    },
    registerMockRpc(commandMap) {
      const mockRpc = createMockRpc({
        commandMap
      });
      set$4(rpcId, mockRpc);
      // @ts-ignore
      mockRpc[Symbol.dispose] = () => {
        remove(rpcId);
      };
      // @ts-ignore
      return mockRpc;
    },
    set(rpc) {
      set$4(rpcId, rpc);
    }
  };
};

const Directory = 3;
const File = 7;
const Symlink = 9;

const Electron = 2;
const Remote = 3;

const ChatStorageWorker = 6003;
const FileSystemWorker = 209;
const RendererWorker = 1;
const TerminalProcess = 7;

const {
  set: set$3
} = create(ChatStorageWorker);

const {
  invoke: invoke$2,
  set: set$2
} = create(FileSystemWorker);
const readDirWithFileTypes = async uri => {
  return invoke$2('FileSystem.readDirWithFileTypes', uri);
};
const readFile$1 = async uri => {
  return invoke$2('FileSystem.readFile', uri);
};
const writeFile$1 = async (uri, content) => {
  return invoke$2('FileSystem.writeFile', uri, content);
};
const exists = async uri => {
  return invoke$2('FileSystem.exists', uri);
};

const {
  invoke: invoke$1,
  invokeAndTransfer,
  set: set$1
} = create(RendererWorker);
const sendMessagePortToTerminalProcess = async (port, rpcId) => {
  const command = 'HandleMessagePortForTerminalProcess.handleMessagePortForTerminalProcess';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToTerminalProcess', port, command, rpcId);
};
const sendMessagePortToFileSystemWorker = async (port, rpcId) => {
  const command = 'FileSystem.handleMessagePort';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSystemWorker', port, command, rpcId);
};
const readFile = async uri => {
  return invoke$1('FileSystem.readFile', uri);
};
const sendMessagePortToChatStorageWorker = async port => {
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToChatStorageWorker', port, 'HandleMessagePort.handleMessagePort');
};
const writeFile = async (uri, text) => {
  await invoke$1('FileSystem.writeFile', uri, text);
};
const getWorkspacePath = () => {
  return invoke$1('Workspace.getPath');
};

const {
  invoke,
  set
} = create(TerminalProcess);

const INVALID_URI_ERROR_CODE = 'E_INVALID_URI';
const getInvalidUriErrorPayload = argumentName => {
  return {
    error: `Invalid argument: ${argumentName} must be an absolute URI.`,
    errorCode: INVALID_URI_ERROR_CODE
  };
};
const getInvalidUrlErrorPayload = () => {
  return {
    error: 'Invalid argument: invalid URL.',
    errorCode: INVALID_URI_ERROR_CODE
  };
};
const getToolErrorPayload = error => {
  const rawCode = error && typeof error === 'object' ? Reflect.get(error, 'code') : undefined;
  const rawStack = error && typeof error === 'object' ? Reflect.get(error, 'stack') : undefined;
  return {
    error: String(error),
    ...(typeof rawCode === 'string' && rawCode.trim() ? {
      errorCode: rawCode
    } : {}),
    ...(typeof rawStack === 'string' && rawStack.trim() ? {
      errorStack: rawStack,
      stack: rawStack
    } : {})
  };
};

const executeClosePreviewTool = async (_args, _options) => {
  try {
    await invoke$1('Preview.close');
    return {
      ok: true
    };
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

const ABSOLUTE_URI_REGEX = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
const isAbsoluteUri = value => {
  return ABSOLUTE_URI_REGEX.test(value);
};

const executeCreateDirectoryTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    new URL(uri);
  } catch {
    return getInvalidUrlErrorPayload();
  }
  try {
    await invoke$1('FileSystem.mkdir', uri);
    return {
      ok: true,
      uri
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      uri
    };
  }
};

const applyTextEdit = (content, start, end, text) => {
  if (start > content.length || end > content.length) {
    throw new Error('Invalid argument: edit range is out of bounds.');
  }
  return `${content.slice(0, start)}${text}${content.slice(end)}`;
};

const executeEditFileTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  const start = typeof args.start === 'number' ? args.start : -1;
  const end = typeof args.end === 'number' ? args.end : -1;
  const text = typeof args.text === 'string' ? args.text : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    new URL(uri);
  } catch {
    return getInvalidUrlErrorPayload();
  }
  if (!Number.isInteger(start) || start < 0) {
    return {
      error: 'Invalid argument: start must be a non-negative integer.'
    };
  }
  if (!Number.isInteger(end) || end < 0) {
    return {
      error: 'Invalid argument: end must be a non-negative integer.'
    };
  }
  if (start > end) {
    return {
      error: 'Invalid argument: start must be less than or equal to end.'
    };
  }
  try {
    const content = await readFile(uri);
    const nextContent = applyTextEdit(content, start, end, text);
    await writeFile(uri, nextContent);
    return {
      ok: true,
      uri
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      uri
    };
  }
};

const windowsDrivePathRegex$1 = /^[a-zA-Z]:[\\/]/;
const isAbsoluteFileSystemPath = value => {
  return value.startsWith('/') || windowsDrivePathRegex$1.test(value);
};

const windowsDrivePathRegex = /^[a-zA-Z]:[\\/]/;
const normalizeWorkspaceUri = workspacePathOrUri => {
  if (!isAbsoluteFileSystemPath(workspacePathOrUri)) {
    return workspacePathOrUri;
  }
  const url = new URL('file:///');
  url.pathname = windowsDrivePathRegex.test(workspacePathOrUri) ? `/${workspacePathOrUri.replaceAll('\\', '/')}` : workspacePathOrUri;
  return url.href;
};
const executeGetWorkspaceUriTool = async (_args, _options) => {
  try {
    const workspacePathOrUri = await getWorkspacePath();
    const workspaceUri = normalizeWorkspaceUri(workspacePathOrUri);
    return {
      workspaceUri
    };
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

/**
 * Matches a string against a glob pattern
 * Supported patterns:
 * - * matches any characters except /
 * - ? matches a single character except /
 * - ** matches any characters including /
 * - [abc] matches a, b, or c
 * - [!abc] matches any character except a, b, c
 * - [a-z] matches any character between a and z
 */

const REGEX_SPECIAL_CHARS_REGEX = /[.*+?^${}()|[\]\\]/g;
const LEADING_DOT_SLASH_REGEX$1 = /^\.\//g;
const MULTIPLE_SLASHES_REGEX$1 = /\/+/g;
const escapeRegExp = str => {
  return str.replaceAll(REGEX_SPECIAL_CHARS_REGEX, '\\$&');
};

/*
 * Convert a glob pattern to a regex, but only for segments between separators
 */
const segmentToRegex = segment => {
  let regexStr = '';
  let i = 0;
  while (i < segment.length) {
    const char = segment[i];
    switch (char) {
      case '?':
        {
          regexStr += '[^/]';
          i++;
          break;
        }
      case '[':
        {
          let j = i + 1;
          let negated = false;
          if (j < segment.length && segment[j] === '!') {
            negated = true;
            j++;
          }
          let classStr = '';
          while (j < segment.length && segment[j] !== ']') {
            classStr += segment[j];
            j++;
          }
          if (j < segment.length) {
            if (negated) {
              regexStr += `[^${escapeRegExp(classStr)}]`;
            } else {
              regexStr += `[${classStr.replaceAll('\\', '\\\\')}]`;
            }
            i = j + 1;
          } else {
            regexStr += escapeRegExp(char);
            i++;
          }
          break;
        }
      case '*':
        {
          regexStr += '[^/]*';
          i++;
          break;
        }
      default:
        {
          regexStr += escapeRegExp(char);
          i++;
        }
    }
  }
  return new RegExp(`^${regexStr}$`);
};
const matchesGlobPattern = (path, pattern) => {
  const normalizedPath = path.replaceAll('\\', '/').replaceAll(LEADING_DOT_SLASH_REGEX$1, '');
  let normalizedPattern = pattern.replaceAll('\\', '/').replaceAll(LEADING_DOT_SLASH_REGEX$1, '').replaceAll(MULTIPLE_SLASHES_REGEX$1, '/');
  if (normalizedPattern.endsWith('/')) {
    normalizedPattern = normalizedPattern.slice(0, -1) + '/*';
  }
  const patternParts = normalizedPattern.split('/');
  const pathParts = normalizedPath.split('/');
  return matchesPatternParts(pathParts, patternParts, 0, 0);
};
const matchesPatternParts = (pathParts, patternParts, pathIdx, patternIdx) => {
  if (patternIdx === patternParts.length) {
    return pathIdx === pathParts.length;
  }
  if (pathIdx > pathParts.length) {
    return false;
  }
  const patternPart = patternParts[patternIdx];
  if (patternPart === undefined) {
    return false;
  }
  if (patternPart === '**') {
    for (let i = pathIdx; i <= pathParts.length; i++) {
      if (matchesPatternParts(pathParts, patternParts, i, patternIdx + 1)) {
        return true;
      }
    }
    return false;
  }
  if (pathIdx === pathParts.length) {
    return false;
  }
  if (patternPart.includes('**')) {
    const regex = segmentToRegex(patternPart.replace('**', ''));
    const pathPart = pathParts[pathIdx];
    if (pathPart !== undefined && regex.test(pathPart)) {
      return matchesPatternParts(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
    }
    return false;
  }
  const regex = segmentToRegex(patternPart);
  const pathPart = pathParts[pathIdx];
  if (pathPart !== undefined && regex.test(pathPart)) {
    return matchesPatternParts(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
  }
  return false;
};

// cspell:ignore venv
const DEFAULT_EXCLUDE_DIRS = new Set(['.git', 'node_modules', '.cache', '.venv', 'dist', 'build', '.next', '.nuxt']);
const shouldExcludeDir = dirName => {
  return DEFAULT_EXCLUDE_DIRS.has(dirName);
};
const traverseDirectory = async (baseUri, currentPath, onEntry) => {
  const visited = new Set();
  const visit = async path => {
    const uri = path === '' ? baseUri : `${baseUri}/${path}`;
    if (visited.has(uri)) {
      return;
    }
    visited.add(uri);
    try {
      const entries = await readDirWithFileTypes(uri);
      for (const entry of entries) {
        const entryPath = path === '' ? entry.name : `${path}/${entry.name}`;
        await onEntry(entryPath, entry);
        if (entry.type === Directory && !shouldExcludeDir(entry.name)) {
          await visit(entryPath);
        }
      }
    } catch (error) {
      if (path === '') {
        throw error;
      }
      // Ignore unreadable directories and continue with other matches.
    }
  };
  return visit(currentPath);
};

const MULTIPLE_SLASHES_REGEX = /\/+/g;
const LEADING_DOT_SLASH_REGEX = /^\.\//g;
const PLACEHOLDER_WORKSPACE_URI = 'file:///workspace';
const hasGlobCharacters = part => {
  return part.includes('*') || part.includes('?') || part.includes('[');
};
const normalizeInputPattern = pattern => {
  return pattern.trim().replaceAll('\\', '/').replaceAll(LEADING_DOT_SLASH_REGEX, '').replaceAll(MULTIPLE_SLASHES_REGEX, '/');
};
const normalizePattern = pattern => {
  const normalized = normalizeInputPattern(pattern);
  const matchDirectories = normalized.endsWith('/');
  const patternToParse = matchDirectories ? normalized.slice(0, -1) : normalized;
  const parts = patternToParse.split('/');
  let firstGlobIndex = -1;
  for (let i = 0; i < parts.length; i++) {
    const part = parts[i];
    if (part && hasGlobCharacters(part)) {
      firstGlobIndex = i;
      break;
    }
  }
  const globPartIndex = firstGlobIndex === -1 ? Math.max(parts.length - 1, 0) : firstGlobIndex;
  const baseDir = parts.slice(0, globPartIndex).join('/');
  const globPart = parts.slice(globPartIndex).join('/');
  return {
    baseDir,
    globPart,
    matchDirectories
  };
};
const joinUri = (baseUri, path) => {
  if (!path) {
    return baseUri;
  }
  return baseUri.endsWith('/') ? `${baseUri}${path}` : `${baseUri}/${path}`;
};
const executeGlobTool = async (args, _options) => {
  const pattern = typeof args.pattern === 'string' ? args.pattern : '';
  if (!pattern) {
    return {
      error: 'Invalid argument: pattern must be a non-empty string.'
    };
  }
  const baseUri = typeof args.baseUri === 'string' ? args.baseUri : '';
  if (!baseUri || !isAbsoluteUri(baseUri)) {
    return getInvalidUriErrorPayload('baseUri');
  }
  if (baseUri === PLACEHOLDER_WORKSPACE_URI || baseUri.startsWith(`${PLACEHOLDER_WORKSPACE_URI}/`)) {
    return {
      baseUri,
      error: 'Invalid argument: baseUri must be a real workspace folder URI. Call getWorkspaceUri first and use the returned workspaceUri value.'
    };
  }
  const normalizedPattern = normalizeInputPattern(pattern);
  const {
    baseDir,
    globPart,
    matchDirectories
  } = normalizePattern(pattern);
  const matches = [];
  try {
    if (matchDirectories) {
      const dirUri = joinUri(baseUri, globPart);
      const entries = await readDirWithFileTypes(dirUri);
      for (const entry of entries) {
        matches.push(globPart ? `${globPart}/${entry.name}` : entry.name);
      }
    } else if (globPart.includes('**')) {
      const baseDirUri = joinUri(baseUri, baseDir);
      await traverseDirectory(baseDirUri, '', async (relativePath, entry) => {
        if (entry.type !== File) {
          return;
        }
        const fullPath = baseDir ? `${baseDir}/${relativePath}` : relativePath;
        if (matchesGlobPattern(fullPath, normalizedPattern)) {
          matches.push(fullPath);
        }
      });
    } else {
      const dirUri = joinUri(baseUri, baseDir);
      const entries = await readDirWithFileTypes(dirUri);
      for (const entry of entries) {
        const fullPath = baseDir ? `${baseDir}/${entry.name}` : entry.name;
        if (matchesGlobPattern(fullPath, normalizedPattern)) {
          matches.push(fullPath);
        }
      }
    }
    matches.sort();
    return {
      paths: matches,
      pattern
    };
  } catch (error) {
    return {
      error: `Failed to glob: ${error instanceof Error ? error.message : String(error)}`,
      pattern
    };
  }
};

const escapeXml = value => {
  return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
};
const formatTextMatches = matches => {
  const lines = [];
  for (const match of matches) {
    if (typeof match.lineNumber === 'number') {
      lines.push(`${match.path}:${match.lineNumber}:${match.text}`);
    } else {
      lines.push(`${match.path}: ${match.text}`);
    }
  }
  return lines.join('\n');
};
const formatXmlMatches = matches => {
  const lines = [`${matches.length} matches`];
  for (const match of matches) {
    const attributes = [`path="${escapeXml(match.path)}"`];
    if (typeof match.lineNumber === 'number') {
      attributes.push(`line="${match.lineNumber}"`);
    }
    lines.push(`<match ${attributes.join(' ')}>`);
    lines.push(escapeXml(match.text));
    lines.push('</match>');
  }
  return lines.join('\n');
};
const formatJsonMatches = matches => {
  return {
    count: matches.length,
    matches: matches.map(match => ({
      ...(typeof match.lineNumber === 'number' ? {
        line: match.lineNumber
      } : {}),
      path: match.path,
      text: match.text
    })),
    matchesFound: matches.length > 0
  };
};
const formatGrepMatches = (matches, outputFormat) => {
  if (outputFormat === 'json') {
    return formatJsonMatches(matches);
  }
  if (matches.length === 0) {
    return 'No matches found.';
  }
  switch (outputFormat) {
    case 'xml':
      return formatXmlMatches(matches);
    default:
      return formatTextMatches(matches);
  }
};

const formatSearchProcessResults = (results, outputFormat) => {
  if (!results || results.length === 0) {
    return formatGrepMatches([], outputFormat);
  }
  let currentFile = '';
  const matches = [];
  for (const result of results) {
    if (result.type === 1) {
      currentFile = result.text;
      continue;
    }
    if (result.type === 2) {
      if (currentFile) {
        matches.push({
          lineNumber: result.lineNumber,
          path: currentFile,
          text: result.text
        });
      } else {
        matches.push({
          lineNumber: result.lineNumber,
          path: '',
          text: result.text
        });
      }
    }
  }
  if (matches.length === 0) {
    return formatGrepMatches([], outputFormat);
  }
  return formatGrepMatches(matches, outputFormat);
};

const isFileUri = value => {
  return value.startsWith('file://');
};

const defaultExcludeGlobs = ['!**/node_modules/**', '!**/.git/**'];
const getRipGrepArgs = ({
  includeIgnoredFiles,
  includePattern,
  isRegexp,
  query,
  useDefaultExcludes
}) => {
  const ripGrepArgs = ['--hidden', '--no-require-git', '--smart-case', '--stats', '--json', '--threads', '1', '--ignore-case'];
  if (includeIgnoredFiles) {
    ripGrepArgs.push('--no-ignore');
  }
  if (useDefaultExcludes) {
    for (const glob of defaultExcludeGlobs) {
      ripGrepArgs.push('--glob', glob);
    }
  }
  if (includePattern && !isFileUri(includePattern) && !isAbsoluteFileSystemPath(includePattern)) {
    ripGrepArgs.push('--glob', includePattern);
  }
  if (isRegexp) {
    ripGrepArgs.push('--regexp', query);
  } else {
    ripGrepArgs.push('--fixed-strings', '--', query);
  }
  ripGrepArgs.push('.');
  return ripGrepArgs;
};

const windowsPathWithLeadingSlashRegex = /^\/[a-zA-Z]:/;
const getFilePathFromUri = uri => {
  const url = new URL(uri);
  const decodedPath = decodeURIComponent(url.pathname);
  if (windowsPathWithLeadingSlashRegex.test(decodedPath)) {
    return decodedPath.slice(1);
  }
  return decodedPath;
};

const getScheme = uriOrPath => {
  if (!uriOrPath.includes('://')) {
    return '';
  }
  return new URL(uriOrPath).protocol.slice(0, -1);
};

const getSearchDir = (workspaceUri, includePattern) => {
  if (!includePattern) {
    return getScheme(workspaceUri) === 'file' ? getFilePathFromUri(workspaceUri) : workspaceUri;
  }
  if (isFileUri(includePattern)) {
    return getFilePathFromUri(includePattern);
  }
  if (isAbsoluteFileSystemPath(includePattern)) {
    return includePattern;
  }
  return getScheme(workspaceUri) === 'file' ? getFilePathFromUri(workspaceUri) : workspaceUri;
};

const executeFileGrepSearch = async (workspaceUri, grepSearchArgs) => {
  const result = await invoke$1('SearchProcess.invoke', 'TextSearch.search', {
    maxSearchResults: grepSearchArgs.maxResults,
    ripGrepArgs: getRipGrepArgs(grepSearchArgs),
    searchDir: getSearchDir(workspaceUri, grepSearchArgs.includePattern)
  });
  const formattedResult = formatSearchProcessResults(result.results, grepSearchArgs.outputFormat);
  return {
    ...(typeof formattedResult === 'string' ? {
      result: formattedResult
    } : formattedResult),
    ...(result.limitHit ? {
      warning: 'Search result limit reached.'
    } : {})
  };
};

const formatLegacyMemorySearchResults = (results, outputFormat) => {
  const matches = [];
  for (const result of results) {
    const [path, resultMatches] = result;
    for (const match of resultMatches) {
      const preview = typeof match?.preview === 'string' ? match.preview : '';
      matches.push(preview ? {
        path,
        text: preview
      } : {
        path,
        text: ''
      });
    }
  }
  if (matches.length === 0) {
    return formatGrepMatches([], outputFormat);
  }
  return formatGrepMatches(matches, outputFormat);
};

const isLegacyMemorySearchResult = value => {
  return Array.isArray(value);
};

const executeMemoryGrepSearch = async (workspaceUri, grepSearchArgs, options) => {
  const searchOptions = {
    exclude: '',
    include: grepSearchArgs.includePattern || '',
    isCaseSensitive: false,
    query: grepSearchArgs.query,
    root: workspaceUri,
    scheme: getScheme(workspaceUri),
    threads: 1,
    useRegularExpression: grepSearchArgs.isRegexp
  };
  try {
    const result = await invoke$1('ExtensionHostTextSearch.textSearchMemory2', searchOptions.scheme, workspaceUri, grepSearchArgs.query, searchOptions, options.assetDir);
    const formattedResult = formatLegacyMemorySearchResults(result.results || [], grepSearchArgs.outputFormat);
    return {
      ...(typeof formattedResult === 'string' ? {
        result: formattedResult
      } : formattedResult),
      ...(result.limitHit ? {
        warning: 'Search result limit reached.'
      } : {})
    };
  } catch {
    const legacyResults = await invoke$1('ExtensionHostTextSearch.textSearchMemory', searchOptions.scheme, workspaceUri, grepSearchArgs.query, searchOptions, options.assetDir);
    const formattedResult = isLegacyMemorySearchResult(legacyResults) ? formatLegacyMemorySearchResults(legacyResults, grepSearchArgs.outputFormat) : formatLegacyMemorySearchResults([], grepSearchArgs.outputFormat);
    return {
      ...(typeof formattedResult === 'string' ? {
        result: formattedResult
      } : formattedResult)
    };
  }
};

const getGrepSearchArgs = args => {
  const {
    includeIgnoredFiles,
    includePattern,
    isRegexp,
    maxResults,
    outputFormat,
    query,
    useDefaultExcludes
  } = args;
  if (typeof query !== 'string' || typeof isRegexp !== 'boolean') {
    return undefined;
  }
  if (includePattern !== undefined && typeof includePattern !== 'string') {
    return undefined;
  }
  if (maxResults !== undefined && typeof maxResults !== 'number') {
    return undefined;
  }
  if (includeIgnoredFiles !== undefined && typeof includeIgnoredFiles !== 'boolean') {
    return undefined;
  }
  if (useDefaultExcludes !== undefined && typeof useDefaultExcludes !== 'boolean') {
    return undefined;
  }
  if (outputFormat !== undefined && outputFormat !== 'xml' && outputFormat !== 'json') {
    return undefined;
  }
  return {
    ...(includeIgnoredFiles === undefined ? {} : {
      includeIgnoredFiles
    }),
    ...(includePattern === undefined ? {} : {
      includePattern
    }),
    ...(maxResults === undefined ? {} : {
      maxResults
    }),
    ...(outputFormat === undefined ? {} : {
      outputFormat
    }),
    isRegexp,
    query,
    useDefaultExcludes: useDefaultExcludes === undefined ? true : useDefaultExcludes
  };
};

const grepSearchArgumentError = 'Invalid argument: grep_search requires query (string), isRegexp (boolean), optional includePattern (string), optional maxResults (number), optional includeIgnoredFiles (boolean), optional useDefaultExcludes (boolean), and optional outputFormat ("xml" | "json").';

const executeGrepSearchTool = async (args, options) => {
  const grepSearchArgs = getGrepSearchArgs(args);
  if (!grepSearchArgs) {
    return {
      error: grepSearchArgumentError
    };
  }
  try {
    const workspaceUri = await getWorkspacePath();
    const scheme = getScheme(workspaceUri);
    if (scheme === '' || scheme === 'file') {
      return executeFileGrepSearch(workspaceUri, grepSearchArgs);
    }
    return executeMemoryGrepSearch(workspaceUri, grepSearchArgs, options);
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      arguments: grepSearchArgs
    };
  }
};

const getEntryType = type => {
  switch (type) {
    case Directory:
      return 'folder';
    case File:
      return 'file';
    case Symlink:
      return 'symlink';
    default:
      return 'unknown';
  }
};
const mapEntry = entry => ({
  name: entry.name,
  type: getEntryType(entry.type)
});
const executeListFilesTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  if (uri === 'file:///workspace' || uri.startsWith('file:///workspace/')) {
    return {
      error: 'Invalid argument: uri must be a real workspace folder URI. Call getWorkspaceUri first and use the returned workspaceUri value.'
    };
  }
  try {
    const entries = await invoke$1('FileSystem.readDirWithFileTypes', uri);
    return {
      entries: entries.map(mapEntry)
    };
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

const executeOpenEditorTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    await invoke$1('Main.openUri', uri);
    return {
      ok: true,
      uri
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      uri
    };
  }
};

const executeOpenPreviewTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    await invoke$1('Preview.open', uri);
    return {
      ok: true,
      uri
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      uri
    };
  }
};

const executeReadFileTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    const content = await readFile(uri);
    return {
      content
    };
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

const executeRenameTool = async (args, _options) => {
  const oldUri = typeof args.oldUri === 'string' ? args.oldUri : '';
  const newUri = typeof args.newUri === 'string' ? args.newUri : '';
  if (!oldUri || !isAbsoluteUri(oldUri)) {
    return getInvalidUriErrorPayload('oldUri');
  }
  if (!newUri || !isAbsoluteUri(newUri)) {
    return getInvalidUriErrorPayload('newUri');
  }
  if (!URL.canParse(oldUri) || !URL.canParse(newUri)) {
    return getInvalidUrlErrorPayload();
  }
  const oldUrl = new URL(oldUri);
  const newUrl = new URL(newUri);
  try {
    await invoke$1('FileSystem.rename', oldUrl.toString(), newUrl.toString());
    return {
      newUri: newUrl.toString(),
      ok: true,
      oldUri: oldUrl.toString()
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      newUri: newUrl.toString(),
      oldUri: oldUrl.toString()
    };
  }
};

const maxPayloadLength = 40_000;
const executeRenderHtmlTool = async (args, _options) => {
  const html = typeof args.html === 'string' ? args.html : '';
  const css = typeof args.css === 'string' ? args.css : '';
  const title = typeof args.title === 'string' ? args.title : '';
  if (!html) {
    return {
      error: 'Missing required argument: html'
    };
  }
  if (html.length > maxPayloadLength || css.length > maxPayloadLength) {
    return {
      error: 'Payload too large: keep html/css under 40,000 characters each.'
    };
  }
  return {
    css,
    html,
    ok: true,
    title
  };
};

const getRgArgs = args => {
  const {
    '-n': lineNumbers,
    output_mode,
    path,
    pattern
  } = args;
  if (typeof pattern !== 'string') {
    return undefined;
  }
  if (path !== undefined && typeof path !== 'string') {
    return undefined;
  }
  if (output_mode !== undefined && output_mode !== 'content' && output_mode !== 'files_with_matches' && output_mode !== 'count') {
    return undefined;
  }
  if (lineNumbers !== undefined && typeof lineNumbers !== 'boolean') {
    return undefined;
  }
  return {
    ...(lineNumbers === undefined ? {} : {
      '-n': lineNumbers
    }),
    ...(output_mode === undefined ? {} : {
      output_mode
    }),
    ...(path === undefined ? {} : {
      path
    }),
    pattern
  };
};
const executeRgTool = async (args, _options) => {
  const rgArgs = getRgArgs(args);
  if (!rgArgs) {
    return {
      error: 'Invalid argument: rg requires pattern (string), optional path (string), optional output_mode ("content" | "files_with_matches" | "count"), and optional -n (boolean).'
    };
  }
  return {
    arguments: rgArgs,
    result: 'No matches found.'
  };
};

const getRunInTerminalOptions = args => {
  const {
    options
  } = args;
  if (!options || typeof options !== 'object') {
    return undefined;
  }
  const candidate = options;
  const {
    command,
    explanation,
    goal,
    shell
  } = candidate;
  if (typeof command !== 'string' || typeof explanation !== 'string' || typeof goal !== 'string' || typeof shell !== 'string') {
    return undefined;
  }
  return {
    command,
    explanation,
    goal,
    shell
  };
};
const executeRunInTerminalTool = async (args, _options) => {
  const runInTerminalOptions = getRunInTerminalOptions(args);
  if (!runInTerminalOptions) {
    return {
      error: 'Invalid argument: options must include shell (string), command (string), explanation (string), and goal (string).'
    };
  }
  try {
    const workspaceUri = await getWorkspacePath();
    const result = await invoke('Terminal.executeShellCommand', {
      args: ['-c', runInTerminalOptions.command],
      cwd: workspaceUri,
      toSpawn: runInTerminalOptions.shell
    });
    return result;
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

const getSearchOptions = args => {
  const {
    options
  } = args;
  if (!options || typeof options !== 'object') {
    return undefined;
  }
  const candidate = options;
  const {
    exclude,
    isRegex,
    machWholeWord,
    matchCase,
    value
  } = candidate;
  if (typeof value !== 'string' || typeof isRegex !== 'boolean' || typeof matchCase !== 'boolean' || typeof machWholeWord !== 'boolean') {
    return undefined;
  }
  if (!Array.isArray(exclude) || exclude.some(item => typeof item !== 'string')) {
    return undefined;
  }
  return {
    exclude,
    isRegex,
    machWholeWord,
    matchCase,
    value
  };
};
const executeSearchTextTool = async (args, _options) => {
  const searchOptions = getSearchOptions(args);
  if (!searchOptions) {
    return {
      error: 'Invalid argument: options must include value (string), isRegex (boolean), matchCase (boolean), machWholeWord (boolean), and exclude (string[]).'
    };
  }
  const results = [{
    column: 12,
    line: 5,
    text: `Mock match for "${searchOptions.value}" in src/main.ts`,
    uri: 'file:///workspace/src/main.ts'
  }, {
    column: 3,
    line: 18,
    text: `Mock match for "${searchOptions.value}" in src/utils/search.ts`,
    uri: 'file:///workspace/src/utils/search.ts'
  }];
  return {
    options: searchOptions,
    results
  };
};

const placeholderResponse = 'Hello From Sub agent - not yet implemented';
const executeSpawnSubagentTool = async (args, _options) => {
  const prompt = typeof args.prompt === 'string' ? args.prompt : '';
  if (!prompt) {
    return {
      error: 'Missing required argument: prompt'
    };
  }
  return {
    ok: true,
    prompt,
    response: placeholderResponse
  };
};

const todoDbName = 'chat-tool-worker';
const todoStoreName = 'state';
const todoKey = 'todoList';
const todoCacheName = 'chat-tool-worker-todo';
const todoCacheRequest = new Request('https://chat-tool-worker.local/todo-list');
let memoryTodoList = '';
const setTodosInIndexedDb = async todos => {
  const db = await new Promise((resolve, reject) => {
    const openRequest = indexedDB.open(todoDbName, 1);
    openRequest.onupgradeneeded = () => {
      const nextDb = openRequest.result;
      if (!nextDb.objectStoreNames.contains(todoStoreName)) {
        nextDb.createObjectStore(todoStoreName);
      }
    };
    openRequest.onsuccess = () => {
      resolve(openRequest.result);
    };
    openRequest.onerror = () => {
      reject(openRequest.error ?? new Error('Failed to open IndexedDB'));
    };
  });
  await new Promise((resolve, reject) => {
    const transaction = db.transaction(todoStoreName, 'readwrite');
    transaction.objectStore(todoStoreName).put(todos, todoKey);
    transaction.oncomplete = () => {
      db.close();
      resolve();
    };
    transaction.onerror = () => {
      db.close();
      reject(transaction.error ?? new Error('Failed to persist todo list'));
    };
    transaction.onabort = () => {
      db.close();
      reject(transaction.error ?? new Error('Failed to persist todo list'));
    };
  });
};
const setTodosInCacheStorage = async todos => {
  const cache = await caches.open(todoCacheName);
  const payload = JSON.stringify({
    todos
  });
  await cache.put(todoCacheRequest, new Response(payload, {
    headers: {
      'content-type': 'application/json'
    }
  }));
};
const executeUpdateTodoTool = async (args, _options) => {
  const todos = typeof args.todos === 'string' ? args.todos : '';
  if (!todos) {
    return {
      error: 'Missing required argument: todos'
    };
  }
  try {
    if (typeof indexedDB !== 'undefined') {
      await setTodosInIndexedDb(todos);
      return {
        message: 'TODO list updated',
        ok: true,
        storage: 'indexeddb',
        todos
      };
    }
    if (typeof caches !== 'undefined') {
      await setTodosInCacheStorage(todos);
      return {
        message: 'TODO list updated',
        ok: true,
        storage: 'cache',
        todos
      };
    }
    const previousTodos = memoryTodoList;
    memoryTodoList = todos;
    return {
      message: 'TODO list updated',
      ok: true,
      previousTodos,
      storage: 'memory',
      todos
    };
  } catch (error) {
    return getToolErrorPayload(error);
  }
};

const carriageReturnNewLineRegex = /\r\n/g;
const toLines = content => {
  if (content === '') {
    return [];
  }
  const normalizedContent = content.replaceAll(carriageReturnNewLineRegex, '\n');
  const lines = normalizedContent.split('\n');
  if (lines.at(-1) === '') {
    lines.pop();
  }
  return lines;
};
const getLongestCommonSubsequenceLength = (beforeLines, afterLines) => {
  if (beforeLines.length === 0 || afterLines.length === 0) {
    return 0;
  }
  const outerLines = beforeLines.length >= afterLines.length ? beforeLines : afterLines;
  const innerLines = beforeLines.length >= afterLines.length ? afterLines : beforeLines;
  let previousRow = new Uint32Array(innerLines.length + 1);
  for (let i = 1; i <= outerLines.length; i++) {
    const currentRow = new Uint32Array(innerLines.length + 1);
    const outerLine = outerLines[i - 1];
    for (let j = 1; j <= innerLines.length; j++) {
      if (outerLine === innerLines[j - 1]) {
        currentRow[j] = previousRow[j - 1] + 1;
      } else {
        currentRow[j] = Math.max(previousRow[j], currentRow[j - 1]);
      }
    }
    previousRow = currentRow;
  }
  return previousRow[innerLines.length];
};
const getLineDiffStats = (beforeContent, afterContent) => {
  const beforeLines = toLines(beforeContent);
  const afterLines = toLines(afterContent);
  const longestCommonSubsequenceLength = getLongestCommonSubsequenceLength(beforeLines, afterLines);
  return {
    addedLines: afterLines.length - longestCommonSubsequenceLength,
    removedLines: beforeLines.length - longestCommonSubsequenceLength
  };
};

const executeWriteFileTool = async (args, _options) => {
  const uri = typeof args.uri === 'string' ? args.uri : '';
  const content = typeof args.content === 'string' ? args.content : '';
  if (!uri || !isAbsoluteUri(uri)) {
    return getInvalidUriErrorPayload('uri');
  }
  try {
    new URL(uri);
  } catch {
    return getInvalidUrlErrorPayload();
  }
  try {
    const exists$1 = await exists(uri);
    const previousContent = exists$1 ? await readFile$1(uri) : '';
    const {
      addedLines,
      removedLines
    } = getLineDiffStats(previousContent, content);
    await writeFile$1(uri, content);
    return {
      addedLines,
      ok: true,
      removedLines,
      uri
    };
  } catch (error) {
    return {
      ...getToolErrorPayload(error),
      uri
    };
  }
};

const parseToolArguments = rawArguments => {
  if (typeof rawArguments !== 'string') {
    return {};
  }
  try {
    const parsed = JSON.parse(rawArguments);
    if (!parsed || typeof parsed !== 'object') {
      return {};
    }
    return parsed;
  } catch {
    return {};
  }
};

const executeChatTool = async (name, rawArguments, options) => {
  const args = parseToolArguments(rawArguments);
  switch (name) {
    case 'close_preview':
      return executeClosePreviewTool();
    case 'create_directory':
      return executeCreateDirectoryTool(args);
    case 'edit_file':
      return executeEditFileTool(args);
    case 'getWorkspaceUri':
      return executeGetWorkspaceUriTool();
    case 'glob':
      return executeGlobTool(args);
    case 'grep_search':
      return executeGrepSearchTool(args, options);
    case 'list_files':
      return executeListFilesTool(args);
    case 'open_preview':
      return executeOpenPreviewTool(args);
    case 'openEditor':
      return executeOpenEditorTool(args);
    case 'read_file':
      return executeReadFileTool(args);
    case 'rename':
      return executeRenameTool(args);
    case 'render_html':
      return executeRenderHtmlTool(args);
    case 'rg':
      return executeRgTool(args);
    case 'run_in_terminal':
      return executeRunInTerminalTool(args);
    case 'search_text':
      return executeSearchTextTool(args);
    case 'spawn_subagent':
      return executeSpawnSubagentTool(args);
    case 'update_todo':
      return executeUpdateTodoTool(args);
    case 'write_file':
      return executeWriteFileTool(args);
    default:
      return {
        error: `Unknown tool: ${name}`
      };
  }
};

const getClosePreviewTool = () => {
  return {
    function: {
      description: 'Close the right-side preview if it is currently open.',
      name: 'close_preview',
      parameters: {
        additionalProperties: false,
        properties: {},
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getCreateDirectoryTool = () => {
  return {
    function: {
      description: 'Create a new directory at the given absolute URI (for example `file://...`, `memfs://...`, or extension-provided file system URIs). Do not pass a relative path.',
      name: 'create_directory',
      parameters: {
        additionalProperties: false,
        properties: {
          uri: {
            description: 'Absolute URI for the target directory (for example `file://...`, `memfs://...`, or extension-provided file system URIs). Relative paths are not allowed.',
            type: 'string'
          }
        },
        required: ['uri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getEditFileTool = () => {
  return {
    function: {
      description: 'Apply a targeted text edit to an existing file by character offsets. This reads the current file, applies the edit, and writes the updated result. Use this for small changes instead of rewriting the full file.',
      name: 'edit_file',
      parameters: {
        additionalProperties: false,
        properties: {
          end: {
            description: 'Zero-based end character offset (exclusive) in the current file content.',
            type: 'number'
          },
          start: {
            description: 'Zero-based start character offset (inclusive) in the current file content.',
            type: 'number'
          },
          text: {
            description: 'Replacement text inserted at the range [start, end).',
            type: 'string'
          },
          uri: {
            description: 'Absolute URI for the target file (for example `file://...`, `memfs://...`, or extension-provided file system URIs). Relative paths are not allowed.',
            type: 'string'
          }
        },
        required: ['uri', 'start', 'end', 'text'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getGetWorkspaceUriTool = () => {
  return {
    function: {
      description: 'Get the URI of the currently open workspace folder. Call this first before using list_files, read_file, write_file, edit_file, open_preview, or openEditor when you do not already have a concrete workspace URI.',
      name: 'getWorkspaceUri',
      parameters: {
        additionalProperties: false,
        properties: {},
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getGlobTool = () => {
  return {
    function: {
      description: 'Find files by glob pattern under a specific workspace folder URI and return matching relative paths. If you do not already have a real workspace URI, call getWorkspaceUri first and then pass that returned workspaceUri as baseUri.',
      name: 'glob',
      parameters: {
        additionalProperties: false,
        properties: {
          baseUri: {
            description: 'Absolute folder URI for the workspace root or subfolder where the glob search should start. If unknown, call getWorkspaceUri first and pass the returned workspaceUri value.',
            type: 'string'
          },
          pattern: {
            description: 'Glob pattern to match files, for example `packages/e2e/src/*.ts`.',
            type: 'string'
          }
        },
        required: ['baseUri', 'pattern'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getGrepSearchTool = () => {
  return {
    function: {
      description: "Do a fast text search in the workspace. Use this tool when you want to search with an exact string or regex. If you are not sure what words will appear in the workspace, prefer using regex patterns with alternation (|) or character classes to search for multiple potential words at once instead of making separate searches. For example, use 'function|method|procedure' to look for all of those words at once. Use includePattern to search within files matching a specific pattern, or in a specific file, using a relative path. Use 'includeIgnoredFiles' to include files normally ignored by .gitignore, other ignore files and `files.exclude` and `search.exclude` settings. Warning: using this may cause the search to be slower, only set it when you want to search in ignored folders like node_modules or build outputs. By default, grep_search also excludes node_modules and .git via ripgrep globs; set useDefaultExcludes to false if you need to search those directories. Use this tool when you want to see an overview of a particular file, instead of using read_file many times to look for code within a file.\n\nIn a multi-root workspace, you can scope the search to a specific workspace folder by using the absolute path to the folder as the includePattern, e.g. /path/to/folder.",
      name: 'grep_search',
      parameters: {
        additionalProperties: false,
        properties: {
          includeIgnoredFiles: {
            description: 'Whether to include files that would normally be ignored according to .gitignore, other ignore files and `files.exclude` and `search.exclude` settings. Warning: using this may cause the search to be slower. Only set it when you want to search in ignored folders like node_modules or build outputs.',
            type: 'boolean'
          },
          includePattern: {
            description: 'Search files matching this glob pattern. Will be applied to the relative path of files within the workspace. To search recursively inside a folder, use a proper glob pattern like "src/folder/**". Do not use | in includePattern. Can also be an absolute path to a workspace folder to scope the search in a multi-root workspace.',
            type: 'string'
          },
          isRegexp: {
            description: 'Whether the pattern is a regex.',
            type: 'boolean'
          },
          maxResults: {
            description: "The maximum number of results to return. Do not use this unless necessary, it can slow things down. By default, only some matches are returned. If you use this and don't see what you're looking for, you can try again with a more specific query or a larger maxResults.",
            type: 'number'
          },
          outputFormat: {
            description: 'Optional structured output format. Use "xml" for match tags or "json" for machine-readable JSON. When omitted, grep_search returns plain text lines.',
            enum: ['xml', 'json'],
            type: 'string'
          },
          query: {
            description: "The pattern to search for in files in the workspace. Use regex with alternation (e.g., 'word1|word2|word3') or character classes to find multiple potential words in a single search. Be sure to set the isRegexp property properly to declare whether it's a regex or plain text pattern. Is case-insensitive.",
            type: 'string'
          },
          useDefaultExcludes: {
            description: 'Whether to exclude node_modules and .git with built-in ripgrep globs. Defaults to true. Set to false when you explicitly need to search those directories.',
            type: 'boolean'
          }
        },
        required: ['query', 'isRegexp'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getListFilesTool = () => {
  return {
    function: {
      description: 'List direct children (files and folders) for a folder URI inside the currently open workspace folder. If you do not already have a real workspace URI, call getWorkspaceUri first and then use that returned URI. Do not use placeholder URIs like file:///workspace.',
      name: 'list_files',
      parameters: {
        additionalProperties: false,
        properties: {
          uri: {
            description: 'Absolute folder URI for a real path inside the currently open workspace folder. If unknown, call getWorkspaceUri first and pass the returned workspaceUri value. Do not use placeholder URIs.',
            type: 'string'
          }
        },
        required: ['uri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getOpenEditorTool = () => {
  return {
    function: {
      description: 'Open a file URI in the editor.',
      name: 'openEditor',
      parameters: {
        additionalProperties: false,
        properties: {
          uri: {
            description: 'Absolute file URI for a real path inside the currently open workspace folder. Do not use placeholder URIs.',
            type: 'string'
          }
        },
        required: ['uri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getOpenPreviewTool = () => {
  return {
    function: {
      description: 'Open the right-side preview for an HTML file URI inside the currently open workspace folder.',
      name: 'open_preview',
      parameters: {
        additionalProperties: false,
        properties: {
          uri: {
            description: 'Absolute HTML file URI for a real path inside the currently open workspace folder. Do not use placeholder URIs.',
            type: 'string'
          }
        },
        required: ['uri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getReadFileTool = () => {
  return {
    function: {
      description: 'Read UTF-8 text content from a file inside the currently open workspace folder. Only pass an absolute URI.',
      name: 'read_file',
      parameters: {
        additionalProperties: false,
        properties: {
          uri: {
            description: 'Absolute file URI for a real path inside the currently open workspace folder. Do not use placeholder URIs.',
            type: 'string'
          }
        },
        required: ['uri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getRenameTool = () => {
  return {
    function: {
      description: 'Rename or move a file or folder from one absolute URI to another absolute URI (for example `file://...`, `memfs://...`, or extension-provided file system URIs).',
      name: 'rename',
      parameters: {
        additionalProperties: false,
        properties: {
          newUri: {
            description: 'Absolute target URI for the file or folder after renaming.',
            type: 'string'
          },
          oldUri: {
            description: 'Absolute source URI for the existing file or folder to rename.',
            type: 'string'
          }
        },
        required: ['oldUri', 'newUri'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getRenderHtmlTool = () => {
  return {
    function: {
      description: 'Render custom HTML and optional CSS directly in the chat tool call list using native chat UI rendering. Use this for structured cards, tables, and small dashboards. After calling this tool, do not repeat the same HTML, data table, or long content again as plain text unless the user explicitly asks for a text-only version.',
      name: 'render_html',
      parameters: {
        additionalProperties: false,
        properties: {
          css: {
            description: 'Optional CSS string applied inside the preview document.',
            type: 'string'
          },
          html: {
            description: 'HTML string to render in the preview document.',
            type: 'string'
          },
          title: {
            description: 'Optional short title for the preview.',
            type: 'string'
          }
        },
        required: ['html'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getRgTool = () => {
  return {
    function: {
      description: 'Search text or regex in workspace files using ripgrep-style arguments and return matching results.',
      name: 'rg',
      parameters: {
        additionalProperties: false,
        properties: {
          '-n': {
            description: 'When true, include line numbers in the output.',
            type: 'boolean'
          },
          output_mode: {
            description: 'Result format to return.',
            enum: ['content', 'files_with_matches', 'count'],
            type: 'string'
          },
          path: {
            description: 'Optional file or directory path inside the current workspace to scope the search.',
            type: 'string'
          },
          pattern: {
            description: 'Text or regular expression pattern to search for.',
            type: 'string'
          }
        },
        required: ['pattern'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getRunInTerminalTool = () => {
  return {
    function: {
      description: 'Run a shell command in a terminal using the provided shell and command options.',
      name: 'run_in_terminal',
      parameters: {
        additionalProperties: false,
        properties: {
          options: {
            additionalProperties: false,
            properties: {
              command: {
                description: 'The shell command to execute.',
                type: 'string'
              },
              explanation: {
                description: 'Why this terminal command is being run.',
                type: 'string'
              },
              goal: {
                description: 'The higher-level objective this terminal command is meant to achieve.',
                type: 'string'
              },
              shell: {
                description: 'The shell executable that should run the command.',
                type: 'string'
              }
            },
            required: ['shell', 'command', 'explanation', 'goal'],
            type: 'object'
          }
        },
        required: ['options'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getSearchTextTool = () => {
  return {
    function: {
      description: 'Search text in workspace files using query options and return matching results.',
      name: 'search_text',
      parameters: {
        additionalProperties: false,
        properties: {
          options: {
            additionalProperties: false,
            properties: {
              exclude: {
                items: {
                  type: 'string'
                },
                type: 'array'
              },
              isRegex: {
                type: 'boolean'
              },
              machWholeWord: {
                type: 'boolean'
              },
              matchCase: {
                type: 'boolean'
              },
              value: {
                type: 'string'
              }
            },
            required: ['value', 'isRegex', 'matchCase', 'machWholeWord', 'exclude'],
            type: 'object'
          }
        },
        required: ['options'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getSpawnSubagentTool = () => {
  return {
    function: {
      description: 'Spawn a subagent for a focused subtask. For now this tool is a stub and returns a fixed placeholder response while the integration is being built.',
      name: 'spawn_subagent',
      parameters: {
        additionalProperties: false,
        properties: {
          prompt: {
            description: 'Short task prompt to send to the subagent.',
            type: 'string'
          }
        },
        required: ['prompt'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getUpdateTodoTool = () => {
  return {
    function: {
      description: 'Update the active TODO checklist for the current chat session. Pass the full markdown checklist text with one item per line (for example "- [ ] Step one").',
      name: 'update_todo',
      parameters: {
        additionalProperties: false,
        properties: {
          todos: {
            description: 'Complete markdown checklist content to store as the current TODO list state.',
            type: 'string'
          }
        },
        required: ['todos'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getWriteFileTool = () => {
  return {
    function: {
      description: 'Write UTF-8 text content to a file for an absolute URI (for example `file://...`, `memfs://...`, or extension-provided file system URIs). Do not pass a relative path and do not use a `path` argument.',
      name: 'write_file',
      parameters: {
        additionalProperties: false,
        properties: {
          content: {
            description: 'New UTF-8 text content to write to the file.',
            type: 'string'
          },
          uri: {
            description: 'Absolute URI for the target file (for example `file://...`, `memfs://...`, or extension-provided file system URIs). Relative paths are not allowed.',
            type: 'string'
          }
        },
        required: ['uri', 'content'],
        type: 'object'
      }
    },
    type: 'function'
  };
};

const getBasicChatTools = () => {
  return [getReadFileTool(), getWriteFileTool(), getRenameTool(), getEditFileTool(), getListFilesTool(), getGetWorkspaceUriTool(), getRenderHtmlTool(), getOpenPreviewTool(), getOpenEditorTool(), getClosePreviewTool(), getSearchTextTool(), getRgTool(), getGrepSearchTool(), getRunInTerminalTool(), getSpawnSubagentTool(), getCreateDirectoryTool(), getGlobTool(), getUpdateTodoTool()];
};

const handleMessagePort = async (port, isRendererWorker = false) => {
  const rpc = await create$7({
    commandMap: commandMap,
    isMessagePortOpen: true,
    messagePort: port
  });
  if (isRendererWorker) {
    set$1(rpc);
  }
};

const send$2 = async port => {
  await sendMessagePortToTerminalProcess(port, 0);
};
const initializeTerminalProcessElectron = async () => {
  const rpc = await create$5({
    commandMap: commandMap,
    send: send$2
  });
  set(rpc);
};
const initializeTerminalProcessRemote = async () => {
  const rpc = await create$2({
    commandMap: commandMap,
    type: 'terminal-process'
  });
  set(rpc);
};
const initializeTerminalProcess = async platform => {
  if (platform === Electron) {
    return initializeTerminalProcessElectron();
  }
  if (platform === Remote) {
    return initializeTerminalProcessRemote();
  }
};

const initialize = async platform => {
  // TODO
  await initializeTerminalProcess(platform);
};

const commandMap = {
  'ChatTool.execute': executeChatTool,
  'ChatTool.getTools': getBasicChatTools,
  'ChatTool.initialize': initialize,
  'HandleMessagePort.handleMessagePort': handleMessagePort,
  initialize: (_, port) => handleMessagePort(port, true)
};

const send$1 = async port => {
  await sendMessagePortToChatStorageWorker(port);
};
const initializeChatStorageWorker = async () => {
  const rpc = await create$5({
    commandMap: commandMap,
    send: send$1
  });
  set$3(rpc);
};

const send = async port => {
  await sendMessagePortToFileSystemWorker(port, 0);
};
const initializeFileSystemWorker = async () => {
  const rpc = await create$5({
    commandMap: commandMap,
    send: send
  });
  set$2(rpc);
};

const initializeRendererWorker = async () => {
  await create$1({
    commandMap: commandMap
  });
};

const listen = async () => {
  await Promise.all([initializeRendererWorker(), initializeFileSystemWorker(), initializeChatStorageWorker()]);
};

const main = async () => {
  await listen();
};

main();
