Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

3.9 KB
Raw Blame
import { generateObject, generateText, jsonSchema } from 'ai';
import { localStorage } from '@/core/env';
import { actionSteps } from '@/core/guides/blocks';
import { MAX_TITLE_LENGTH, sanitizeGuideTitle } from '@/core/guides/title';
import type { Step } from '@/core/guides/types';
import { logger } from '@/core/logger';
import { formatExamples, resolveExamples } from './examples';
import { GUIDE_META_JSON_SUFFIX, GUIDE_META_PROMPT, getLanguageSuffix } from './prompts';
import { createModel } from './provider';
import { unwrapQuotes } from './text';

export interface GuideMeta {
  title: string;
  description?: string;
}

const MAX_BARE_TITLE_LENGTH = 100;
const FENCE = /^```(?:json)?\s*|\s*```$/g;

const guideMetaSchema = jsonSchema<{ title: string; description?: string | null }>({
  type: 'object',
  properties: {
    title: { type: 'string' },
    description: { type: ['string', 'null'] },
  },
  required: ['title', 'description'],
  additionalProperties: false,
});

function toGuideMeta(rawTitle: unknown, rawDescription: unknown): GuideMeta | null {
  let title = typeof rawTitle === 'string' ? unwrapQuotes(sanitizeGuideTitle(rawTitle)) : '';
  if (!title) return null;
  if (title.length > MAX_TITLE_LENGTH) title = `${title.slice(0, MAX_TITLE_LENGTH - 3)}...`;

  const description = typeof rawDescription === 'string' ? unwrapQuotes(rawDescription) || undefined : undefined;
  return { title, description };
}

export function parseGuideMeta(raw: string): GuideMeta | null {
  const text = raw.trim().replace(FENCE, '').trim();

  const start = text.indexOf('{');
  const end = text.lastIndexOf('}');
  if (start !== -1 && end > start) {
    try {
      const parsed = JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>;
      const meta = toGuideMeta(parsed.title, parsed.description);
      if (meta) return meta;
    } catch {
      logger.warn('Guide meta fallback returned malformed JSON');
    }
  }

  const line = text.split('\n')[0]?.trim() ?? '';
  if (!line || line.length > MAX_BARE_TITLE_LENGTH || line.includes('{')) return null;
  return toGuideMeta(line, null);
}

export async function generateGuideMeta(
  steps: { description: string; place: string }[],
  provider: string,
  model: string,
  apiKey: string,
  baseUrl?: string,
): Promise<GuideMeta | null> {
  if (steps.length === 0) return null;

  const formatted = steps.map((s, i) => `${i + 1}. [${s.place}] ${s.description}`).join('\n');
  const settings = await localStorage.get(['aiLanguage']);
  const locale = (settings.aiLanguage as string) || 'en';
  const examples = resolveExamples(locale);
  const prompt =
    GUIDE_META_PROMPT.replace('{{titleExamples}}', formatExamples(examples.titles))
      .replace('{{descriptionExamples}}', formatExamples(examples.descriptions))
      .replace('{{steps}}', () => formatted) + getLanguageSuffix(locale);
  const aiModel = createModel(provider, model, apiKey, baseUrl);

  try {
    const { object } = await generateObject({
      model: aiModel,
      schema: guideMetaSchema,
      prompt,
      maxOutputTokens: 200,
    });
    return toGuideMeta(object.title, object.description);
  } catch (err) {
    logger.warn('Structured guide meta failed, retrying as plain text', err);
  }

  try {
    const { text } = await generateText({
      model: aiModel,
      prompt: prompt + GUIDE_META_JSON_SUFFIX,
      maxOutputTokens: 200,
    });
    return parseGuideMeta(text);
  } catch (err) {
    logger.error('Guide meta generation failed', err);
    return null;
  }
}

export function guideMetaSteps(steps: Step[]): { description: string; place: string }[] {
  const described = actionSteps(steps)
    .filter((step) => step.description)
    .map((step) => ({
      description: step.description,
      place: step.url || [step.app?.name, step.window?.title].filter(Boolean).join(' β€” '),
    }));
  return described.length > 15 ? [...described.slice(0, 10), ...described.slice(-5)] : described;
}