Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
knowledge
Nika Siradzea6655deb795c
diff --git a/.gitignore b/.gitignoreindex 29b67db..2004503 100644--- a/.gitignore+++ b/.gitignore@@ -7,6 +7,7 @@ dist/# Data directorydata/+.podcli/# Environment.envdiff --git a/src/config/paths.ts b/src/config/paths.tsindex 4a85ae1..e387ef7 100644--- a/src/config/paths.ts+++ b/src/config/paths.ts@@ -1,11 +1,12 @@-import { homedir } from "os";import { join, dirname } from "path";import { fileURLToPath } from "url";const __dirname = dirname(fileURLToPath(import.meta.url));+// Project-local .podcli directory (next to package.json)+const projectRoot = join(__dirname, "..", "..");const home =- process.env.PODCLI_HOME || join(homedir(), ".podcli");+ process.env.PODCLI_HOME || join(projectRoot, ".podcli");export const paths = {home,@@ -14,6 +15,11 @@ export const paths = {working: join(home, "working"),output: join(home, "output"),logs: join(home, "logs"),+ assets: join(home, "assets"),+ assetsRegistry: join(home, "assets", "registry.json"),+ history: join(home, "history"),+ clipsHistory: join(home, "history", "clips.json"),+ knowledge: join(home, "knowledge"),pythonBackend: join(__dirname, "..", "..", "backend", "main.py"),pythonPath: process.env.PYTHON_PATH || "python3",ffmpegPath: process.env.FFMPEG_PATH || "ffmpeg",diff --git a/src/models/index.ts b/src/models/index.tsindex cb9c150..fcd66f0 100644--- a/src/models/index.ts+++ b/src/models/index.ts@@ -95,3 +95,41 @@ export interface SuggestedClip {reasoning: string;preview_text: string;}++// === Asset Models ===++export interface Asset {+ name: string;+ type: "logo" | "video" | "image" | "other";+ path: string;+ addedAt: string;+}++export interface AssetRegistry {+ assets: Asset[];+}++// === Clip History Models ===++export interface ClipHistoryEntry {+ id: string;+ source_video: string;+ start_second: number;+ end_second: number;+ caption_style: string;+ crop_strategy: string;+ logo_path?: string;+ title: string;+ output_path: string;+ file_size_mb: number;+ duration: number;+ created_at: string;+}++// === Knowledge Base Models ===++export interface KnowledgeFile {+ filename: string;+ content: string;+ updatedAt: string;+}diff --git a/src/server.ts b/src/server.tsindex 569adf1..e85fb0a 100644--- a/src/server.ts+++ b/src/server.ts@@ -6,8 +6,26 @@ import { suggestClipsToolDef, handleSuggestClips } from "./handlers/suggest-clipimport { createClipToolDef, handleCreateClip } from "./handlers/create-clip.handler.js";import { batchClipsToolDef, handleBatchClips } from "./handlers/batch-clips.handler.js";import { FileManager } from "./services/file-manager.js";+import { KnowledgeBase } from "./services/knowledge-base.js";+import { AssetManager } from "./services/asset-manager.js";+import { ClipsHistory } from "./services/clips-history.js";import { paths } from "./config/paths.js";+const kb = new KnowledgeBase();+const assets = new AssetManager();+const history = new ClipsHistory();++/** Prepend knowledge base context to a tool result if available. */+async function withKnowledge(result: string): Promise<string> {+ try {+ const context = await kb.readAll();+ if (!context) return result;+ return `[Knowledge Base]\n${context}\n\n---\n\n${result}`;+ } catch {+ return result;+ }+}+export function createServer(): McpServer {const server = new McpServer({name: "podcli",@@ -41,7 +59,7 @@ export function createServer(): McpServer {async ({ file_path, model_size, language, enable_diarization, num_speakers }) => {try {const result = await handleTranscribe({ file_path, model_size, language, enable_diarization, num_speakers });- return { content: [{ type: "text" as const, text: result }] };+ return { content: [{ type: "text" as const, text: await withKnowledge(result) }] };} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);return {@@ -77,7 +95,16 @@ export function createServer(): McpServer {async ({ suggestions }) => {try {const result = await handleSuggestClips({ suggestions });- return { content: [{ type: "text" as const, text: result }] };+ // Include clip history so Claude avoids duplicates+ const existing = await history.list(20);+ let text = await withKnowledge(result);+ if (existing.length > 0) {+ const summary = existing.map(+ (e) => ` - "${e.title}" ${e.start_second}s–${e.end_second}s (${e.caption_style})`+ ).join("\n");+ text += `\n\n[Previously Created Clips — avoid duplicates]\n${summary}`;+ }+ return { content: [{ type: "text" as const, text }] };} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);return {@@ -122,7 +149,7 @@ export function createServer(): McpServer {logo_path: z.string().optional()- .describe("Path to PNG logo image. Shown in top-left (used with 'branded' style)."),+ .describe("Path or registered asset name for PNG logo. Shown in top-left (branded style)."),outro_video_path: z.string().optional()@@ -135,7 +162,46 @@ export function createServer(): McpServer {},async (params) => {try {+ // Resolve asset names to paths+ if (params.logo_path) {+ const resolved = await assets.resolve(params.logo_path);+ if (resolved) params.logo_path = resolved;+ }++ // Check for duplicates+ const dup = await history.findDuplicate(+ params.video_path as string,+ params.start_second as number,+ params.end_second as number,+ (params.caption_style || "hormozi") as string,+ (params.crop_strategy || "center") as string+ );+ if (dup) {+ return {+ content: [{+ type: "text" as const,+ text: `Duplicate found! This clip was already created on ${dup.created_at}.\nOutput: ${dup.output_path}\nUse a different time range or style to create a new clip.`,+ }],+ };+ }+const result = await handleCreateClip(params);+ const parsed = JSON.parse(result);++ // Record to history+ await history.record({+ source_video: params.video_path as string,+ start_second: params.start_second as number,+ end_second: params.end_second as number,+ caption_style: (params.caption_style || "hormozi") as string,+ crop_strategy: (params.crop_strategy || "center") as string,+ logo_path: params.logo_path as string | undefined,+ title: (params.title || "clip") as string,+ output_path: parsed.output_path,+ file_size_mb: parsed.file_size_mb,+ duration: parsed.duration,+ });+return { content: [{ type: "text" as const, text: result }] };} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);@@ -180,6 +246,27 @@ export function createServer(): McpServer {async (params) => {try {const result = await handleBatchClips(params);+ const parsed = JSON.parse(result);++ // Record each successful clip+ if (parsed.results) {+ for (const r of parsed.results as any[]) {+ if (r.status === "success" && r.output_path) {+ await history.record({+ source_video: params.video_path,+ start_second: r.start_second || 0,+ end_second: r.end_second || 0,+ caption_style: r.caption_style || "hormozi",+ crop_strategy: r.crop_strategy || "center",+ title: r.title || "clip",+ output_path: r.output_path,+ file_size_mb: r.file_size_mb || 0,+ duration: r.duration || 0,+ });+ }+ }+ }+return { content: [{ type: "text" as const, text: result }] };} catch (err: unknown) {const msg = err instanceof Error ? err.message : String(err);@@ -191,5 +278,132 @@ export function createServer(): McpServer {});+ // =============================================+ // Tool: knowledge_base+ // =============================================+ server.tool(+ "knowledge_base",+ "Read or manage the podcli knowledge base. These are .md files that provide context about the podcast (hosts, style, audience, etc). Always read the knowledge base before suggesting or creating clips.",+ {+ action: z.enum(["read_all", "list", "read", "write", "delete"]).describe("Action to perform"),+ filename: z.string().optional().describe("Filename for read/write/delete (e.g. 'style.md')"),+ content: z.string().optional().describe("Markdown content for write action"),+ },+ async ({ action, filename, content }) => {+ try {+ if (action === "read_all") {+ const text = await kb.readAll();+ return { content: [{ type: "text" as const, text: text || "Knowledge base is empty. Add .md files to ~/.podcli/knowledge/" }] };+ }+ if (action === "list") {+ const files = await kb.listFiles();+ const text = files.map((f) => `- ${f.filename} (updated ${f.updatedAt})`).join("\n");+ return { content: [{ type: "text" as const, text: text || "No knowledge files found." }] };+ }+ if (action === "read" && filename) {+ const text = await kb.readFile(filename);+ return { content: [{ type: "text" as const, text }] };+ }+ if (action === "write" && filename && content) {+ await kb.writeFile(filename, content);+ return { content: [{ type: "text" as const, text: `Saved ${filename}` }] };+ }+ if (action === "delete" && filename) {+ await kb.deleteFile(filename);+ return { content: [{ type: "text" as const, text: `Deleted ${filename}` }] };+ }+ return { content: [{ type: "text" as const, text: "Invalid action or missing parameters." }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };+ }+ }+ );++ // =============================================+ // Tool: manage_assets+ // =============================================+ server.tool(+ "manage_assets",+ "Register and manage reusable assets (logos, videos). Registered assets can be referenced by name in create_clip instead of full paths.",+ {+ action: z.enum(["list", "register", "unregister", "resolve"]).describe("Action to perform"),+ name: z.string().optional().describe("Asset name (e.g. 'podcast-logo')"),+ path: z.string().optional().describe("Absolute file path (for register)"),+ type: z.enum(["logo", "video", "image", "other"]).optional().describe("Asset type (for register/list filter)"),+ },+ async ({ action, name, path, type }) => {+ try {+ if (action === "list") {+ const items = await assets.list(type || undefined);+ if (items.length === 0) return { content: [{ type: "text" as const, text: "No assets registered." }] };+ const text = items.map((a) => `- ${a.name} (${a.type}): ${a.path}`).join("\n");+ return { content: [{ type: "text" as const, text }] };+ }+ if (action === "register" && name && path) {+ const asset = await assets.register(name, path, type || "other");+ return { content: [{ type: "text" as const, text: `Registered "${asset.name}" → ${asset.path}` }] };+ }+ if (action === "unregister" && name) {+ await assets.unregister(name);+ return { content: [{ type: "text" as const, text: `Unregistered "${name}"` }] };+ }+ if (action === "resolve" && name) {+ const resolved = await assets.resolve(name);+ return { content: [{ type: "text" as const, text: resolved || `Asset "${name}" not found.` }] };+ }+ return { content: [{ type: "text" as const, text: "Invalid action or missing parameters." }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };+ }+ }+ );++ // =============================================+ // Tool: clip_history+ // =============================================+ server.tool(+ "clip_history",+ "View previously created clips to avoid duplicates. Check before creating new clips.",+ {+ action: z.enum(["list", "check"]).describe("list = recent clips, check = find duplicate"),+ source_video: z.string().optional().describe("Source video path (for check or filter)"),+ start_second: z.number().optional().describe("Start time (for check)"),+ end_second: z.number().optional().describe("End time (for check)"),+ caption_style: z.string().optional().describe("Caption style (for check)"),+ crop_strategy: z.string().optional().describe("Crop strategy (for check)"),+ limit: z.number().optional().default(20).describe("Max results for list"),+ },+ async ({ action, source_video, start_second, end_second, caption_style, crop_strategy, limit }) => {+ try {+ if (action === "list") {+ const entries = source_video+ ? await history.getBySource(source_video)+ : await history.list(limit || 20);+ if (entries.length === 0) return { content: [{ type: "text" as const, text: "No clips in history." }] };+ const text = entries+ .map((e) => `- "${e.title}" ${e.start_second}s–${e.end_second}s | ${e.caption_style} | ${e.created_at} | ${e.output_path}`)+ .join("\n");+ return { content: [{ type: "text" as const, text }] };+ }+ if (action === "check" && source_video && start_second !== undefined && end_second !== undefined) {+ const dup = await history.findDuplicate(+ source_video, start_second, end_second,+ caption_style || "hormozi", crop_strategy || "center"+ );+ if (dup) {+ return { content: [{ type: "text" as const, text: `Duplicate found: "${dup.title}" created ${dup.created_at}\nOutput: ${dup.output_path}` }] };+ }+ return { content: [{ type: "text" as const, text: "No duplicate found. Safe to create." }] };+ }+ return { content: [{ type: "text" as const, text: "Invalid action or missing parameters." }] };+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };+ }+ }+ );+return server;}diff --git a/src/services/asset-manager.ts b/src/services/asset-manager.tsnew file mode 100644index 0000000..e0e956b--- /dev/null+++ b/src/services/asset-manager.ts@@ -0,0 +1,80 @@+import { readFile, writeFile, copyFile, mkdir } from "fs/promises";+import { existsSync } from "fs";+import { join, basename } from "path";+import { paths } from "../config/paths.js";+import type { Asset, AssetRegistry } from "../models/index.js";++export class AssetManager {+ private registryPath = paths.assetsRegistry;+ private assetsDir = paths.assets;++ private async ensureDir() {+ if (!existsSync(this.assetsDir)) {+ await mkdir(this.assetsDir, { recursive: true });+ }+ }++ async load(): Promise<AssetRegistry> {+ try {+ if (!existsSync(this.registryPath)) return { assets: [] };+ const raw = await readFile(this.registryPath, "utf-8");+ return JSON.parse(raw) as AssetRegistry;+ } catch {+ return { assets: [] };+ }+ }++ private async save(registry: AssetRegistry): Promise<void> {+ await this.ensureDir();+ await writeFile(this.registryPath, JSON.stringify(registry, null, 2), "utf-8");+ }++ async register(name: string, filePath: string, type: Asset["type"]): Promise<Asset> {+ if (!existsSync(filePath)) {+ throw new Error(`File not found: ${filePath}`);+ }+ const registry = await this.load();+ // Update if name exists, otherwise add+ const existing = registry.assets.findIndex((a) => a.name === name);+ const asset: Asset = { name, type, path: filePath, addedAt: new Date().toISOString() };+ if (existing >= 0) {+ registry.assets[existing] = asset;+ } else {+ registry.assets.push(asset);+ }+ await this.save(registry);+ return asset;+ }++ async unregister(name: string): Promise<void> {+ const registry = await this.load();+ registry.assets = registry.assets.filter((a) => a.name !== name);+ await this.save(registry);+ }++ async list(type?: string): Promise<Asset[]> {+ const registry = await this.load();+ if (type) return registry.assets.filter((a) => a.type === type);+ return registry.assets;+ }++ /** Resolve a name or path to an absolute file path. */+ async resolve(nameOrPath: string): Promise<string | null> {+ if (!nameOrPath) return null;+ // Check if it's a registered asset name+ const registry = await this.load();+ const asset = registry.assets.find((a) => a.name === nameOrPath);+ if (asset && existsSync(asset.path)) return asset.path;+ // Otherwise treat as a direct path+ if (existsSync(nameOrPath)) return nameOrPath;+ return null;+ }++ /** Copy a file into ~/.podcli/assets/ and register it. */+ async importFile(sourcePath: string, name: string, type: Asset["type"]): Promise<Asset> {+ await this.ensureDir();+ const destPath = join(this.assetsDir, basename(sourcePath));+ await copyFile(sourcePath, destPath);+ return this.register(name, destPath, type);+ }+}diff --git a/src/services/clips-history.ts b/src/services/clips-history.tsnew file mode 100644index 0000000..2e972df--- /dev/null+++ b/src/services/clips-history.ts@@ -0,0 +1,81 @@+import { readFile, writeFile, mkdir } from "fs/promises";+import { existsSync } from "fs";+import { basename } from "path";+import { v4 as uuidv4 } from "uuid";+import { paths } from "../config/paths.js";+import type { ClipHistoryEntry } from "../models/index.js";++export class ClipsHistory {+ private historyPath = paths.clipsHistory;++ private async ensureDir() {+ if (!existsSync(paths.history)) {+ await mkdir(paths.history, { recursive: true });+ }+ }++ async load(): Promise<ClipHistoryEntry[]> {+ try {+ if (!existsSync(this.historyPath)) return [];+ const raw = await readFile(this.historyPath, "utf-8");+ return JSON.parse(raw) as ClipHistoryEntry[];+ } catch {+ return [];+ }+ }++ private async save(entries: ClipHistoryEntry[]): Promise<void> {+ await this.ensureDir();+ await writeFile(this.historyPath, JSON.stringify(entries, null, 2), "utf-8");+ }++ async record(entry: Omit<ClipHistoryEntry, "id" | "created_at">): Promise<ClipHistoryEntry> {+ const entries = await this.load();+ const full: ClipHistoryEntry = {+ ...entry,+ id: uuidv4(),+ created_at: new Date().toISOString(),+ };+ entries.push(full);+ await this.save(entries);+ return full;+ }++ /**+ * Check if a clip with the same source, time range, and style already exists.+ * Uses basename matching for source video and ±2s tolerance on time range.+ */+ async findDuplicate(+ sourceVideo: string,+ startSecond: number,+ endSecond: number,+ captionStyle: string,+ cropStrategy: string+ ): Promise<ClipHistoryEntry | null> {+ const entries = await this.load();+ const srcName = basename(sourceVideo);++ return (+ entries.find((e) => {+ if (basename(e.source_video) !== srcName) return false;+ if (e.caption_style !== captionStyle) return false;+ if (e.crop_strategy !== cropStrategy) return false;+ if (Math.abs(e.start_second - startSecond) > 2) return false;+ if (Math.abs(e.end_second - endSecond) > 2) return false;+ // Check output still exists+ return existsSync(e.output_path);+ }) || null+ );+ }++ async list(limit = 50): Promise<ClipHistoryEntry[]> {+ const entries = await this.load();+ return entries.slice(-limit).reverse();+ }++ async getBySource(videoPath: string): Promise<ClipHistoryEntry[]> {+ const entries = await this.load();+ const srcName = basename(videoPath);+ return entries.filter((e) => basename(e.source_video) === srcName).reverse();+ }+}diff --git a/src/services/file-manager.ts b/src/services/file-manager.tsindex eac2f0a..533a0f0 100644--- a/src/services/file-manager.ts+++ b/src/services/file-manager.ts@@ -16,6 +16,9 @@ export class FileManager {paths.working,paths.output,paths.logs,+ paths.assets,+ paths.history,+ paths.knowledge,];for (const dir of dirs) {if (!existsSync(dir)) {diff --git a/src/services/knowledge-base.ts b/src/services/knowledge-base.tsnew file mode 100644index 0000000..1a56920--- /dev/null+++ b/src/services/knowledge-base.ts@@ -0,0 +1,80 @@+import { readFile, writeFile, readdir, stat, unlink, mkdir } from "fs/promises";+import { existsSync } from "fs";+import { join } from "path";+import { paths } from "../config/paths.js";+import type { KnowledgeFile } from "../models/index.js";++const DEFAULT_README = `# podcli Knowledge Base++Add \`.md\` files here to give the AI context when creating clips.++## Suggested files++- \`podcast.md\` — Show name, description, format, episode structure+- \`hosts.md\` — Host names, speaking styles, roles+- \`style.md\` — Preferred caption style, logo, crop strategy, colors+- \`audience.md\` — Target audience, platform preferences (TikTok vs Reels vs Shorts)+- \`avoid.md\` — Topics, segments, or time ranges to skip++The MCP server reads all files here before processing requests.+`;++export class KnowledgeBase {+ private dir = paths.knowledge;++ async ensureDir() {+ if (!existsSync(this.dir)) {+ await mkdir(this.dir, { recursive: true });+ // Write default README+ await writeFile(join(this.dir, "README.md"), DEFAULT_README, "utf-8");+ }+ }++ async listFiles(): Promise<KnowledgeFile[]> {+ await this.ensureDir();+ const entries = await readdir(this.dir);+ const mdFiles = entries.filter((f) => f.endsWith(".md"));++ const files: KnowledgeFile[] = [];+ for (const filename of mdFiles) {+ const filePath = join(this.dir, filename);+ const s = await stat(filePath);+ const content = await readFile(filePath, "utf-8");+ files.push({+ filename,+ content,+ updatedAt: s.mtime.toISOString(),+ });+ }+ return files.sort((a, b) => a.filename.localeCompare(b.filename));+ }++ /** Read all .md files concatenated — the main method used by MCP tools. */+ async readAll(): Promise<string> {+ const files = await this.listFiles();+ // Skip README+ const relevant = files.filter((f) => f.filename !== "README.md");+ if (relevant.length === 0) return "";++ return relevant+ .map((f) => `--- ${f.filename} ---\n${f.content.trim()}`)+ .join("\n\n");+ }++ async readFile(filename: string): Promise<string> {+ const filePath = join(this.dir, filename);+ if (!existsSync(filePath)) throw new Error(`File not found: ${filename}`);+ return readFile(filePath, "utf-8");+ }++ async writeFile(filename: string, content: string): Promise<void> {+ await this.ensureDir();+ if (!filename.endsWith(".md")) filename += ".md";+ await writeFile(join(this.dir, filename), content, "utf-8");+ }++ async deleteFile(filename: string): Promise<void> {+ const filePath = join(this.dir, filename);+ if (existsSync(filePath)) await unlink(filePath);+ }+}diff --git a/src/ui/public/index.html b/src/ui/public/index.htmlindex 36f064b..be09647 100644--- a/src/ui/public/index.html+++ b/src/ui/public/index.html@@ -674,6 +674,7 @@{encoderInfo.best === 'libx264' ? 'CPU' : encoderInfo.best.replace('h264_','').toUpperCase()}</span>)}+ <a href="/knowledge.html" style={{ fontSize:12, fontWeight:600, color:'var(--text2)', textDecoration:'none', padding:'5px 12px', border:'1px solid var(--border)', borderRadius:'var(--radius-sm)', transition:'all 0.15s' }}>Knowledge</a><a href="/integration.html" style={{ fontSize:12, fontWeight:600, color:'var(--text2)', textDecoration:'none', padding:'5px 12px', border:'1px solid var(--border)', borderRadius:'var(--radius-sm)', transition:'all 0.15s' }}>MCP Setup</a></div></div>diff --git a/src/ui/public/knowledge.html b/src/ui/public/knowledge.htmlnew file mode 100644index 0000000..1428817--- /dev/null+++ b/src/ui/public/knowledge.html@@ -0,0 +1,364 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>podcli — Knowledge Base</title>+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">+ <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.9/babel.min.js"></script>+ <style>+ :root {+ --bg: #0b0b0d;+ --surface: #131316;+ --surface2: #1b1b20;+ --border: #252530;+ --border-hover: #35354a;+ --text: #e8e8e2;+ --text2: #77776f;+ --text3: #4e4e48;+ --accent: #d4874a;+ --accent-hover: #e09860;+ --accent-subtle: rgba(212, 135, 74, 0.10);+ --accent-glow: rgba(212, 135, 74, 0.25);+ --green: #4ade80;+ --green-subtle: rgba(74, 222, 128, 0.07);+ --green-border: rgba(74, 222, 128, 0.18);+ --red: #f87171;+ --red-subtle: rgba(248, 113, 113, 0.07);+ --red-border: rgba(248, 113, 113, 0.18);+ --radius: 12px;+ --radius-sm: 8px;+ --ease: cubic-bezier(0.4, 0, 0.2, 1);+ }++ * { margin: 0; padding: 0; box-sizing: border-box; }+ body {+ font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;+ background: var(--bg); color: var(--text); min-height: 100vh;+ -webkit-font-smoothing: antialiased;+ }++ .app { max-width: 860px; margin: 0 auto; padding: 48px 32px 96px; }+ .nav { display: flex; align-items: center; justify-content: space-between; margin-bottom: 28px; }+ .logo { font-size: 13px; font-weight: 700; letter-spacing: 1.2px; color: var(--text3); text-transform: uppercase; text-decoration: none; }+ .logo span { color: var(--accent); }+ .nav-link {+ font-size: 13px; font-weight: 600; color: var(--text2);+ text-decoration: none; padding: 6px 14px;+ border-radius: var(--radius-sm); border: 1px solid var(--border);+ transition: all 0.15s var(--ease);+ }+ .nav-link:hover { border-color: var(--border-hover); color: var(--text); }++ .header { margin-bottom: 32px; }+ h1 { font-size: 28px; font-weight: 700; letter-spacing: -0.5px; line-height: 1.15; }+ .subtitle { font-size: 14px; color: var(--text2); margin-top: 8px; line-height: 1.6; }+ .dir-path {+ display: inline-flex; align-items: center; gap: 6px;+ margin-top: 10px; padding: 5px 12px;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius-sm);+ font-family: 'JetBrains Mono', monospace; font-size: 11.5px; color: var(--text2);+ }++ /* ─── Drop Zone ─── */+ .drop-zone {+ border: 1.5px dashed var(--border); border-radius: var(--radius);+ padding: 36px 24px; text-align: center; cursor: pointer;+ transition: all 0.2s var(--ease); position: relative; margin-bottom: 24px;+ }+ .drop-zone:hover { border-color: var(--border-hover); background: rgba(255,255,255,0.012); }+ .drop-zone.drag-over { border-color: var(--accent); background: var(--accent-subtle); box-shadow: 0 0 0 4px var(--accent-subtle); }+ .drop-zone .dz-icon { font-size: 28px; opacity: 0.3; margin-bottom: 8px; }+ .drop-zone .dz-text { font-size: 13px; color: var(--text2); line-height: 1.5; }+ .drop-zone .dz-text strong { color: var(--accent); font-weight: 600; }+ .drop-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }++ /* ─── File Grid ─── */+ .file-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }+ .file-card {+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); padding: 16px; cursor: pointer;+ transition: all 0.15s var(--ease); position: relative;+ }+ .file-card:hover { border-color: var(--border-hover); }+ .file-card.active { border-color: var(--accent); background: var(--accent-subtle); }+ .file-name {+ font-family: 'JetBrains Mono', monospace; font-size: 13px;+ font-weight: 600; color: var(--text); margin-bottom: 4px;+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .file-meta { font-size: 11px; color: var(--text3); }+ .file-preview { font-size: 12px; color: var(--text2); margin-top: 8px; line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }+ .file-delete {+ position: absolute; top: 10px; right: 10px;+ width: 22px; height: 22px; border-radius: 6px;+ background: transparent; border: 1px solid transparent;+ color: var(--text3); cursor: pointer; font-size: 13px;+ display: flex; align-items: center; justify-content: center;+ transition: all 0.15s var(--ease); opacity: 0;+ }+ .file-card:hover .file-delete { opacity: 1; }+ .file-delete:hover { border-color: var(--red-border); color: var(--red); background: var(--red-subtle); }++ /* ─── Editor ─── */+ .editor-panel {+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius); overflow: hidden; margin-top: 20px;+ }+ .editor-header {+ display: flex; align-items: center; justify-content: space-between;+ padding: 10px 16px; background: var(--surface2);+ border-bottom: 1px solid var(--border);+ }+ .editor-filename {+ font-family: 'JetBrains Mono', monospace; font-size: 12px;+ font-weight: 600; color: var(--text);+ }+ .editor-actions { display: flex; gap: 6px; }+ .btn {+ padding: 6px 14px; border-radius: var(--radius-sm); font-family: inherit;+ font-size: 12px; font-weight: 600; cursor: pointer; border: none;+ transition: all 0.15s var(--ease); display: inline-flex;+ align-items: center; gap: 5px;+ }+ .btn-primary { background: var(--accent); color: #fff; }+ .btn-primary:hover { background: var(--accent-hover); }+ .btn-ghost { background: transparent; color: var(--text2); border: 1px solid var(--border); }+ .btn-ghost:hover { border-color: var(--border-hover); color: var(--text); }+ .editor-textarea {+ width: 100%; min-height: 320px; padding: 16px;+ background: transparent; border: none; color: var(--text);+ font-family: 'JetBrains Mono', monospace; font-size: 13px;+ line-height: 1.7; resize: vertical; outline: none;+ }++ /* ─── New File ─── */+ .new-file-row {+ display: flex; gap: 8px; margin-top: 16px;+ }+ .new-file-input {+ flex: 1; padding: 8px 14px;+ background: var(--surface); border: 1px solid var(--border);+ border-radius: var(--radius-sm); color: var(--text);+ font-family: 'JetBrains Mono', monospace; font-size: 13px;+ outline: none;+ }+ .new-file-input:focus { border-color: var(--accent); }+ .new-file-input::placeholder { color: var(--text3); }++ /* ─── Toast ─── */+ .toast {+ position: fixed; bottom: 24px; right: 24px;+ padding: 10px 18px; border-radius: var(--radius-sm);+ background: var(--green-subtle); border: 1px solid var(--green-border);+ color: var(--green); font-size: 13px; font-weight: 600;+ animation: fadeIn 0.2s var(--ease);+ }++ .empty-state { text-align: center; padding: 48px 20px; color: var(--text3); font-size: 13px; }++ @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }+ @media (max-width: 640px) {+ .app { padding: 28px 16px 64px; }+ .file-grid { grid-template-columns: 1fr; }+ }+ </style>+</head>+<body>+ <div id="root"></div>+ <script type="text/babel">+ const { useState, useEffect, useCallback } = React;++ function App() {+ const [files, setFiles] = useState([]);+ const [activeFile, setActiveFile] = useState(null);+ const [editorContent, setEditorContent] = useState('');+ const [dirty, setDirty] = useState(false);+ const [dragOver, setDragOver] = useState(false);+ const [toast, setToast] = useState(null);+ const [newName, setNewName] = useState('');+ const [kbDir, setKbDir] = useState('');++ const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2000); };++ const loadFiles = useCallback(async () => {+ const data = await (await fetch('/api/knowledge')).json();+ setFiles(data);+ }, []);++ useEffect(() => {+ loadFiles();+ fetch('/api/knowledge/dir').then(r => r.json()).then(d => setKbDir(d.path)).catch(() => {});+ }, []);++ const openFile = (f) => {+ if (dirty && !confirm('Discard unsaved changes?')) return;+ setActiveFile(f.filename);+ setEditorContent(f.content);+ setDirty(false);+ };++ const saveFile = async () => {+ if (!activeFile) return;+ await fetch(`/api/knowledge/${encodeURIComponent(activeFile)}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ content: editorContent }),+ });+ setDirty(false);+ showToast('Saved');+ loadFiles();+ };++ const deleteFile = async (filename, e) => {+ e.stopPropagation();+ if (!confirm(`Delete ${filename}?`)) return;+ await fetch(`/api/knowledge/${encodeURIComponent(filename)}`, { method: 'DELETE' });+ if (activeFile === filename) { setActiveFile(null); setEditorContent(''); }+ showToast('Deleted');+ loadFiles();+ };++ const createFile = async () => {+ let name = newName.trim();+ if (!name) return;+ if (!name.endsWith('.md')) name += '.md';+ await fetch(`/api/knowledge/${encodeURIComponent(name)}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ content: `# ${name.replace('.md', '')}\n\n` }),+ });+ setNewName('');+ await loadFiles();+ // Open the new file+ const data = await (await fetch('/api/knowledge')).json();+ const created = data.find(f => f.filename === name);+ if (created) openFile(created);+ showToast('Created');+ };++ const handleDrop = async (e) => {+ e.preventDefault();+ setDragOver(false);+ const dt = e.dataTransfer;+ if (!dt.files.length) return;+ const fd = new FormData();+ for (const f of dt.files) {+ if (f.name.endsWith('.md') || f.name.endsWith('.txt')) fd.append('files', f);+ }+ if (!fd.has('files')) return;+ await fetch('/api/knowledge/upload', { method: 'POST', body: fd });+ showToast(`${dt.files.length} file(s) added`);+ loadFiles();+ };++ const handleFileInput = async (e) => {+ const inputFiles = e.target.files;+ if (!inputFiles.length) return;+ const fd = new FormData();+ for (const f of inputFiles) fd.append('files', f);+ await fetch('/api/knowledge/upload', { method: 'POST', body: fd });+ showToast(`${inputFiles.length} file(s) added`);+ loadFiles();+ e.target.value = '';+ };++ const realFiles = files.filter(f => f.filename !== 'README.md');++ return (+ <div className="app">+ <div className="nav">+ <a href="/" className="logo">pod<span>cli</span></a>+ <a href="/" className="nav-link">Back to app</a>+ </div>++ <div className="header">+ <h1>Knowledge Base</h1>+ <p className="subtitle">+ Add .md files to give the AI context about your podcast — hosts, style preferences, audience, topics to avoid.+ The MCP server reads these before every request.+ </p>+ {kbDir && <div className="dir-path">{kbDir}</div>}+ </div>++ {/* Drop zone */}+ <div+ className={`drop-zone ${dragOver ? 'drag-over' : ''}`}+ onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}+ onDragLeave={() => setDragOver(false)}+ onDrop={handleDrop}+ >+ <div className="dz-icon">{'\uD83D\uDCC4'}</div>+ <div className="dz-text">+ Drop <strong>.md files</strong> here or click to browse+ </div>+ <input type="file" accept=".md,.txt" multiple onChange={handleFileInput} />+ </div>++ {/* File grid */}+ {realFiles.length > 0 ? (+ <div className="file-grid">+ {realFiles.map(f => (+ <div+ key={f.filename}+ className={`file-card ${activeFile === f.filename ? 'active' : ''}`}+ onClick={() => openFile(f)}+ >+ <button className="file-delete" onClick={(e) => deleteFile(f.filename, e)}>{'\u00D7'}</button>+ <div className="file-name">{f.filename}</div>+ <div className="file-meta">{new Date(f.updatedAt).toLocaleDateString()}</div>+ <div className="file-preview">{f.content.split('\n').filter(l => l.trim() && !l.startsWith('#')).slice(0,2).join(' ')}</div>+ </div>+ ))}+ </div>+ ) : (+ <div className="empty-state">+ No knowledge files yet. Drop .md files above or create one below.+ </div>+ )}++ {/* New file */}+ <div className="new-file-row">+ <input+ className="new-file-input"+ placeholder="new-file-name.md"+ value={newName}+ onChange={e => setNewName(e.target.value)}+ onKeyDown={e => e.key === 'Enter' && createFile()}+ />+ <button className="btn btn-primary" onClick={createFile}>Create</button>+ </div>++ {/* Editor */}+ {activeFile && (+ <div className="editor-panel" style={{ animation: 'fadeIn 0.2s var(--ease)' }}>+ <div className="editor-header">+ <span className="editor-filename">{activeFile}</span>+ <div className="editor-actions">+ {dirty && <span style={{ fontSize: 11, color: 'var(--accent)', fontWeight: 600, padding: '4px 8px' }}>unsaved</span>}+ <button className="btn btn-ghost" onClick={() => { setActiveFile(null); setEditorContent(''); setDirty(false); }}>Close</button>+ <button className="btn btn-primary" onClick={saveFile}>Save</button>+ </div>+ </div>+ <textarea+ className="editor-textarea"+ value={editorContent}+ onChange={e => { setEditorContent(e.target.value); setDirty(true); }}+ />+ </div>+ )}++ {toast && <div className="toast">{toast}</div>}+ </div>+ );+ }++ ReactDOM.createRoot(document.getElementById('root')).render(<App />);+ </script>+</body>+</html>diff --git a/src/ui/web-server.ts b/src/ui/web-server.tsindex 4becd93..0de656f 100644--- a/src/ui/web-server.ts+++ b/src/ui/web-server.ts@@ -20,6 +20,9 @@ import { v4 as uuidv4 } from "uuid";import { PythonExecutor } from "../services/python-executor.js";import { TranscriptCache } from "../services/transcript-cache.js";import { FileManager } from "../services/file-manager.js";+import { AssetManager } from "../services/asset-manager.js";+import { ClipsHistory } from "../services/clips-history.js";+import { KnowledgeBase } from "../services/knowledge-base.js";import { paths } from "../config/paths.js";const __dirname = dirname(fileURLToPath(import.meta.url));@@ -30,6 +33,9 @@ const PORT = parseInt(process.env.PORT || "3847");const executor = new PythonExecutor();const cache = new TranscriptCache();const fileManager = new FileManager();+const assetManager = new AssetManager();+const clipsHistory = new ClipsHistory();+const knowledgeBase = new KnowledgeBase();// --- State ---// Track active jobs so the UI can poll progress@@ -317,11 +323,24 @@ app.post("/api/create-clip", async (req, res) => {job.message = event.message;})- .then((result) => {+ .then(async (result) => {job.status = "done";job.progress = 100;job.message = "Clip created!";job.result = result.data;+ // Record to history+ try {+ const d = result.data as any;+ await clipsHistory.record({+ source_video: video_path,+ start_second, end_second,+ caption_style, crop_strategy,+ logo_path: logo_path || undefined,+ title, output_path: d.output_path || "",+ file_size_mb: d.file_size_mb || 0,+ duration: d.duration || 0,+ });+ } catch {}}).catch((err) => {job.status = "error";@@ -365,11 +384,32 @@ app.post("/api/batch-clips", async (req, res) => {job.message = event.message;})- .then((result) => {+ .then(async (result) => {job.status = "done";job.progress = 100;job.message = "Batch complete!";job.result = result.data;+ // Record successful clips to history+ try {+ const d = result.data as any;+ if (d?.results) {+ for (const r of d.results) {+ if (r.status === "success" && r.output_path) {+ await clipsHistory.record({+ source_video: video_path,+ start_second: r.start_second || 0,+ end_second: r.end_second || 0,+ caption_style: r.caption_style || "hormozi",+ crop_strategy: r.crop_strategy || "center",+ title: r.title || "clip",+ output_path: r.output_path,+ file_size_mb: r.file_size_mb || 0,+ duration: r.duration || 0,+ });+ }+ }+ }+ } catch {}}).catch((err) => {job.status = "error";@@ -612,9 +652,141 @@ app.post("/api/presets", async (req, res) => {}});+// --- Assets ---+app.get("/api/assets", async (req, res) => {+ try {+ const items = await assetManager.list(req.query.type as string | undefined);+ res.json(items);+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++app.post("/api/assets/register", async (req, res) => {+ const { name, path: filePath, type = "other" } = req.body;+ try {+ const asset = await assetManager.register(name, filePath, type);+ res.json(asset);+ } catch (err: any) {+ res.status(400).json({ error: err.message });+ }+});++app.post("/api/assets/unregister", async (req, res) => {+ try {+ await assetManager.unregister(req.body.name);+ res.json({ ok: true });+ } catch (err: any) {+ res.json({ error: err.message });+ }+});++// --- Clip History ---+app.get("/api/history", async (req, res) => {+ try {+ const source = req.query.source as string | undefined;+ const limit = parseInt(req.query.limit as string) || 50;+ const entries = source+ ? await clipsHistory.getBySource(source)+ : await clipsHistory.list(limit);+ res.json(entries);+ } catch (err: any) {+ res.json([]);+ }+});++app.get("/api/history/check", async (req, res) => {+ try {+ const { source, start, end, style = "hormozi", crop = "center" } = req.query;+ if (!source || !start || !end) {+ res.json({ duplicate: null });+ return;+ }+ const dup = await clipsHistory.findDuplicate(+ source as string,+ parseFloat(start as string),+ parseFloat(end as string),+ style as string,+ crop as string+ );+ res.json({ duplicate: dup });+ } catch (err: any) {+ res.json({ duplicate: null });+ }+});++// --- Knowledge Base ---+app.get("/api/knowledge", async (_req, res) => {+ try {+ const files = await knowledgeBase.listFiles();+ res.json(files);+ } catch (err: any) {+ res.json([]);+ }+});++app.get("/api/knowledge/dir", (_req, res) => {+ res.json({ path: paths.knowledge });+});++// Knowledge file upload (drag & drop .md files) — must be before :filename routes+const knowledgeUpload = multer({+ storage: multer.diskStorage({+ destination: async (_req, _file, cb) => {+ await mkdir(paths.knowledge, { recursive: true });+ cb(null, paths.knowledge);+ },+ filename: (_req, file, cb) => cb(null, file.originalname),+ }),+ fileFilter: (_req, file, cb) => {+ if (file.originalname.endsWith(".md") || file.originalname.endsWith(".txt")) {+ cb(null, true);+ } else {+ cb(new Error("Only .md and .txt files are allowed"));+ }+ },+});++app.post("/api/knowledge/upload", knowledgeUpload.array("files", 50), (req, res) => {+ const files = req.files as Express.Multer.File[];+ if (!files || files.length === 0) {+ res.status(400).json({ error: "No files uploaded" });+ return;+ }+ res.json({ uploaded: files.map((f) => f.originalname) });+});++app.get("/api/knowledge/:filename", async (req, res) => {+ try {+ const content = await knowledgeBase.readFile(req.params.filename);+ res.json({ filename: req.params.filename, content });+ } catch (err: any) {+ res.status(404).json({ error: err.message });+ }+});++app.post("/api/knowledge/:filename", async (req, res) => {+ try {+ await knowledgeBase.writeFile(req.params.filename, req.body.content);+ res.json({ ok: true, filename: req.params.filename });+ } catch (err: any) {+ res.status(400).json({ error: err.message });+ }+});++app.delete("/api/knowledge/:filename", async (req, res) => {+ try {+ await knowledgeBase.deleteFile(req.params.filename);+ res.json({ ok: true });+ } catch (err: any) {+ res.json({ error: err.message });+ }+});+// --- Start ---async function main() {await fileManager.ensureDirectories();+ await knowledgeBase.ensureDir();await mkdir(uploadDir, { recursive: true });app.listen(PORT, () => {