Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

19.5 KB
Raw Blame
import { formatIdentifierLabel } from '@/utils/textPresentation';

export const canonicalToolActionURL = (name: string, success: boolean, output: string) => {
  if (!success || (name !== 'pulse_control' && name !== 'pulse_query')) return '';
  try {
    const record = JSON.parse(output);
    const canonical =
      name === 'pulse_control'
        ? record.planned === true
        : record.source === 'canonical_action_audit';
    const id = record.action_id;
    if (!canonical || typeof id !== 'string' || !id || record.plan?.actionId !== id) return '';
    return `/actions?action=${encodeURIComponent(id)}`;
  } catch {
    return '';
  }
};

export const getToolLabel = (name: string) => {
  if (name === 'pulse_control') return 'plan';
  if (name === 'run_command' || name === 'pulse_run_command') return 'cmd';
  if (name === 'fetch_url' || name === 'pulse_fetch_url') return 'fetch';
  if (name === 'get_infrastructure_state' || name === 'pulse_get_infrastructure_state')
    return 'infra';
  if (name === 'get_active_alerts' || name === 'pulse_get_active_alerts') return 'alerts';
  if (name === 'get_metrics_history' || name === 'pulse_get_metrics_history') return 'metrics';
  if (name === 'get_baselines' || name === 'pulse_get_baselines') return 'baselines';
  if (name === 'get_patterns' || name === 'pulse_get_patterns') return 'patterns';
  if (name === 'get_disk_health' || name === 'pulse_get_disk_health') return 'disks';
  if (name === 'get_storage' || name === 'pulse_get_storage') return 'storage';
  if (name === 'pulse_get_storage_config') return 'storage cfg';
  if (name === 'get_resource_details' || name === 'pulse_get_resource_details') return 'resource';
  if (name.includes('finding')) return 'finding';
  return formatIdentifierLabel(name, { stripPrefix: 'pulse_', maxLength: 12 });
};

const normalizedToolName = (name?: string) => (name || '').trim().replace(/^pulse_/, '');

const isPlaceholderToolInputSummary = (summary: string) => {
  const normalized = summary.trim().toLowerCase();
  return !normalized || normalized === 'request' || normalized === 'receiving input';
};

const escapePartialJSONKey = (key: string) => key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

const extractPartialJSONStringField = (rawInput: string, keys: string[]) => {
  const raw = rawInput.trim();
  if (!raw) return '';

  for (const key of keys) {
    const escapedKey = escapePartialJSONKey(key);
    const match = raw.match(new RegExp(`"${escapedKey}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)`));
    if (match?.[1]) {
      return match[1].replace(/\\"/g, '"').replace(/\\\\/g, '\\').trim();
    }
  }
  return '';
};

const stringField = (record: Record<string, unknown>, keys: string[]) => {
  for (const key of keys) {
    const value = record[key];
    if (typeof value === 'string' && value.trim()) {
      return value.trim();
    }
    if (typeof value === 'number' && Number.isFinite(value)) {
      return String(value);
    }
  }
  return '';
};

const booleanField = (record: Record<string, unknown>, key: string) => record[key] === true;

const inlineValue = (value: string, maxLength = 24) =>
  value
    .replace(/["\r\n]+/g, ' ')
    .trim()
    .substring(0, maxLength);

const targetSuffix = (record: Record<string, unknown>) => {
  const target = stringField(record, ['target_host', 'targetHost', 'resource_id', 'resourceId']);
  if (!target) return '';
  return ` on ${formatIdentifierLabel(target, { maxLength: 18 })}`;
};

const normalizedShellCommand = (command: string) => command.replace(/\s+/g, ' ').trim();

const redactShellCommandPreview = (command: string) =>
  command
    .replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, '[redacted-secret]')
    .replace(/(Authorization:\s*Bearer\s+)([^"'\s]+)/gi, '$1[redacted-secret]')
    .replace(/(Bearer\s+)([A-Za-z0-9._~+/=-]{8,})/gi, '$1[redacted-secret]')
    .replace(
      /(--(?:api-?key|access-token|token|password|secret)(?:=|\s+))("[^"]*"|'[^']*'|[^\s]+)/gi,
      '$1[redacted-secret]',
    )
    .replace(
      /\b([A-Z0-9_]*(?:API_?KEY|ACCESS_?TOKEN|TOKEN|PASSWORD|SECRET)[A-Z0-9_]*=)("[^"]*"|'[^']*'|[^\s]+)/g,
      '$1[redacted-secret]',
    )
    .replace(
      /\b((?:api[_-]?key|apikey|access[_-]?token|token|password|secret)=)([^\s&]+)/gi,
      '$1[redacted-secret]',
    );

const commandPreviewValue = (command: string, maxLength = 140) => {
  const redacted = redactShellCommandPreview(normalizedShellCommand(command));
  if (!redacted) return '';
  if (redacted.length <= maxLength) return redacted;
  return `${redacted.slice(0, maxLength).trimEnd()}...`;
};

const formatShellCommandPreview = (command: string) => {
  const preview = commandPreviewValue(command);
  return preview ? `$ ${preview}` : '';
};

const shellCommandIntentLabel = (command: string) => {
  const normalized = normalizedShellCommand(command).toLowerCase();
  if (!normalized) return '';

  if (/lsblk|udevadm|lspci|lsusb|\/dev|nvme\s+list|blkid/.test(normalized)) {
    return 'Inspect devices';
  }
  if (/smartctl|nvme\s+smart-log|storcli|megacli/.test(normalized)) {
    return 'Check disk health';
  }
  if (/\bdf\b|findmnt|mount\s|ls\s+\/mnt|ls\s+\/media/.test(normalized)) {
    return 'Inspect filesystems';
  }
  if (/\bzpool\b|\bzfs\b/.test(normalized)) {
    return 'Inspect ZFS storage';
  }
  if (
    /journalctl|docker\s+logs|kubectl\s+logs|tail\s+-f\s+\/var\/log|\/var\/log/.test(normalized)
  ) {
    return 'Read logs';
  }
  if (/systemctl\s+(status|is-active|show)|service\s+\S+\s+status/.test(normalized)) {
    return 'Check service status';
  }
  if (/docker\s+(ps|inspect|stats)|podman\s+(ps|inspect|stats)/.test(normalized)) {
    return 'Inspect containers';
  }
  if (/kubectl\s+(get|describe|top)|helm\s+(list|status)/.test(normalized)) {
    return 'Inspect Kubernetes resources';
  }
  if (/\b(qm|pct)\s+(list|status|config|pending)|pvesh\s+get|pvesm\s+status/.test(normalized)) {
    return 'Inspect Proxmox resources';
  }
  if (/\b(ip|ss|netstat|ping|traceroute|curl|wget|dig|nslookup)\b/.test(normalized)) {
    return 'Check network state';
  }
  return '';
};

const formatCommandActivitySummary = (record: Record<string, unknown>, mode: 'read' | 'write') => {
  const command = normalizedShellCommand(stringField(record, ['command', 'cmd']));
  if (!command) return '';

  const target = targetSuffix(record);
  const intent = shellCommandIntentLabel(command);
  if (mode === 'write') {
    return `Run command${target}`;
  }
  if (mode === 'read' && intent) {
    return `${intent}${target}`;
  }
  return `Run read-only command${target}`;
};

const parseFunctionStyleToolInput = (input: string, options?: { allowPartial?: boolean }) => {
  const trimmed = input.trim();
  const allowPartial = options?.allowPartial === true;
  const match = (
    allowPartial
      ? /^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([\s\S]*)$/
      : /^([a-zA-Z_][a-zA-Z0-9_]*)\s*\(([\s\S]*)\)\s*$/
  ).exec(trimmed);
  if (!match) return null;

  const args: Record<string, unknown> = {};
  let body = match[2] || '';
  const rightTrimmed = body.trimEnd();
  if (allowPartial && rightTrimmed.endsWith(')')) {
    body = rightTrimmed.slice(0, -1);
  }
  let index = 0;

  const partialResult = () =>
    allowPartial && Object.keys(args).length > 0 ? { name: match[1], args } : null;

  const skipWhitespace = () => {
    while (index < body.length && /\s/.test(body[index])) index += 1;
  };

  const parseQuotedValue = (quote: string) => {
    index += 1;
    let value = '';
    while (index < body.length) {
      const char = body[index];
      if (char === '\\') {
        if (index + 1 < body.length) {
          value += body[index + 1];
          index += 2;
          continue;
        }
        if (allowPartial) {
          index += 1;
          break;
        }
        return null;
      }
      if (char === quote) {
        index += 1;
        return value;
      }
      value += char;
      index += 1;
    }
    return allowPartial ? value : null;
  };

  while (index < body.length) {
    skipWhitespace();
    if (index >= body.length) break;

    if (body[index] === ',') {
      index += 1;
      continue;
    }

    const keyMatch = /^[a-zA-Z_][a-zA-Z0-9_]*/.exec(body.slice(index));
    if (!keyMatch) return partialResult();
    const key = keyMatch[0];
    index += key.length;

    skipWhitespace();
    if (body[index] !== '=') return partialResult();
    index += 1;
    skipWhitespace();
    if (index >= body.length) return partialResult();

    const quote = body[index];
    let value: unknown;
    if (quote === '"' || quote === "'") {
      value = parseQuotedValue(quote);
      if (value === null) return null;
    } else {
      const start = index;
      while (
        index < body.length &&
        body[index] !== ',' &&
        (allowPartial ? body[index] !== ')' : true)
      ) {
        index += 1;
      }
      const rawValue = body.slice(start, index).trim();
      if (!rawValue) return partialResult();
      if (rawValue === 'true') value = true;
      else if (rawValue === 'false') value = false;
      else if (rawValue === 'null') value = null;
      else if (/^-?\d+(?:\.\d+)?$/.test(rawValue)) value = Number(rawValue);
      else value = rawValue;
    }

    args[key] = value;
    skipWhitespace();
    if (body[index] === ',') {
      index += 1;
      continue;
    }
    if (allowPartial && body[index] === ')') break;
    if (index < body.length) {
      return partialResult();
    }
  }

  if (allowPartial && Object.keys(args).length === 0) return null;
  return { name: match[1], args };
};

const parseStructuredInputRecord = (input: string) => {
  const trimmed = input.trim();
  if (!trimmed) return null;

  try {
    const parsed = JSON.parse(trimmed) as unknown;
    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
      return { record: parsed as Record<string, unknown> };
    }
  } catch {
    // Keep trying provider-style function-call input below.
  }

  const functionCall = parseFunctionStyleToolInput(trimmed);
  if (functionCall) {
    return { name: functionCall.name, record: functionCall.args };
  }

  const partialFunctionCall = parseFunctionStyleToolInput(trimmed, { allowPartial: true });
  if (partialFunctionCall) {
    return { name: partialFunctionCall.name, record: partialFunctionCall.args };
  }

  return null;
};

const formatPartialRawInputSummary = (rawInput: string | undefined, toolName?: string) => {
  if (!rawInput?.trim()) return '';

  const action = extractPartialJSONStringField(rawInput, ['action', 'type']).toLowerCase();
  const command = extractPartialJSONStringField(rawInput, ['command', 'cmd']);
  const path = extractPartialJSONStringField(rawInput, ['path', 'file', 'file_path', 'filePath']);
  const pattern = extractPartialJSONStringField(rawInput, [
    'pattern',
    'grep',
    'grep_pattern',
    'grepPattern',
  ]);
  const query = extractPartialJSONStringField(rawInput, [
    'query',
    'search',
    'name',
    'resource_name',
  ]);
  const target = extractPartialJSONStringField(rawInput, [
    'target_host',
    'targetHost',
    'resource_id',
    'resourceId',
  ]);
  const record: Record<string, unknown> = {
    ...(action ? { action } : {}),
    ...(command ? { command } : {}),
    ...(path ? { path } : {}),
    ...(pattern ? { pattern } : {}),
    ...(query ? { query } : {}),
    ...(target ? { target_host: target } : {}),
  };
  const tool = normalizedToolName(toolName);

  if ((tool === 'read' || tool === 'run_command' || tool === 'control') && command) {
    const mode = tool === 'run_command' || tool === 'control' ? 'write' : 'read';
    return formatCommandActivitySummary(record, mode);
  }
  if (tool === 'read') {
    if (action === 'file' && path) return `read ${inlineValue(path, 36)}${targetSuffix(record)}`;
    if (action === 'tail' && path) return `tail ${inlineValue(path, 36)}${targetSuffix(record)}`;
    if (action === 'find' && pattern)
      return `find "${inlineValue(pattern, 28)}"${targetSuffix(record)}`;
    if (action === 'logs') return `read logs${targetSuffix(record)}`;
  }
  if (tool === 'query') {
    if (action === 'search' && query) return `search "${inlineValue(query, 28)}"`;
    if (action === 'list') return 'list resources';
    if (action) return formatIdentifierLabel(action, { maxLength: 28 });
  }
  if (action) return formatIdentifierLabel(action, { maxLength: 28 });
  return 'receiving input';
};

const formatPulseReadInputSummary = (record: Record<string, unknown>) => {
  const action = stringField(record, ['action', 'type']).toLowerCase();
  const path = inlineValue(stringField(record, ['path', 'file', 'file_path', 'filePath']), 36);
  const pattern = inlineValue(
    stringField(record, ['pattern', 'grep', 'grep_pattern', 'grepPattern']),
    28,
  );
  const container = inlineValue(stringField(record, ['container', 'service', 'unit']), 24);
  const source = stringField(record, ['source']).toLowerCase();

  if (action === 'exec') {
    return (
      formatCommandActivitySummary(record, 'read') || `run read-only command${targetSuffix(record)}`
    );
  }
  if (action === 'file') {
    return path ? `read ${path}${targetSuffix(record)}` : `read file${targetSuffix(record)}`;
  }
  if (action === 'tail') {
    return path ? `tail ${path}${targetSuffix(record)}` : `tail file${targetSuffix(record)}`;
  }
  if (action === 'find') {
    if (pattern && path) return `find "${pattern}" in ${path}${targetSuffix(record)}`;
    return pattern
      ? `find "${pattern}"${targetSuffix(record)}`
      : `find files${targetSuffix(record)}`;
  }
  if (action === 'logs') {
    if (container) return `logs ${container}${targetSuffix(record)}`;
    return source
      ? `${formatIdentifierLabel(source, { maxLength: 18 })} logs${targetSuffix(record)}`
      : `read logs${targetSuffix(record)}`;
  }
  return (
    formatCommandActivitySummary(record, 'read') ||
    (action ? formatIdentifierLabel(action, { maxLength: 28 }) : '')
  );
};

const formatQueryInputSummary = (record: Record<string, unknown>) => {
  const action = stringField(record, ['action', 'type']).toLowerCase();
  const resourceType = stringField(record, ['resource_type', 'resourceType', 'kind', 'include']);
  const listType = stringField(record, ['type', 'resource_type', 'resourceType', 'kind']);
  const query = inlineValue(stringField(record, ['query', 'search', 'name', 'resource_name']));
  const resourceId = inlineValue(stringField(record, ['resource_id', 'resourceId', 'id', 'vmid']));
  const node = inlineValue(stringField(record, ['node', 'host']));

  switch (action) {
    case 'action':
      return 'read recorded action outcome';
    case 'search':
      return query ? `search "${query}"` : 'search resources';
    case 'list':
      return listType
        ? `list ${formatIdentifierLabel(listType, { maxLength: 22 })}`
        : 'list resources';
    case 'get':
      return resourceId ? `get ${resourceId}` : 'get resource';
    case 'config':
      if (resourceId && node) return `config ${resourceId} on ${node}`;
      return resourceId ? `config ${resourceId}` : 'resource config';
    case 'topology':
      return booleanField(record, 'summary_only') ? 'topology summary' : 'topology';
    case 'health':
      return 'health summary';
    default:
      if (action) return formatIdentifierLabel(action, { maxLength: 28 });
      return resourceType
        ? `query ${formatIdentifierLabel(resourceType, { maxLength: 22 })}`
        : 'query resources';
  }
};

const formatAlertsInputSummary = (record: Record<string, unknown>) => {
  const action = stringField(record, ['action']).toLowerCase();
  const severity = stringField(record, ['severity', 'level']);
  const resource = stringField(record, ['resource', 'resource_id', 'resourceId', 'name']);

  if (action === 'list') {
    return severity
      ? `list ${formatIdentifierLabel(severity, { maxLength: 18 })} alerts`
      : 'list active alerts';
  }
  if (action === 'get') {
    return resource ? `get alert for ${inlineValue(resource, 18)}` : 'get alert';
  }
  return action ? formatIdentifierLabel(action, { maxLength: 28 }) : 'read alerts';
};

const formatStructuredInputSummary = (
  record: Record<string, unknown>,
  toolName?: string,
  rawInput?: string,
) => {
  if (Object.keys(record).length === 0) {
    return formatPartialRawInputSummary(rawInput, toolName) || 'request';
  }

  const tool = normalizedToolName(toolName);
  if (tool === 'control' && record.type === 'resource') {
    const action = stringField(record, ['action']);
    return `${action ? `Plan ${formatIdentifierLabel(action)}` : 'Plan action'}${targetSuffix(record)}`;
  }
  if (tool === 'read') {
    return formatPulseReadInputSummary(record) || 'read resource';
  }
  if (tool === 'run_command' || tool === 'control') {
    return formatCommandActivitySummary(record, 'write') || 'run command';
  }
  if (tool === 'query') {
    return formatQueryInputSummary(record);
  }
  if (tool === 'alerts') {
    return formatAlertsInputSummary(record);
  }
  if (typeof record.action === 'string' && record.action.trim()) {
    return formatIdentifierLabel(record.action, { maxLength: 28 });
  }
  if (typeof record.command === 'string' && record.command.trim()) {
    return formatIdentifierLabel(record.command, { maxLength: 28 });
  }
  return 'request';
};

const parseStructuredInputSummary = (input: string, toolName?: string, rawInput?: string) => {
  const parsed = parseStructuredInputRecord(input);
  if (!parsed) return null;
  return formatStructuredInputSummary(parsed.record, parsed.name || toolName, rawInput);
};

export const parseToolInputSummary = (input: string, toolName?: string, rawInput?: string) => {
  const trimmed = input.trim();
  if (!trimmed) return '';

  const directSummary = parseStructuredInputSummary(trimmed, toolName, rawInput);
  if (directSummary && !isPlaceholderToolInputSummary(directSummary)) {
    return directSummary;
  }

  if (rawInput && rawInput.trim() && rawInput.trim() !== trimmed) {
    const rawSummary = parseStructuredInputSummary(rawInput, toolName);
    if (rawSummary && !isPlaceholderToolInputSummary(rawSummary)) {
      return rawSummary;
    }
  }

  if (directSummary) {
    return directSummary;
  }

  return formatIdentifierLabel(trimmed, { maxLength: 28 });
};

const commandPreviewForRecord = (record: Record<string, unknown>, toolName?: string) => {
  const tool = normalizedToolName(toolName);
  if (tool !== 'read' && tool !== 'run_command' && tool !== 'control') return '';
  const command = stringField(record, ['command', 'cmd']);
  return command ? formatShellCommandPreview(command) : '';
};

const partialCommandPreview = (input: string | undefined, toolName?: string) => {
  const tool = normalizedToolName(toolName);
  if (tool !== 'read' && tool !== 'run_command' && tool !== 'control') return '';
  const command = extractPartialJSONStringField(input || '', ['command', 'cmd']);
  return command ? formatShellCommandPreview(command) : '';
};

const parseStructuredCommandPreview = (input: string, toolName?: string) => {
  const parsed = parseStructuredInputRecord(input);
  if (!parsed) return '';
  return commandPreviewForRecord(parsed.record, parsed.name || toolName);
};

export const parseToolCommandPreview = (input: string, toolName?: string, rawInput?: string) => {
  const trimmed = input.trim();
  const directPreview = trimmed
    ? parseStructuredCommandPreview(trimmed, toolName) || partialCommandPreview(trimmed, toolName)
    : '';
  if (directPreview) return directPreview;

  const raw = rawInput?.trim();
  if (raw && raw !== trimmed) {
    return parseStructuredCommandPreview(raw, toolName) || partialCommandPreview(raw, toolName);
  }

  return '';
};

export const toolValueText = (value: unknown) => {
  if (typeof value === 'string') return value;
  if (value === null || value === undefined) return '';
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
};