Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

19.0 KB
Raw Blame
import fs from 'node:fs';

import type { Command } from 'commander';
import pc from 'picocolors';

import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
import { resolveUrlBuilder, resourcePath, withUrl, withUrls } from './resourceUrl';
import { resolveAppUrlBuilder } from './task/url';

// ── Helpers ────────────────────────────────────────────────

/** Upper bound for `--all`: at 100 rows a page this covers 100k documents. */
const MAX_ALL_PAGES = 1000;

function readBodyContent(options: { body?: string; bodyFile?: string }): string | undefined {
  if (options.bodyFile) {
    if (!fs.existsSync(options.bodyFile)) {
      log.error(`File not found: ${options.bodyFile}`);
      process.exit(1);
    }
    return fs.readFileSync(options.bodyFile, 'utf8');
  }
  return options.body;
}

// ── Command Registration ───────────────────────────────────

export function registerDocCommand(program: Command) {
  const doc = program.command('doc').description('Manage documents');

  // ── list ──────────────────────────────────────────────

  doc
    .command('list')
    .description('List documents, one page at a time')
    .option('-L, --limit <n>', 'Page size (1-100)', '30')
    .option('--page <n>', 'Zero-based page index; 0 is the first page of the sort order', '0')
    .option('--sort-by <field>', 'Sort field: createdAt | updatedAt | title', 'updatedAt')
    .option('--all', 'Walk every page and return all matching documents')
    .option('--file-type <type>', 'Filter by file type')
    .option('--source-type <type>', 'Filter by source type (file, web, api, topic)')
    .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
    .action(
      async (options: {
        all?: boolean;
        fileType?: string;
        json?: string | boolean;
        limit?: string;
        page?: string;
        sortBy?: string;
        sourceType?: string;
      }) => {
        const client = await getTrpcClient();

        const pageSize = Number.parseInt(options.limit || '30', 10);
        if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 100) {
          log.error('--limit must be an integer between 1 and 100');
          process.exit(1);
          return;
        }

        const sortBy = options.sortBy || 'updatedAt';
        if (sortBy !== 'createdAt' && sortBy !== 'updatedAt' && sortBy !== 'title') {
          log.error('--sort-by must be one of: createdAt, updatedAt, title');
          process.exit(1);
          return;
        }

        const startPage = Number.parseInt(options.page || '0', 10);
        if (!Number.isInteger(startPage) || startPage < 0) {
          log.error('--page must be a non-negative integer');
          process.exit(1);
          return;
        }

        const query: {
          current: number;
          fileTypes?: string[];
          pageSize: number;
          sortBy: 'createdAt' | 'title' | 'updatedAt';
          sourceTypes?: string[];
        } = { current: startPage, pageSize, sortBy };
        if (options.fileType) query.fileTypes = [options.fileType];
        if (options.sourceType) query.sourceTypes = [options.sourceType];

        const fetchPage = async (page: number) => {
          const result = await client.document.queryDocuments.query({ ...query, current: page });
          const items = Array.isArray(result) ? result : ((result as any).items ?? []);
          const total = Array.isArray(result) ? undefined : (result as any).total;
          return { items, total };
        };

        let docs: any[] = [];
        let total: number | undefined;
        let page = startPage;
        // `--all` normally stops when the server runs out of rows. If it stops
        // because of MAX_ALL_PAGES instead, the result is incomplete and the
        // caller has to be told rather than handed a short list as if complete.
        let truncated = false;

        if (options.all) {
          // Walk forward until the server runs out of rows. The cap keeps a bad
          // `total` from turning the loop into an unbounded request stream.
          let exhausted = false;
          for (let i = 0; i < MAX_ALL_PAGES; i++) {
            const chunk = await fetchPage(page);
            total = chunk.total ?? total;
            if (chunk.items.length === 0) {
              exhausted = true;
              break;
            }

            docs = docs.concat(chunk.items);
            if (total !== undefined ? docs.length >= total : chunk.items.length < pageSize) {
              exhausted = true;
              break;
            }
            page += 1;
          }
          truncated = !exhausted;
          page = startPage;
        } else {
          const chunk = await fetchPage(page);
          docs = chunk.items;
          total = chunk.total;
        }

        const pageCount =
          total === undefined ? undefined : Math.max(1, Math.ceil(total / pageSize));
        const hasNext =
          !options.all &&
          (total === undefined ? docs.length === pageSize : page + 1 < (pageCount ?? 0));

        if (options.json !== undefined) {
          const fields = typeof options.json === 'string' ? options.json : undefined;
          outputJson(
            withUrls(docs, await resolveUrlBuilder(client), resourcePath.document),
            fields,
          );
          // Keep stdout valid JSON β€” the pagination hint goes to stderr.
          if (hasNext) {
            process.stderr.write(
              `${docs.length} row(s) returned, more available β€” continue with --page ${page + 1}\n`,
            );
          }
          if (truncated) {
            process.stderr.write(
              `Warning: --all stopped at the ${MAX_ALL_PAGES}-page cap after ${docs.length}${total === undefined ? '' : ` of ${total}`} document(s); the list is incomplete β€” narrow the filters or raise --limit\n`,
            );
          }
          return;
        }

        if (docs.length === 0) {
          console.log(
            total ? `No documents on page ${page + 1} (${total} total).` : 'No documents found.',
          );
          return;
        }

        const rows = docs.map((d: any) => [
          d.id,
          truncate(d.title || d.filename || 'Untitled', 120),
          d.fileType || '',
          d.updatedAt ? timeAgo(d.updatedAt) : '',
        ]);

        printTable(rows, ['ID', 'TITLE', 'TYPE', 'UPDATED']);

        if (options.all) {
          if (truncated) {
            log.warn(
              `Showing ${docs.length}${total === undefined ? '' : ` of ${total}`} β€” stopped at the ${MAX_ALL_PAGES}-page cap, so the list is incomplete; narrow the filters or raise --limit`,
            );
          } else {
            log.info(`Total: ${total ?? docs.length} (all pages)`);
          }
          return;
        }

        const from = page * pageSize + 1;
        const to = page * pageSize + docs.length;
        const range = `${from}-${to}${total === undefined ? '' : ` of ${total}`}`;
        const pager =
          pageCount === undefined ? `page ${page + 1}` : `page ${page + 1}/${pageCount}`;
        log.info(`${range} Β· ${pager}${hasNext ? ` Β· next: --page ${page + 1}` : ' Β· last page'}`);
      },
    );

  // ── view ──────────────────────────────────────────────

  doc
    .command('view <id>')
    .description('View a document')
    .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
    .action(async (id: string, options: { json?: string | boolean }) => {
      const client = await getTrpcClient();
      const document = await client.document.getDocumentById.query({ id });

      if (!document) {
        log.error(`Document not found: ${id}`);
        process.exit(1);
        return;
      }

      if (options.json !== undefined) {
        const fields = typeof options.json === 'string' ? options.json : undefined;
        outputJson(
          withUrl(
            document,
            await resolveUrlBuilder(client),
            resourcePath.document(document as any),
          ),
          fields,
        );
        return;
      }

      // Human-readable output
      console.log(pc.bold(document.title || 'Untitled'));
      const meta: string[] = [];
      if (document.fileType) meta.push(document.fileType);
      if ((document as any).knowledgeBaseId) meta.push(`KB: ${(document as any).knowledgeBaseId}`);
      if (document.updatedAt) meta.push(`Updated ${timeAgo(document.updatedAt)}`);
      if (meta.length > 0) console.log(pc.dim(meta.join(' Β· ')));
      console.log();

      if (document.content) {
        console.log(document.content);
      } else {
        console.log(pc.dim('(no content)'));
      }
    });

  // ── create ────────────────────────────────────────────

  doc
    .command('create')
    .description('Create a new document')
    .requiredOption('-t, --title <title>', 'Document title')
    .option('-b, --body <content>', 'Document content')
    .option('-F, --body-file <path>', 'Read content from file')
    .option('--parent <id>', 'Parent document or folder ID')
    .option('--slug <slug>', 'Custom slug')
    .option('--kb <id>', 'Knowledge base ID to associate with')
    .option('--file-type <type>', 'File type (e.g. custom/document, custom/folder)')
    .action(
      async (options: {
        body?: string;
        bodyFile?: string;
        fileType?: string;
        kb?: string;
        parent?: string;
        slug?: string;
        title: string;
      }) => {
        const content = readBodyContent(options);
        const client = await getTrpcClient();
        const buildUrl = await resolveAppUrlBuilder(client);

        const result = await client.document.createDocument.mutate({
          // The server builds the editor state from `content`; the CLI has no editor.
          content,
          fileType: options.fileType,
          knowledgeBaseId: options.kb,
          // Inside an agent run, credit the document to that run so it shows up
          // as the run's deliverable (e.g. on a Goal) instead of a loose page.
          ...(process.env.LOBEHUB_OPERATION_ID
            ? { operationId: process.env.LOBEHUB_OPERATION_ID }
            : {}),
          parentId: options.parent,
          slug: options.slug,
          title: options.title,
        });
        const url = buildUrl(
          resourcePath.document({ id: result.id, knowledgeBaseId: options.kb })!,
        );

        console.log(`${pc.green('βœ“')} Created document ${pc.bold(result.id)}`);
        console.log(`${pc.bold('document')}: ${url}`);
      },
    );

  // ── batch-create ───────────────────────────────────────

  doc
    .command('batch-create <file>')
    .description('Batch create documents from a JSON file')
    .action(async (file: string) => {
      if (!fs.existsSync(file)) {
        log.error(`File not found: ${file}`);
        process.exit(1);
        return;
      }

      let documents: any[];
      try {
        const raw = fs.readFileSync(file, 'utf8');
        documents = JSON.parse(raw);
      } catch {
        log.error('Failed to parse JSON file. Expected an array of document objects.');
        process.exit(1);
        return;
      }

      if (!Array.isArray(documents) || documents.length === 0) {
        log.error('JSON file must contain a non-empty array of document objects.');
        process.exit(1);
        return;
      }

      const client = await getTrpcClient();
      const buildUrl = await resolveAppUrlBuilder(client);

      const items = documents.map((d) => ({
        content: d.content,
        fileType: d.fileType,
        knowledgeBaseId: d.knowledgeBaseId,
        parentId: d.parentId,
        slug: d.slug,
        title: d.title,
      }));

      const result = await client.document.createDocuments.mutate({ documents: items });
      const created = Array.isArray(result) ? result : [result];
      const urls = await Promise.all(
        created.map((document, index) => {
          const source = items[index];
          return buildUrl(
            resourcePath.document({ id: document.id, knowledgeBaseId: source?.knowledgeBaseId })!,
          );
        }),
      );
      console.log(`${pc.green('βœ“')} Created ${created.length} document(s)`);
      for (const [index, doc] of created.entries()) {
        console.log(`  ${pc.dim('β€’')} ${doc.id} β€” ${doc.title || 'Untitled'} β€” ${urls[index]}`);
      }
    });

  // ── edit ──────────────────────────────────────────────

  doc
    .command('edit <id>')
    .description('Edit a document')
    .option('-t, --title <title>', 'New title')
    .option('-b, --body <content>', 'New content')
    .option('-F, --body-file <path>', 'Read new content from file')
    .option('--parent <id>', 'Move to parent document (empty string for root)')
    .option('--file-type <type>', 'Change file type')
    .action(
      async (
        id: string,
        options: {
          body?: string;
          bodyFile?: string;
          fileType?: string;
          parent?: string;
          title?: string;
        },
      ) => {
        const content = readBodyContent(options);

        if (!options.title && !content && options.parent === undefined && !options.fileType) {
          log.error(
            'No changes specified. Use --title, --body, --body-file, --parent, or --file-type.',
          );
          process.exit(1);
        }

        const client = await getTrpcClient();

        const params: Record<string, any> = { id };
        if (options.title) params.title = options.title;
        // The server rebuilds the editor state from the new content.
        if (content !== undefined) params.content = content;
        if (options.parent !== undefined) {
          params.parentId = options.parent || null;
        }
        if (options.fileType) params.fileType = options.fileType;
        // Inside an agent run, an edit becomes a new version of that run's deliverable.
        if (process.env.LOBEHUB_OPERATION_ID) params.operationId = process.env.LOBEHUB_OPERATION_ID;

        await client.document.updateDocument.mutate(params as any);
        console.log(`${pc.green('βœ“')} Updated document ${pc.bold(id)}`);
      },
    );

  // ── delete ────────────────────────────────────────────

  doc
    .command('delete <ids...>')
    .description('Delete one or more documents')
    .option('--yes', 'Skip confirmation prompt')
    .action(async (ids: string[], options: { yes?: boolean }) => {
      if (!options.yes) {
        const confirmed = await confirm(
          `Are you sure you want to delete ${ids.length} document(s)?`,
        );
        if (!confirmed) {
          console.log('Cancelled.');
          return;
        }
      }

      const client = await getTrpcClient();

      if (ids.length === 1) {
        await client.document.deleteDocument.mutate({ id: ids[0] });
      } else {
        await client.document.deleteDocuments.mutate({ ids });
      }

      console.log(`${pc.green('βœ“')} Deleted ${ids.length} document(s)`);
    });

  // ── parse ─────────────────────────────────────────────

  doc
    .command('parse <fileId>')
    .description('Parse an uploaded file into a document')
    .option('--with-pages', 'Preserve page structure')
    .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
    .action(async (fileId: string, options: { json?: string | boolean; withPages?: boolean }) => {
      const client = await getTrpcClient();

      const result = options.withPages
        ? await client.document.parseFileContent.mutate({ id: fileId })
        : await client.document.parseDocument.mutate({ id: fileId });

      if (options.json !== undefined) {
        const fields = typeof options.json === 'string' ? options.json : undefined;
        outputJson(result, fields);
        return;
      }

      console.log(`${pc.green('βœ“')} Parsed file ${pc.bold(fileId)}`);
      if ((result as any).title) console.log(`  Title: ${(result as any).title}`);
      if ((result as any).content) {
        const preview = truncate((result as any).content, 200);
        console.log(`  Content: ${pc.dim(preview)}`);
      }
    });

  // ── link-topic ────────────────────────────────────────

  doc
    .command('link-topic <docId> <topicId>')
    .description('Associate a document with a topic')
    .action(async (docId: string, topicId: string) => {
      const client = await getTrpcClient();

      // Attach the existing document; creating a copy here used to leave two
      // documents (and two run deliverables) for a single link.
      const document = await client.document.getDocumentById.query({ id: docId });
      if (!document) {
        log.error(`Document not found: ${docId}`);
        process.exit(1);
        return;
      }

      const result = await client.notebook.associateDocument.mutate({ documentId: docId, topicId });

      console.log(
        `${pc.green('βœ“')} Linked document ${pc.bold(result.documentId)} to topic ${pc.bold(topicId)}`,
      );
    });

  // ── topic-docs ────────────────────────────────────────

  doc
    .command('topic-docs <topicId>')
    .description('List documents associated with a topic')
    .option('--type <type>', 'Filter by document type (article, markdown, note, report)')
    .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')
    .action(async (topicId: string, options: { json?: string | boolean; type?: string }) => {
      const client = await getTrpcClient();

      const query: { topicId: string; type?: any } = { topicId };
      if (options.type) query.type = options.type;
      const result = await client.notebook.listDocuments.query(query);
      const docs = Array.isArray(result) ? result : ((result as any).data ?? []);

      if (options.json !== undefined) {
        const fields = typeof options.json === 'string' ? options.json : undefined;
        outputJson(withUrls(docs, await resolveUrlBuilder(client), resourcePath.document), fields);
        return;
      }

      if (docs.length === 0) {
        console.log('No documents found for this topic.');
        return;
      }

      const rows = docs.map((d: any) => [
        d.id,
        truncate(d.title || 'Untitled', 120),
        d.fileType || '',
        d.updatedAt ? timeAgo(d.updatedAt) : '',
      ]);

      printTable(rows, ['ID', 'TITLE', 'TYPE', 'UPDATED']);
    });
}