@program-video/cli 0.1.12 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/commands/auth/login.ts","../src/lib/auth/credentials.ts","../src/lib/auth/device.ts","../src/lib/config.ts","../src/lib/output.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/commands/project/create.ts","../src/lib/auth/oauth.ts","../src/lib/convex.ts","../src/commands/project/get.ts","../src/commands/project/list.ts","../src/commands/workflow/list.ts","../src/commands/workflow/run.ts","../src/commands/workflow/status.ts","../src/commands/tool/execute.ts","../src/lib/agent-detect.ts","../src/commands/tool/list.ts","../src/commands/message/send.ts","../src/commands/message/list.ts","../src/commands/docs.ts","../src/commands/template/list.ts","../src/commands/template/get.ts","../src/lib/context.ts","../src/commands/template/create.ts","../src/commands/template/update.ts","../src/commands/template/remove.ts","../src/commands/template/run.ts","../src/commands/template/status.ts","../src/commands/template/use.ts","../src/commands/template/step/list.ts","../src/commands/template/step/info.ts","../src/commands/template/step/add.ts","../src/commands/template/step/remove.ts","../src/commands/template/step/update.ts","../src/commands/template/model/list.ts","../src/commands/template/model/schema.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { createRequire } from \"node:module\";\nimport { loginCommand } from \"./commands/auth/login.js\";\nimport type { LoginOptions } from \"./commands/auth/login.js\";\nimport { logoutCommand } from \"./commands/auth/logout.js\";\nimport type { LogoutOptions } from \"./commands/auth/logout.js\";\nimport { statusCommand as authStatusCommand } from \"./commands/auth/status.js\";\nimport type { StatusOptions as AuthStatusOptions } from \"./commands/auth/status.js\";\nimport { createCommand as projectCreateCommand } from \"./commands/project/create.js\";\nimport type { CreateOptions } from \"./commands/project/create.js\";\nimport { getCommand as projectGetCommand } from \"./commands/project/get.js\";\nimport type { GetOptions } from \"./commands/project/get.js\";\nimport { listCommand as projectListCommand } from \"./commands/project/list.js\";\nimport type { ListOptions as ProjectListOptions } from \"./commands/project/list.js\";\nimport { listCommand as workflowListCommand } from \"./commands/workflow/list.js\";\nimport type { ListOptions as WorkflowListOptions } from \"./commands/workflow/list.js\";\nimport { runCommand as workflowRunCommand } from \"./commands/workflow/run.js\";\nimport type { RunOptions } from \"./commands/workflow/run.js\";\nimport { statusCommand as workflowStatusCommand } from \"./commands/workflow/status.js\";\nimport type { StatusOptions as WorkflowStatusOptions } from \"./commands/workflow/status.js\";\nimport { executeCommand as toolExecuteCommand } from \"./commands/tool/execute.js\";\nimport type { ExecuteOptions } from \"./commands/tool/execute.js\";\nimport { listCommand as toolListCommand } from \"./commands/tool/list.js\";\nimport type { ListOptions as ToolListOptions } from \"./commands/tool/list.js\";\nimport { sendCommand as messageSendCommand } from \"./commands/message/send.js\";\nimport type { SendMessageOptions } from \"./commands/message/send.js\";\nimport { listCommand as messageListCommand } from \"./commands/message/list.js\";\nimport type { ListMessageOptions } from \"./commands/message/list.js\";\nimport { docsCommand } from \"./commands/docs.js\";\nimport type { DocsOptions } from \"./commands/docs.js\";\n\n// Template command imports\nimport { listCommand as templateListCommand } from \"./commands/template/list.js\";\nimport type { ListOptions as TemplateListOptions } from \"./commands/template/list.js\";\nimport { getCommand as templateGetCommand } from \"./commands/template/get.js\";\nimport type { GetOptions as TemplateGetOptions } from \"./commands/template/get.js\";\nimport { createCommand as templateCreateCommand } from \"./commands/template/create.js\";\nimport type { CreateOptions as TemplateCreateOptions } from \"./commands/template/create.js\";\nimport { updateCommand as templateUpdateCommand } from \"./commands/template/update.js\";\nimport type { UpdateOptions as TemplateUpdateOptions } from \"./commands/template/update.js\";\nimport { removeCommand as templateRemoveCommand } from \"./commands/template/remove.js\";\nimport type { RemoveOptions as TemplateRemoveOptions } from \"./commands/template/remove.js\";\nimport { runCommand as templateRunCommand } from \"./commands/template/run.js\";\nimport type { RunOptions as TemplateRunOptions } from \"./commands/template/run.js\";\nimport { statusCommand as templateStatusCommand } from \"./commands/template/status.js\";\nimport type { StatusOptions as TemplateStatusOptions } from \"./commands/template/status.js\";\nimport { useCommand as templateUseCommand } from \"./commands/template/use.js\";\nimport type { UseOptions as TemplateUseOptions } from \"./commands/template/use.js\";\n\n// Template step command imports\nimport { stepListCommand } from \"./commands/template/step/list.js\";\nimport type { StepListOptions } from \"./commands/template/step/list.js\";\nimport { stepInfoCommand } from \"./commands/template/step/info.js\";\nimport type { StepInfoOptions } from \"./commands/template/step/info.js\";\nimport { stepAddCommand } from \"./commands/template/step/add.js\";\nimport type { StepAddOptions } from \"./commands/template/step/add.js\";\nimport { stepRemoveCommand } from \"./commands/template/step/remove.js\";\nimport type { StepRemoveOptions } from \"./commands/template/step/remove.js\";\nimport { stepUpdateCommand } from \"./commands/template/step/update.js\";\nimport type { StepUpdateOptions } from \"./commands/template/step/update.js\";\n\n// Template model command imports\nimport { modelListCommand } from \"./commands/template/model/list.js\";\nimport type { ModelListOptions } from \"./commands/template/model/list.js\";\nimport { modelSchemaCommand } from \"./commands/template/model/schema.js\";\nimport type { ModelSchemaOptions } from \"./commands/template/model/schema.js\";\n\nconst program = new Command();\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as { version: string };\n\nprogram\n .name(\"program\")\n .description(\"CLI for the Program video creation platform\")\n .version(packageJson.version);\n\n// Auth commands\nconst auth = program.command(\"auth\").description(\"Authentication commands\");\n\nauth\n .command(\"login\")\n .description(\"Authenticate with the Program platform\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: LoginOptions) => {\n await loginCommand(options);\n });\n\nauth\n .command(\"logout\")\n .description(\"Log out from the Program platform\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: LogoutOptions) => {\n logoutCommand(options);\n });\n\nauth\n .command(\"status\")\n .description(\"Check authentication status\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: AuthStatusOptions) => {\n authStatusCommand(options);\n });\n\n// Project commands\nconst project = program.command(\"project\").description(\"Project management commands\");\n\nproject\n .command(\"create\")\n .description(\"Create a new project\")\n .option(\"--title <title>\", \"Project title\")\n .option(\"--description <description>\", \"Project description\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: CreateOptions) => {\n await projectCreateCommand(options);\n });\n\nproject\n .command(\"list\")\n .description(\"List projects\")\n .option(\"--limit <limit>\", \"Maximum number of projects to return\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ProjectListOptions) => {\n await projectListCommand(options);\n });\n\nproject\n .command(\"get <id>\")\n .description(\"Get project details including composition\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: GetOptions) => {\n await projectGetCommand(id, options);\n });\n\n// Workflow commands (deprecated — use 'template' commands instead)\nconst workflow = program.command(\"workflow\").description(\"Workflow template commands (use 'template' for full management)\");\n\nworkflow\n .command(\"list\")\n .description(\"List available workflow templates\")\n .option(\"--limit <limit>\", \"Maximum number of templates to return\", parseInt)\n .option(\"--public-only\", \"Only show public templates\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: WorkflowListOptions) => {\n await workflowListCommand(options);\n });\n\nworkflow\n .command(\"run <templateId>\")\n .description(\"Execute a workflow template\")\n .option(\"--project <projectId>\", \"Project ID to associate with execution\")\n .option(\"--input <json>\", \"JSON input for the workflow\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (templateId: string, options: RunOptions) => {\n await workflowRunCommand(templateId, options);\n });\n\nworkflow\n .command(\"status <executionId>\")\n .description(\"Check workflow execution status\")\n .option(\"--watch\", \"Continuously poll for status updates\")\n .option(\"--interval <ms>\", \"Poll interval in milliseconds\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action(async (executionId: string, options: WorkflowStatusOptions) => {\n await workflowStatusCommand(executionId, options);\n });\n\n// Template commands\nconst template = program.command(\"template\").description(\"Template management commands\");\n\ntemplate\n .command(\"list\")\n .description(\"List templates\")\n .option(\"--public-only\", \"Only show public templates\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: TemplateListOptions) => {\n await templateListCommand(options);\n });\n\ntemplate\n .command(\"get [id]\")\n .description(\"Get template details (uses active template if no ID)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateGetOptions) => {\n await templateGetCommand(id, options);\n });\n\ntemplate\n .command(\"create\")\n .description(\"Create a new template (auto-sets as active)\")\n .requiredOption(\"--name <name>\", \"Template name\")\n .option(\"--description <description>\", \"Template description\")\n .option(\"--public\", \"Make template public\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: TemplateCreateOptions) => {\n await templateCreateCommand(options);\n });\n\ntemplate\n .command(\"update [id]\")\n .description(\"Update template metadata (uses active template if no ID)\")\n .option(\"--name <name>\", \"New template name\")\n .option(\"--description <description>\", \"New template description\")\n .option(\"--public\", \"Make template public\")\n .option(\"--steps <json>\", \"Replace steps array with JSON\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateUpdateOptions) => {\n await templateUpdateCommand(id, options);\n });\n\ntemplate\n .command(\"remove [id]\")\n .description(\"Delete a template (uses active template if no ID)\")\n .option(\"--force\", \"Skip confirmation prompt\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateRemoveOptions) => {\n await templateRemoveCommand(id, options);\n });\n\ntemplate\n .command(\"run [id]\")\n .description(\"Execute a template (uses active template if no ID)\")\n .option(\"--project <projectId>\", \"Project ID to associate with execution\")\n .option(\"--input <json>\", \"JSON input for the workflow\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateRunOptions) => {\n await templateRunCommand(id, options);\n });\n\ntemplate\n .command(\"status <executionId>\")\n .description(\"Check execution status\")\n .option(\"--watch\", \"Continuously poll for status updates\")\n .option(\"--interval <ms>\", \"Poll interval in milliseconds\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action(async (executionId: string, options: TemplateStatusOptions) => {\n await templateStatusCommand(executionId, options);\n });\n\ntemplate\n .command(\"use <id>\")\n .description(\"Set the active template context\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: TemplateUseOptions) => {\n await templateUseCommand(id, options);\n });\n\n// Template step subgroup\nconst step = template.command(\"step\").description(\"Manage template steps and discover step types\");\n\nstep\n .command(\"list\")\n .description(\"List available step types\")\n .option(\"--category <category>\", \"Filter by category\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: StepListOptions) => {\n await stepListCommand(options);\n });\n\nstep\n .command(\"info <stepType>\")\n .description(\"Show step type details (inputs, outputs)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (stepType: string, options: StepInfoOptions) => {\n await stepInfoCommand(stepType, options);\n });\n\nstep\n .command(\"add <stepType>\")\n .description(\"Add a step to the active template\")\n .option(\"--config <json>\", \"Step configuration as JSON\")\n .option(\"--at <position>\", \"Insert at position (0-indexed)\", parseInt)\n .option(\"--after <id>\", \"Insert after step with this ID\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (stepType: string, options: StepAddOptions) => {\n await stepAddCommand(stepType, options);\n });\n\nstep\n .command(\"remove <id>\")\n .description(\"Remove a step by its instance ID\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: StepRemoveOptions) => {\n await stepRemoveCommand(id, options);\n });\n\nstep\n .command(\"update <id>\")\n .description(\"Update a step's config by its instance ID\")\n .option(\"--config <json>\", \"Config to merge as JSON\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: StepUpdateOptions) => {\n await stepUpdateCommand(id, options);\n });\n\n// Template model subgroup\nconst model = template.command(\"model\").description(\"Browse models and schemas\");\n\nmodel\n .command(\"list <category>\")\n .description(\"List models for a category (image, video, speech, text)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (category: string, options: ModelListOptions) => {\n await modelListCommand(category, options);\n });\n\nmodel\n .command(\"schema <modelId>\")\n .description(\"Show full input schema for a model\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (modelId: string, options: ModelSchemaOptions) => {\n await modelSchemaCommand(modelId, options);\n });\n\n// Tool commands (direct agent tool access)\nconst tool = program.command(\"tool\").description(\"Execute agent tools directly\");\ntool.addHelpText(\n \"after\",\n `\nAgent Hint:\n Start with:\n program tool exec assessComposition --project <projectId> --params '{}'\n Then inspect models before generation:\n program tool exec listImageModels --project <projectId> --params '{}'\n program tool exec listSpeechModels --project <projectId> --params '{}'`,\n);\n\ntool\n .command(\"list\")\n .description(\"List available agent tools\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ToolListOptions) => {\n await toolListCommand(options);\n });\n\nconst toolExec = tool\n .command(\"exec <toolName>\")\n .description(\"Execute an agent tool\")\n .requiredOption(\"--project <projectId>\", \"Project ID to execute tool against\")\n .option(\"--params <json>\", \"JSON parameters for the tool\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (toolName: string, options: ExecuteOptions) => {\n await toolExecuteCommand(toolName, options);\n });\n\ntoolExec.addHelpText(\n \"after\",\n `\nUpload examples:\n Path-based upload (recommended for larger files):\n program tool exec uploadFile --project <projectId> --params '{\"path\":\"/tmp/recording.mp4\",\"category\":\"video\"}'\n Base64 upload:\n program tool exec uploadFile --project <projectId> --params '{\"fileName\":\"notes.txt\",\"mimeType\":\"text/plain\",\"dataBase64\":\"SGVsbG8=\"}'`,\n);\n\n// Message commands (send and list messages in project chat)\nconst message = program.command(\"message\").description(\"Manage messages in project chat\");\n\nmessage\n .command(\"list\")\n .description(\"List messages in the project chat\")\n .requiredOption(\"--project <projectId>\", \"Project ID to list messages from\")\n .option(\"--limit <limit>\", \"Maximum number of messages to return\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ListMessageOptions) => {\n await messageListCommand(options);\n });\n\nmessage\n .command(\"send <text>\")\n .description(\n \"Log a text message to the project chat. NOTE: This only adds a message to the chat history - it does NOT trigger the AI agent. To perform actions, use 'tool exec' instead.\",\n )\n .requiredOption(\"--project <projectId>\", \"Project ID to send message to\")\n .option(\"--role <role>\", \"Message role: user or assistant (default: assistant)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (text: string, options: SendMessageOptions) => {\n await messageSendCommand(text, options);\n });\n\n// Docs command\nprogram\n .command(\"docs\")\n .description(\"Display CLI documentation and command schema\")\n .option(\"--schema\", \"Output full command schema as JSON\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: DocsOptions) => {\n docsCommand(options);\n });\n\n// Parse arguments\nprogram.parse();\n","import chalk from \"chalk\";\nimport open from \"open\";\nimport ora from \"ora\";\nimport { startDeviceAuth } from \"../../lib/auth/device.js\";\nimport { oauthConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\n\nexport type LoginOptions = OutputOptions;\n\n/**\n * Format user code with dash for readability (ABCD1234 -> ABCD-1234)\n */\nfunction formatUserCode(code: string): string {\n if (code.length === 8) {\n return `${code.slice(0, 4)}-${code.slice(4)}`;\n }\n return code;\n}\n\n/**\n * Device authorization flow - works everywhere including headless environments\n * User visits a URL on any device and enters the code shown in the terminal\n */\nexport async function loginCommand(options: LoginOptions): Promise<void> {\n const showSpinner = process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Requesting device code...\").start() : null;\n\n try {\n const deviceAuth = await startDeviceAuth(oauthConfig);\n spinner?.stop();\n spinner?.clear();\n\n // Try to open the browser automatically (use base URL, not the one with code embedded)\n // User must manually enter the code for security\n void open(deviceAuth.verificationUrl).catch(() => {\n // Silently ignore - URL is displayed below for manual access\n });\n\n // Always display the code and URL (essential for agents/headless environments)\n console.log();\n console.log(chalk.bold(\" Sign in to Program\"));\n console.log();\n console.log(` URL: ${chalk.cyan(deviceAuth.verificationUrl)}`);\n console.log(` Code: ${chalk.bold.yellow(formatUserCode(deviceAuth.userCode))}`);\n console.log();\n console.log(chalk.dim(\" Enter the code above in your browser to authorize.\"));\n console.log();\n\n const waitingSpinner = showSpinner ? ora(\"Waiting for authorization...\").start() : null;\n\n // Poll until the user completes auth\n const credentials = await deviceAuth.pollForCompletion();\n\n waitingSpinner?.stop();\n waitingSpinner?.clear();\n\n if (options.json) {\n outputSuccess(\n {\n authenticated: true,\n email: credentials.email,\n userId: credentials.userId,\n organizationId: credentials.organizationId,\n },\n options\n );\n } else {\n console.log(formatSuccess(`Authenticated as ${chalk.cyan(credentials.email)}`));\n if (credentials.organizationId) {\n console.log(chalk.dim(` Organization: ${credentials.organizationId}`));\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Authentication failed\";\n outputError(message, options);\n process.exit(1);\n }\n}\n","import Conf from \"conf\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\n\nexport interface Credentials {\n accessToken: string;\n refreshToken: string;\n expiresAt: number;\n userId: string;\n organizationId: string;\n email: string;\n}\n\n// Use ~/.program/ for credentials storage\nconst CREDENTIALS_DIR = path.join(os.homedir(), \".program\");\nconst CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, \"credentials.json\");\n\n// Ensure directory exists with proper permissions\nfunction ensureCredentialsDir(): void {\n if (!fs.existsSync(CREDENTIALS_DIR)) {\n fs.mkdirSync(CREDENTIALS_DIR, { mode: 0o700, recursive: true });\n }\n}\n\n// Using conf for secure credential storage with automatic file permissions\nconst store = new Conf<{ credentials: Credentials | null }>({\n projectName: \"program-cli\",\n cwd: CREDENTIALS_DIR,\n configName: \"credentials\",\n fileExtension: \"json\",\n defaults: {\n credentials: null,\n },\n});\n\nexport function saveCredentials(credentials: Credentials): void {\n ensureCredentialsDir();\n store.set(\"credentials\", credentials);\n\n // Ensure file has restrictive permissions (owner read/write only)\n try {\n fs.chmodSync(CREDENTIALS_FILE, 0o600);\n } catch {\n // Ignore chmod errors on Windows\n }\n}\n\nexport function getCredentials(): Credentials | null {\n return store.get(\"credentials\");\n}\n\nexport function clearCredentials(): void {\n store.delete(\"credentials\");\n}\n\nexport function isAuthenticated(): boolean {\n const creds = getCredentials();\n if (!creds) return false;\n\n // Check if token is expired (with 5 minute buffer)\n const now = Date.now();\n const expiresAt = creds.expiresAt * 1000; // Convert to milliseconds\n const bufferMs = 5 * 60 * 1000; // 5 minutes\n\n return now < expiresAt - bufferMs;\n}\n\nexport function needsRefresh(): boolean {\n const creds = getCredentials();\n if (!creds) return false;\n\n // Needs refresh if within 5 minutes of expiry\n const now = Date.now();\n const expiresAt = creds.expiresAt * 1000;\n const bufferMs = 5 * 60 * 1000;\n\n return now >= expiresAt - bufferMs && now < expiresAt;\n}\n","import { saveCredentials, getCredentials } from \"./credentials.js\";\nimport type { Credentials } from \"./credentials.js\";\n\n// OAuth client ID - same as the main oauth.ts\nconst CLIENT_ID = \"program-cli\";\nconst SCOPES = [\"openid\", \"profile\", \"email\", \"offline_access\"];\n\nexport interface DeviceAuthConfig {\n baseUrl: string;\n}\n\ninterface DeviceCodeResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n expires_in: number;\n interval: number;\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n token_type?: string;\n scope?: string;\n}\n\ninterface TokenErrorResponse {\n error: string;\n error_description?: string;\n}\n\ninterface UserInfo {\n id: string;\n email: string;\n name: string;\n organizationId?: string;\n}\n\n/**\n * Request a device code from the server\n */\nexport async function requestDeviceCode(\n config: DeviceAuthConfig\n): Promise<DeviceCodeResponse> {\n const url = new URL(\"/api/auth/device/code\", config.baseUrl);\n\n const response = await fetch(url.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n client_id: CLIENT_ID,\n scope: SCOPES.join(\" \"),\n }),\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Failed to get device code: ${response.status} ${errorText}`);\n }\n\n return response.json() as Promise<DeviceCodeResponse>;\n}\n\n/**\n * Poll for the token after user authorizes\n * Returns the token response or an error code\n */\nexport async function pollForToken(\n config: DeviceAuthConfig,\n deviceCode: string\n): Promise<TokenResponse | TokenErrorResponse> {\n const url = new URL(\"/api/auth/device/token\", config.baseUrl);\n\n const response = await fetch(url.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: deviceCode,\n client_id: CLIENT_ID,\n }),\n });\n\n // Device flow uses 400 status for pending/slow_down errors\n const data = (await response.json()) as TokenResponse | TokenErrorResponse;\n\n if (!response.ok) {\n // Check if it's an expected error (authorization_pending, slow_down)\n if (\"error\" in data) {\n return data;\n }\n throw new Error(`Token request failed: ${response.status}`);\n }\n\n return data as TokenResponse;\n}\n\n/**\n * Get user info from the BetterAuth session endpoint\n * Device authorization returns a BetterAuth token, not an OIDC token\n */\nasync function getUserInfo(\n config: DeviceAuthConfig,\n accessToken: string\n): Promise<UserInfo> {\n // Use the BetterAuth get-session endpoint with Bearer token\n const sessionUrl = new URL(\"/api/auth/get-session\", config.baseUrl);\n\n const response = await fetch(sessionUrl.toString(), {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!response.ok) {\n // Try the token/session endpoint if get-session doesn't work\n const tokenUrl = new URL(\"/api/auth/token\", config.baseUrl);\n const tokenResponse = await fetch(tokenUrl.toString(), {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n if (!tokenResponse.ok) {\n throw new Error(`Failed to get user info: ${response.status}`);\n }\n\n const tokenData = (await tokenResponse.json()) as {\n user?: { id?: string; email?: string; name?: string };\n session?: { activeOrganizationId?: string };\n };\n\n if (!tokenData.user?.id || !tokenData.user.email) {\n throw new Error(\"Invalid token response: missing user info\");\n }\n\n return {\n id: tokenData.user.id,\n email: tokenData.user.email,\n name: tokenData.user.name ?? tokenData.user.email,\n organizationId: tokenData.session?.activeOrganizationId,\n };\n }\n\n const data = (await response.json()) as {\n user?: {\n id?: string;\n email?: string;\n name?: string;\n };\n session?: {\n activeOrganizationId?: string;\n };\n };\n\n if (!data.user?.id || !data.user.email) {\n throw new Error(\"Invalid session response: missing user info\");\n }\n\n return {\n id: data.user.id,\n email: data.user.email,\n name: data.user.name ?? data.user.email,\n organizationId: data.session?.activeOrganizationId,\n };\n}\n\n/**\n * Start the device authorization flow\n * Returns display info for the CLI to show the user\n */\nexport interface DeviceAuthDisplay {\n userCode: string;\n verificationUrl: string;\n verificationUrlComplete?: string;\n expiresIn: number;\n interval: number;\n pollForCompletion: () => Promise<Credentials>;\n}\n\nexport async function startDeviceAuth(\n config: DeviceAuthConfig\n): Promise<DeviceAuthDisplay> {\n const deviceCode = await requestDeviceCode(config);\n\n return {\n userCode: deviceCode.user_code,\n verificationUrl: deviceCode.verification_uri,\n verificationUrlComplete: deviceCode.verification_uri_complete,\n expiresIn: deviceCode.expires_in,\n interval: deviceCode.interval,\n pollForCompletion: async () => {\n return pollUntilComplete(config, deviceCode);\n },\n };\n}\n\n/**\n * Poll until the user completes authorization or the code expires\n */\nasync function pollUntilComplete(\n config: DeviceAuthConfig,\n deviceCode: DeviceCodeResponse\n): Promise<Credentials> {\n const startTime = Date.now();\n const expiresAt = startTime + deviceCode.expires_in * 1000;\n let interval = deviceCode.interval * 1000;\n\n while (Date.now() < expiresAt) {\n // Wait for the interval before polling\n await new Promise((resolve) => setTimeout(resolve, interval));\n\n const result = await pollForToken(config, deviceCode.device_code);\n\n // Check if it's an error response\n if (\"error\" in result) {\n switch (result.error) {\n case \"authorization_pending\":\n // User hasn't completed authorization yet, continue polling\n continue;\n\n case \"slow_down\":\n // Server asked us to slow down, increase interval\n interval += 5000;\n continue;\n\n case \"expired_token\":\n throw new Error(\"Device code expired. Please start a new login.\");\n\n case \"access_denied\":\n throw new Error(\"Access denied. You denied the authorization request.\");\n\n default:\n throw new Error(\n result.error_description ?? `Authorization failed: ${result.error}`\n );\n }\n }\n\n // Success! We got tokens\n const tokens = result;\n\n // Get user info\n const userInfo = await getUserInfo(config, tokens.access_token);\n\n // Calculate expiry timestamp (default to 1 hour if not provided)\n const expiresIn = tokens.expires_in ?? 3600;\n const expiresAtTimestamp = Math.floor(Date.now() / 1000) + expiresIn;\n\n // Save credentials (refresh token may not be present for device flow)\n const credentials: Credentials = {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? \"\",\n expiresAt: expiresAtTimestamp,\n userId: userInfo.id,\n organizationId: userInfo.organizationId ?? \"\",\n email: userInfo.email,\n };\n\n saveCredentials(credentials);\n\n return credentials;\n }\n\n throw new Error(\"Device code expired. Please start a new login.\");\n}\n\n/**\n * Check if we have valid credentials\n */\nexport function hasValidCredentials(): boolean {\n const creds = getCredentials();\n if (!creds) return false;\n\n // Check if token is expired (with 5 min buffer)\n const now = Date.now();\n const expiresAt = creds.expiresAt * 1000;\n const bufferMs = 5 * 60 * 1000;\n\n return now < expiresAt - bufferMs;\n}\n","import type { OAuthConfig } from \"./auth/index.js\";\nimport type { ConvexConfig } from \"./convex.js\";\n\n// Production URLs - hardcoded to prevent credential theft via env var manipulation\nexport const BASE_URL = \"https://program.video\";\n\n// Convex deployment URL (production)\nexport const CONVEX_URL = \"https://keen-eel-920.convex.cloud\";\n\nexport const oauthConfig: OAuthConfig = {\n baseUrl: BASE_URL,\n};\n\nexport const convexConfig: ConvexConfig = {\n convexUrl: CONVEX_URL,\n oauthConfig,\n};\n","import chalk from \"chalk\";\n\nexport interface OutputOptions {\n json?: boolean;\n}\n\nexport interface SuccessResult<T> {\n success: true;\n data: T;\n}\n\nexport interface ErrorResult {\n success: false;\n error: string;\n}\n\nexport type Result<T> = SuccessResult<T> | ErrorResult;\n\n/**\n * Output a success result in the appropriate format\n */\nexport function outputSuccess<T>(data: T, options: OutputOptions = {}): void {\n if (options.json) {\n const result: SuccessResult<T> = { success: true, data };\n console.log(JSON.stringify(result, null, 2));\n } else {\n // For human-readable output, we'll handle this per-command\n // This is a fallback that just pretty-prints\n console.log(data);\n }\n}\n\n/**\n * Output an error result in the appropriate format\n */\nexport function outputError(error: string, options: OutputOptions = {}): void {\n if (options.json) {\n const result: ErrorResult = { success: false, error };\n console.log(JSON.stringify(result, null, 2));\n } else {\n console.error(chalk.red(\"Error:\"), error);\n }\n}\n\n/**\n * Format a table for human-readable output\n */\nexport function formatTable(\n headers: string[],\n rows: string[][],\n options: { indent?: number } = {}\n): string {\n const indent = \" \".repeat(options.indent ?? 0);\n\n // Calculate column widths\n const widths = headers.map((h, i) => {\n const maxRow = Math.max(...rows.map((r) => (r[i] ?? \"\").length));\n return Math.max(h.length, maxRow);\n });\n\n // Format header\n const headerLine = headers\n .map((h, i) => chalk.bold(h.padEnd(widths[i] ?? 0)))\n .join(\" \");\n\n // Format separator\n const separator = widths.map((w) => \"-\".repeat(w)).join(\" \");\n\n // Format rows\n const formattedRows = rows.map((row) =>\n row.map((cell, i) => (cell || \"\").padEnd(widths[i] ?? 0)).join(\" \")\n );\n\n return [indent + headerLine, indent + separator, ...formattedRows.map((r) => indent + r)].join(\n \"\\n\"\n );\n}\n\n/**\n * Format a key-value list for human-readable output\n */\nexport function formatKeyValue(\n items: { key: string; value: string }[],\n options: { indent?: number } = {}\n): string {\n const indent = \" \".repeat(options.indent ?? 0);\n const maxKeyLength = Math.max(...items.map((item) => item.key.length));\n\n return items\n .map(\n (item) =>\n indent + chalk.dim(item.key.padEnd(maxKeyLength) + \":\") + \" \" + item.value\n )\n .join(\"\\n\");\n}\n\n/**\n * Format a success message\n */\nexport function formatSuccess(message: string): string {\n return chalk.green(\"✓\") + \" \" + message;\n}\n\n/**\n * Format a warning message\n */\nexport function formatWarning(message: string): string {\n return chalk.yellow(\"⚠\") + \" \" + message;\n}\n\n/**\n * Format an info message\n */\nexport function formatInfo(message: string): string {\n return chalk.blue(\"ℹ\") + \" \" + message;\n}\n","import { clearCredentials, getCredentials } from \"../../lib/auth/credentials.js\";\nimport { formatSuccess, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport type LogoutOptions = OutputOptions;\n\nexport function logoutCommand(options: LogoutOptions): void {\n const credentials = getCredentials();\n\n if (!credentials) {\n if (options.json) {\n outputSuccess({ loggedOut: true, wasAuthenticated: false }, options);\n } else {\n console.log(\"Not currently logged in.\");\n }\n return;\n }\n\n const email = credentials.email;\n clearCredentials();\n\n if (options.json) {\n outputSuccess({ loggedOut: true, wasAuthenticated: true, email }, options);\n } else {\n console.log(formatSuccess(`Logged out from ${email}`));\n }\n}\n","import chalk from \"chalk\";\nimport { getCredentials, isAuthenticated, needsRefresh } from \"../../lib/auth/credentials.js\";\nimport { formatKeyValue, formatSuccess, formatWarning, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport type StatusOptions = OutputOptions;\n\nexport function statusCommand(options: StatusOptions): void {\n const credentials = getCredentials();\n\n if (!credentials) {\n if (options.json) {\n outputSuccess({ authenticated: false }, options);\n } else {\n console.log(\"Not logged in. Run 'program auth login' to authenticate.\");\n }\n return;\n }\n\n const authenticated = isAuthenticated();\n const expiresAt = credentials.expiresAt;\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = expiresAt - now;\n\n if (options.json) {\n outputSuccess(\n {\n authenticated,\n user: credentials.email,\n userId: credentials.userId,\n organizationId: credentials.organizationId,\n expiresAt,\n expiresIn,\n needsRefresh: needsRefresh(),\n },\n options\n );\n } else {\n if (!authenticated) {\n console.log(formatWarning(\"Token expired. Run 'program auth login' to re-authenticate.\"));\n return;\n }\n\n console.log(formatSuccess(\"Logged in\"));\n console.log();\n console.log(\n formatKeyValue([\n { key: \"Email\", value: credentials.email },\n { key: \"User ID\", value: credentials.userId },\n { key: \"Organization\", value: credentials.organizationId || chalk.dim(\"(none)\") },\n { key: \"Token expires\", value: formatExpiresIn(expiresIn) },\n ])\n );\n }\n}\n\nfunction formatExpiresIn(seconds: number): string {\n if (seconds <= 0) {\n return chalk.red(\"expired\");\n }\n\n if (seconds < 60) {\n return chalk.yellow(`in ${seconds} seconds`);\n }\n\n if (seconds < 3600) {\n const minutes = Math.floor(seconds / 60);\n return chalk.green(`in ${minutes} minute${minutes === 1 ? \"\" : \"s\"}`);\n }\n\n const hours = Math.floor(seconds / 3600);\n const minutes = Math.floor((seconds % 3600) / 60);\n return chalk.green(`in ${hours}h ${minutes}m`);\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport interface CreateOptions extends OutputOptions {\n title?: string;\n description?: string;\n}\n\ninterface CreateResult {\n id: string;\n title: string;\n}\n\nexport async function createCommand(options: CreateOptions): Promise<void> {\n // Only show spinner in TTY environments (not through npx/pipes)\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Creating project...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.mutation<string>(\"projects.create\", {\n title: options.title,\n description: options.description,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to create project\", options);\n process.exit(1);\n }\n\n const projectData: CreateResult = {\n id: result.data,\n title: options.title ?? \"Untitled Project\",\n };\n\n if (options.json) {\n outputSuccess(projectData, options);\n } else {\n console.log(formatSuccess(`Created project ${chalk.cyan(projectData.title)}`));\n console.log(chalk.dim(` ID: ${projectData.id}`));\n }\n}\n","import { getCredentials } from \"./credentials.js\";\n\nexport interface OAuthConfig {\n baseUrl: string;\n}\n\n/**\n * Ensure we have a valid access token.\n * For device auth, we don't refresh - user must re-authenticate if expired.\n */\nexport function ensureValidToken(_config: OAuthConfig): string | null {\n const creds = getCredentials();\n if (!creds) {\n return null;\n }\n\n const now = Date.now();\n const expiresAt = creds.expiresAt * 1000;\n const bufferMs = 5 * 60 * 1000; // 5 minutes\n\n // If token is still valid, return it\n if (now < expiresAt - bufferMs) {\n return creds.accessToken;\n }\n\n // Token expired - user needs to re-authenticate\n return null;\n}\n","import { getCredentials, ensureValidToken } from \"./auth/index.js\";\nimport type {OAuthConfig} from \"./auth/index.js\";\n\nexport interface ConvexConfig {\n convexUrl: string;\n oauthConfig: OAuthConfig;\n}\n\nexport interface ConvexResponse<T> {\n success: boolean;\n data?: T;\n error?: string;\n}\n\n/**\n * Create a Convex HTTP client for calling Convex functions via the CLI gateway\n */\nexport function createConvexClient(config: ConvexConfig) {\n const { convexUrl } = config;\n\n // The CLI gateway is on the .convex.site endpoint\n const gatewayUrl = convexUrl.replace(\".convex.cloud\", \".convex.site\");\n\n /**\n * Call a Convex query function via the CLI gateway\n */\n async function query<T>(\n functionPath: string,\n args: Record<string, unknown> = {}\n ): Promise<ConvexResponse<T>> {\n return callGateway<T>(functionPath, args);\n }\n\n /**\n * Call a Convex mutation function via the CLI gateway\n */\n async function mutation<T>(\n functionPath: string,\n args: Record<string, unknown> = {}\n ): Promise<ConvexResponse<T>> {\n return callGateway<T>(functionPath, args);\n }\n\n /**\n * Call a Convex action function via the CLI gateway\n */\n async function action<T>(\n functionPath: string,\n args: Record<string, unknown> = {}\n ): Promise<ConvexResponse<T>> {\n return callGateway<T>(functionPath, args);\n }\n\n /**\n * Call the CLI gateway with OAuth authentication\n */\n async function callGateway<T>(\n functionPath: string,\n args: Record<string, unknown>\n ): Promise<ConvexResponse<T>> {\n // Get valid access token\n const accessToken = ensureValidToken(config.oauthConfig);\n if (!accessToken) {\n return {\n success: false,\n error: \"Not authenticated. Run 'program auth login' first.\",\n };\n }\n\n // Build the gateway URL\n const url = new URL(\"/cli\", gatewayUrl);\n\n try {\n const response = await fetch(url.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n fn: functionPath,\n params: args,\n }),\n });\n\n const result = (await response.json()) as {\n success: boolean;\n data?: T;\n error?: string;\n };\n\n if (!response.ok || !result.success) {\n return {\n success: false,\n error: result.error ?? `Gateway error: ${response.status}`,\n };\n }\n\n return { success: true, data: result.data };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : \"Unknown error\",\n };\n }\n }\n\n /**\n * Get the current credentials (for checking auth status)\n */\n function getAuth() {\n return getCredentials();\n }\n\n return {\n query,\n mutation,\n action,\n getAuth,\n };\n}\n\nexport type ConvexClient = ReturnType<typeof createConvexClient>;\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatKeyValue, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport type GetOptions = OutputOptions;\n\ninterface ProjectWithComposition {\n _id: string;\n title: string;\n description?: string;\n createdAt: number;\n updatedAt: number;\n latestVersion: {\n _id: string;\n version: number;\n compositionId: string;\n createdAt: number;\n } | null;\n composition: {\n _id: string;\n title: string;\n description?: string;\n duration: number;\n fps: number;\n width: number;\n height: number;\n sceneCount: number;\n scenes: unknown[];\n } | null;\n}\n\nexport async function getCommand(projectId: string, options: GetOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching project...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<ProjectWithComposition>(\"projects.byId\", {\n id: projectId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to get project\", options);\n process.exit(1);\n }\n\n const project = result.data;\n\n if (options.json) {\n outputSuccess(project, options);\n } else {\n console.log(chalk.bold(project.title || \"Untitled Project\"));\n if (project.description) {\n console.log(chalk.dim(project.description));\n }\n console.log();\n\n console.log(\n formatKeyValue([\n { key: \"ID\", value: project._id },\n { key: \"Created\", value: new Date(project.createdAt).toLocaleString() },\n { key: \"Updated\", value: new Date(project.updatedAt).toLocaleString() },\n ])\n );\n\n if (project.latestVersion) {\n console.log(chalk.bold(\"\\nVersion\"));\n console.log(\n formatKeyValue([\n { key: \"Version\", value: String(project.latestVersion.version) },\n { key: \"Composition ID\", value: project.latestVersion.compositionId },\n ])\n );\n } else {\n console.log(chalk.dim(\"\\nNo versions yet\"));\n }\n\n if (project.composition) {\n console.log(chalk.bold(\"\\nComposition\"));\n console.log(\n formatKeyValue([\n { key: \"Title\", value: project.composition.title },\n { key: \"Resolution\", value: `${project.composition.width}x${project.composition.height}` },\n { key: \"FPS\", value: String(project.composition.fps) },\n { key: \"Duration\", value: `${(project.composition.duration / 1000).toFixed(1)}s` },\n { key: \"Scenes\", value: String(project.composition.sceneCount) },\n ])\n );\n\n if (project.composition.sceneCount > 0 && Array.isArray(project.composition.scenes)) {\n console.log(chalk.bold(\"\\nScenes\"));\n for (const scene of project.composition.scenes as { id: string; type: string; duration: number }[]) {\n console.log(chalk.dim(` - ${scene.type} (${(scene.duration / 1000).toFixed(1)}s)`));\n }\n }\n } else {\n console.log(chalk.dim(\"\\nNo composition yet\"));\n }\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport interface ListOptions extends OutputOptions {\n limit?: number;\n}\n\ninterface Project {\n _id: string;\n title: string;\n description?: string;\n createdAt: number;\n updatedAt: number;\n}\n\ninterface ListResult {\n items: Project[];\n nextCursor: string | null;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n // Only show spinner in TTY environments (not through npx/pipes)\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching projects...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<ListResult>(\"projects.list\", {\n limit: options.limit,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to list projects\", options);\n process.exit(1);\n }\n\n const projects = result.data.items;\n\n if (options.json) {\n outputSuccess(projects, options);\n } else {\n if (projects.length === 0) {\n console.log(chalk.dim(\"No projects found. Create one with 'program project create'\"));\n return;\n }\n\n console.log(`Found ${chalk.cyan(projects.length)} project${projects.length === 1 ? \"\" : \"s\"}:\\n`);\n\n const rows = projects.map((p) => [\n p._id,\n p.title || chalk.dim(\"Untitled\"),\n formatDate(p.createdAt),\n ]);\n\n console.log(formatTable([\"ID\", \"Title\", \"Created\"], rows));\n }\n}\n\nfunction formatDate(timestamp: number): string {\n const date = new Date(timestamp);\n const now = new Date();\n const diffMs = now.getTime() - date.getTime();\n const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));\n\n if (diffDays === 0) {\n return \"today\";\n } else if (diffDays === 1) {\n return \"yesterday\";\n } else if (diffDays < 7) {\n return `${diffDays} days ago`;\n } else {\n return date.toLocaleDateString();\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport interface ListOptions extends OutputOptions {\n limit?: number;\n publicOnly?: boolean;\n}\n\ninterface Template {\n _id: string;\n name: string;\n description?: string;\n public: boolean;\n createdAt: number;\n updatedAt: number;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching workflow templates...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<Template[]>(\"workflows.listTemplates\", {\n category: options.publicOnly ? \"public\" : undefined,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to list templates\", options);\n process.exit(1);\n }\n\n const templates = result.data;\n\n if (options.json) {\n outputSuccess(\n templates.map((t) => ({\n id: t._id,\n name: t.name,\n description: t.description,\n public: t.public,\n })),\n options\n );\n } else {\n if (templates.length === 0) {\n console.log(chalk.dim(\"No workflow templates found.\"));\n return;\n }\n\n console.log(`Found ${chalk.cyan(templates.length)} template${templates.length === 1 ? \"\" : \"s\"}:\\n`);\n\n const rows = templates.map((t) => [\n t._id,\n t.name,\n t.description?.substring(0, 40) ?? chalk.dim(\"No description\"),\n t.public ? chalk.green(\"public\") : chalk.dim(\"private\"),\n ]);\n\n console.log(formatTable([\"ID\", \"Name\", \"Description\", \"Visibility\"], rows));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport interface RunOptions extends OutputOptions {\n project?: string;\n input?: string;\n}\n\nexport async function runCommand(templateId: string, options: RunOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Starting workflow execution...\").start() : null;\n\n // Parse input JSON if provided\n let input: Record<string, unknown> | undefined;\n if (options.input) {\n try {\n input = JSON.parse(options.input) as Record<string, unknown>;\n } catch {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Invalid JSON in --input parameter\", options);\n process.exit(1);\n }\n }\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.mutation<string>(\"workflows.run\", {\n templateId,\n projectId: options.project,\n input,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to start workflow\", options);\n process.exit(1);\n }\n\n const executionId = result.data;\n\n if (options.json) {\n outputSuccess({ executionId }, options);\n } else {\n console.log(formatSuccess(`Workflow started`));\n console.log(chalk.dim(` Execution ID: ${executionId}`));\n console.log(chalk.dim(` Check status with: program workflow status ${executionId}`));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatKeyValue, formatSuccess, formatWarning, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport interface StatusOptions extends OutputOptions {\n watch?: boolean;\n interval?: number;\n}\n\ninterface ExecutionStatus {\n status: \"pending\" | \"running\" | \"success\" | \"error\" | \"cancelled\";\n output?: unknown;\n error?: string;\n completedAt?: number;\n nodeStatuses?: { nodeId: string; status: string }[];\n}\n\nexport async function statusCommand(executionId: string, options: StatusOptions): Promise<void> {\n const client = createConvexClient(convexConfig);\n const pollInterval = options.interval ?? 2000;\n\n if (options.watch) {\n await watchStatus(client, executionId, pollInterval, options);\n } else {\n await getStatusOnce(client, executionId, options);\n }\n}\n\nasync function getStatusOnce(\n client: ReturnType<typeof createConvexClient>,\n executionId: string,\n options: StatusOptions\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching execution status...\").start() : null;\n\n const result = await client.query<ExecutionStatus>(\"workflows.status\", {\n executionId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get status\", options);\n process.exit(1);\n }\n\n const status = result.data;\n\n if (!status) {\n outputError(\"Execution not found\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(status, options);\n } else {\n printStatus(status);\n }\n}\n\nasync function watchStatus(\n client: ReturnType<typeof createConvexClient>,\n executionId: string,\n pollInterval: number,\n options: StatusOptions\n): Promise<void> {\n let lastStatus: string | null = null;\n\n const poll = async (): Promise<boolean> => {\n const result = await client.query<ExecutionStatus>(\"workflows.status\", {\n executionId,\n });\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get status\", options);\n return true; // Stop polling\n }\n\n const status = result.data;\n\n if (!status) {\n outputError(\"Execution not found\", options);\n return true;\n }\n\n // For JSON mode, output each status change\n if (options.json) {\n if (status.status !== lastStatus) {\n console.log(JSON.stringify(status));\n lastStatus = status.status;\n }\n } else {\n // For human mode, clear and reprint\n if (status.status !== lastStatus) {\n console.clear();\n console.log(chalk.dim(`Watching execution ${executionId}...\\n`));\n printStatus(status);\n lastStatus = status.status;\n }\n }\n\n // Stop polling if complete\n if ([\"success\", \"error\", \"cancelled\"].includes(status.status)) {\n return true;\n }\n\n return false;\n };\n\n // Initial poll\n let done = await poll();\n\n // Continue polling until complete\n while (!done) {\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n done = await poll();\n }\n}\n\nfunction printStatus(status: ExecutionStatus): void {\n const statusColor = getStatusColor(status.status);\n\n console.log(\n formatKeyValue([\n { key: \"Status\", value: statusColor(status.status) },\n ...(status.completedAt\n ? [{ key: \"Completed\", value: new Date(status.completedAt).toLocaleString() }]\n : []),\n ])\n );\n\n if (status.nodeStatuses && status.nodeStatuses.length > 0) {\n console.log(chalk.dim(\"\\nStep progress:\"));\n for (const node of status.nodeStatuses) {\n const nodeColor = getStatusColor(node.status);\n console.log(` ${nodeColor(getStatusIcon(node.status))} ${node.nodeId}`);\n }\n }\n\n if (status.error) {\n console.log(formatWarning(`\\nError: ${status.error}`));\n }\n\n if (status.status === \"success\" && status.output) {\n console.log(formatSuccess(\"\\nOutput:\"));\n console.log(JSON.stringify(status.output, null, 2));\n }\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case \"success\":\n return chalk.green;\n case \"error\":\n return chalk.red;\n case \"cancelled\":\n return chalk.yellow;\n case \"running\":\n return chalk.blue;\n case \"pending\":\n default:\n return chalk.dim;\n }\n}\n\nfunction getStatusIcon(status: string): string {\n switch (status) {\n case \"success\":\n return \"✓\";\n case \"error\":\n return \"✕\";\n case \"running\":\n return \"●\";\n case \"pending\":\n default:\n return \"○\";\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createReadStream } from \"node:fs\";\nimport * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { ensureValidToken } from \"../../lib/auth/index.js\";\nimport { oauthConfig, BASE_URL } from \"../../lib/config.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\nimport { detectAgentSource } from \"../../lib/agent-detect.js\";\n\nexport interface ExecuteOptions extends OutputOptions {\n project: string;\n params?: string;\n}\n\nconst MIME_TYPES_BY_EXTENSION: Record<string, string> = {\n \".aac\": \"audio/aac\",\n \".flac\": \"audio/flac\",\n \".gif\": \"image/gif\",\n \".jpeg\": \"image/jpeg\",\n \".jpg\": \"image/jpeg\",\n \".json\": \"application/json\",\n \".m4a\": \"audio/mp4\",\n \".mov\": \"video/quicktime\",\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n \".ogg\": \"audio/ogg\",\n \".png\": \"image/png\",\n \".svg\": \"image/svg+xml\",\n \".txt\": \"text/plain\",\n \".wav\": \"audio/wav\",\n \".webm\": \"video/webm\",\n};\n\nfunction inferMimeType(fileName: string): string | null {\n const extension = path.extname(fileName).toLowerCase();\n return MIME_TYPES_BY_EXTENSION[extension] ?? null;\n}\n\ninterface ToolResponse {\n success: boolean;\n data?: unknown;\n error?: string;\n compositionId?: string;\n}\n\ninterface UploadInitResponse extends ToolResponse {\n data?: {\n uploadUrl: string;\n fileName: string;\n mimeType: string;\n fileSize: number;\n };\n}\n\ninterface UploadStorageResponse {\n storageId?: string;\n}\n\nfunction normalizeToolParams(\n toolName: string,\n params: Record<string, unknown>,\n): Record<string, unknown> {\n if (toolName !== \"addScene\") {\n return params;\n }\n\n const next = { ...params };\n if (\n typeof next.name === \"string\" &&\n next.name.length > 0 &&\n (typeof next.title !== \"string\" || next.title.length === 0)\n ) {\n next.title = next.name;\n }\n\n return next;\n}\n\nasync function uploadFileFromPath(\n params: Record<string, unknown>,\n projectId: string,\n accessToken: string,\n source?: string,\n): Promise<ToolResponse> {\n const filePath = params.path;\n if (typeof filePath !== \"string\" || filePath.length === 0) {\n throw new Error(\"uploadFile path must be a non-empty string\");\n }\n if (!path.isAbsolute(filePath)) {\n throw new Error(\"uploadFile path must be an absolute file path\");\n }\n\n const fileStat = await fs.stat(filePath);\n if (!fileStat.isFile()) {\n throw new Error(`uploadFile path is not a file: ${filePath}`);\n }\n\n const fileName =\n typeof params.fileName === \"string\" && params.fileName.length > 0\n ? params.fileName\n : path.basename(filePath);\n if (fileName.includes(\"/\") || fileName.includes(\"\\\\\")) {\n throw new Error(\"fileName must be a plain file name, not a path\");\n }\n const inferredMimeType = inferMimeType(fileName);\n const mimeType =\n typeof params.mimeType === \"string\" && params.mimeType.length > 0\n ? params.mimeType\n : inferredMimeType;\n if (!mimeType) {\n throw new Error(\n \"Could not infer MIME type from file extension. Provide params.mimeType explicitly.\",\n );\n }\n\n const category =\n typeof params.category === \"string\" && params.category.length > 0\n ? params.category\n : undefined;\n if (category && !/^[a-z0-9_-]{1,32}$/i.test(category)) {\n throw new Error(\"category must match /^[a-z0-9_-]{1,32}$/i\");\n }\n const metadata =\n params.metadata && typeof params.metadata === \"object\"\n ? params.metadata\n : undefined;\n\n const initRequest: RequestInit = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n \"x-project-id\": projectId,\n ...(source ? { \"x-source\": source } : {}),\n },\n body: JSON.stringify({\n step: \"init\",\n fileName,\n mimeType,\n fileSize: fileStat.size,\n category,\n metadata,\n }),\n };\n\n const initResponse = await fetch(`${BASE_URL}/api/cli/upload`, initRequest);\n const initResult = (await initResponse\n .json()\n .catch(() => null)) as UploadInitResponse | null;\n\n if (!initResponse.ok || !initResult?.success || !initResult.data) {\n throw new Error(\n initResult?.error ?? `Upload init failed (${initResponse.status})`,\n );\n }\n\n const fileStream = createReadStream(filePath);\n const uploadRequest: RequestInit & { duplex: \"half\" } = {\n method: \"POST\",\n headers: {\n \"Content-Type\": mimeType,\n \"Content-Length\": String(fileStat.size),\n },\n body: fileStream as unknown as NonNullable<RequestInit[\"body\"]>,\n duplex: \"half\",\n };\n const storageUploadResponse = await fetch(\n initResult.data.uploadUrl,\n uploadRequest,\n );\n const storageUploadJson = (await storageUploadResponse\n .json()\n .catch(() => null)) as UploadStorageResponse | null;\n\n if (\n !storageUploadResponse.ok ||\n !storageUploadJson ||\n typeof storageUploadJson.storageId !== \"string\"\n ) {\n throw new Error(\n `Failed to upload bytes to storage (${storageUploadResponse.status})`,\n );\n }\n\n const finalizeRequest: RequestInit = {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n \"Content-Type\": \"application/json\",\n \"x-project-id\": projectId,\n ...(source ? { \"x-source\": source } : {}),\n },\n body: JSON.stringify({\n step: \"finalize\",\n storageId: storageUploadJson.storageId,\n fileName,\n mimeType,\n fileSize: fileStat.size,\n category,\n metadata,\n }),\n };\n\n const finalizeResponse = await fetch(\n `${BASE_URL}/api/cli/upload`,\n finalizeRequest,\n );\n\n const finalizeResult = (await finalizeResponse\n .json()\n .catch(() => null)) as ToolResponse | null;\n if (!finalizeResponse.ok || !finalizeResult?.success) {\n throw new Error(\n finalizeResult?.error ??\n `File finalize failed (${finalizeResponse.status})`,\n );\n }\n\n return finalizeResult;\n}\n\nexport async function executeCommand(\n toolName: string,\n options: ExecuteOptions\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(`Executing ${toolName}...`).start() : null;\n\n // Get valid access token\n const accessToken = ensureValidToken(oauthConfig);\n if (!accessToken) {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Not authenticated. Run 'program auth login' first.\", options);\n process.exit(1);\n }\n\n // Parse params if provided\n let params: Record<string, unknown> = {};\n if (options.params) {\n try {\n params = JSON.parse(options.params) as Record<string, unknown>;\n params = normalizeToolParams(toolName, params);\n } catch {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Invalid JSON in --params\", options);\n process.exit(1);\n }\n }\n\n // Detect agent at runtime (not login time) for correct multi-agent support\n const source = detectAgentSource();\n\n if (toolName === \"uploadFile\" && typeof params.path === \"string\") {\n try {\n if (spinner) {\n spinner.text = \"Uploading file...\";\n }\n const result = await uploadFileFromPath(\n params,\n options.project,\n accessToken,\n source,\n );\n if (spinner) {\n spinner.stop();\n spinner.clear();\n }\n if (options.json) {\n outputSuccess(result.data, options);\n } else {\n console.log(chalk.green(`✓ ${toolName} executed successfully`));\n if (result.compositionId) {\n console.log(chalk.dim(` Composition: ${result.compositionId}`));\n }\n console.log();\n console.log(JSON.stringify(result.data, null, 2));\n }\n return;\n } catch (error) {\n spinner?.stop();\n spinner?.clear();\n outputError(\n error instanceof Error ? error.message : \"Failed to upload file\",\n options,\n );\n process.exit(1);\n }\n }\n\n try {\n const response = await fetch(`${BASE_URL}/api/cli/tool`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n projectId: options.project,\n tool: toolName,\n params,\n source,\n }),\n });\n\n const result = (await response.json()) as ToolResponse;\n\n spinner?.stop();\n spinner?.clear();\n\n if (!response.ok || !result.success) {\n outputError(result.error ?? `Tool execution failed: ${response.status}`, options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(result.data, options);\n } else {\n console.log(chalk.green(`✓ ${toolName} executed successfully`));\n if (result.compositionId) {\n console.log(chalk.dim(` Composition: ${result.compositionId}`));\n }\n console.log();\n console.log(JSON.stringify(result.data, null, 2));\n }\n } catch (error) {\n spinner?.stop();\n spinner?.clear();\n outputError(error instanceof Error ? error.message : \"Request failed\", options);\n process.exit(1);\n }\n}\n","/**\n * Runtime agent detection\n *\n * Detects which agent/IDE is running the CLI based on environment variables.\n * This is checked per-request, not at login time, so multiple agents can\n * use the same credentials simultaneously with correct attribution.\n */\n\n/**\n * Detect which agent is currently running this CLI command.\n * Returns undefined for unknown agents (will show as \"Agent via CLI\").\n */\nexport function detectAgentSource(): string | undefined {\n if (process.env.CLAUDECODE === \"1\") {\n return \"claude-code\";\n }\n\n if (process.env.OPENCODE === \"1\") {\n return \"opencode\";\n }\n\n // Codex environments can expose CODEX_HOME, CODEX_CI, or a Codex bundle identifier.\n if (process.env.CODEX_CI === \"1\") {\n return \"codex\";\n }\n\n if (\n typeof process.env.__CFBundleIdentifier === \"string\" &&\n process.env.__CFBundleIdentifier.includes(\"codex\")\n ) {\n return \"codex\";\n }\n\n if (typeof process.env.CODEX_HOME === \"string\") {\n return \"codex\";\n }\n\n // OpenClaw and other agents will fall back to \"Agent via CLI\" until\n // they implement detection env vars\n return undefined;\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { BASE_URL } from \"../../lib/config.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\n\nexport type ListOptions = OutputOptions;\n\ninterface Tool {\n name: string;\n description: string;\n inputs: string[];\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching available tools...\").start() : null;\n\n try {\n const response = await fetch(`${BASE_URL}/api/cli/tool`, {\n method: \"GET\",\n });\n\n const result = (await response.json()) as {\n success: boolean;\n tools?: Tool[];\n error?: string;\n };\n\n spinner?.stop();\n spinner?.clear();\n\n if (!response.ok || !result.success) {\n outputError(result.error ?? \"Failed to list tools\", options);\n process.exit(1);\n }\n\n const tools = result.tools ?? [];\n\n if (options.json) {\n outputSuccess(tools, options);\n } else {\n console.log(chalk.bold(`Available Tools (${tools.length}):\\n`));\n\n for (const tool of tools) {\n console.log(chalk.cyan(` ${tool.name}`));\n console.log(chalk.dim(` ${tool.description}`));\n if (tool.inputs.length > 0) {\n console.log(chalk.dim(` Inputs: ${tool.inputs.join(\", \")}`));\n }\n console.log();\n }\n\n console.log(chalk.dim(\"Usage: program tool exec <toolName> --project <id> --params '{...}'\"));\n }\n } catch (error) {\n spinner?.stop();\n spinner?.clear();\n outputError(error instanceof Error ? error.message : \"Request failed\", options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { ensureValidToken } from \"../../lib/auth/index.js\";\nimport { oauthConfig, BASE_URL } from \"../../lib/config.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport type {OutputOptions} from \"../../lib/output.js\";\nimport { detectAgentSource } from \"../../lib/agent-detect.js\";\n\nexport interface SendMessageOptions extends OutputOptions {\n project: string;\n role?: \"user\" | \"assistant\";\n}\n\nexport async function sendCommand(\n text: string,\n options: SendMessageOptions\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Sending message...\").start() : null;\n\n // Get valid access token\n const accessToken = ensureValidToken(oauthConfig);\n if (!accessToken) {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Not authenticated. Run 'program auth login' first.\", options);\n process.exit(1);\n }\n\n const role = options.role ?? \"assistant\";\n\n // Detect agent at runtime (not login time) for correct multi-agent support\n const source = detectAgentSource();\n\n try {\n const response = await fetch(`${BASE_URL}/api/cli/message`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({\n projectId: options.project,\n role,\n text,\n source,\n }),\n });\n\n const result = (await response.json()) as {\n success: boolean;\n messageId?: string;\n error?: string;\n };\n\n spinner?.stop();\n spinner?.clear();\n\n if (!response.ok || !result.success) {\n outputError(result.error ?? `Failed to send message: ${response.status}`, options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess({ messageId: result.messageId, role, text }, options);\n } else {\n console.log(chalk.green(`✓ Message sent as ${role}`));\n if (result.messageId) {\n console.log(chalk.dim(` Message ID: ${result.messageId}`));\n }\n }\n } catch (error) {\n spinner?.stop();\n spinner?.clear();\n outputError(error instanceof Error ? error.message : \"Request failed\", options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { ensureValidToken } from \"../../lib/auth/index.js\";\nimport { oauthConfig, BASE_URL } from \"../../lib/config.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\n\nexport interface ListMessageOptions extends OutputOptions {\n project: string;\n limit?: number;\n}\n\ninterface MessagePart {\n type: string;\n text?: string;\n toolName?: string;\n toolCallId?: string;\n state?: string;\n}\n\ninterface Message {\n id: string;\n role: \"user\" | \"assistant\";\n parts: MessagePart[];\n source?: string;\n createdAt: number;\n}\n\nexport async function listCommand(options: ListMessageOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching messages...\").start() : null;\n\n // Get valid access token\n const accessToken = ensureValidToken(oauthConfig);\n if (!accessToken) {\n spinner?.stop();\n spinner?.clear();\n outputError(\n \"Not authenticated. Run 'program auth login' first.\",\n options\n );\n process.exit(1);\n }\n\n try {\n const url = new URL(`${BASE_URL}/api/cli/message`);\n url.searchParams.set(\"projectId\", options.project);\n if (options.limit) {\n url.searchParams.set(\"limit\", options.limit.toString());\n }\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${accessToken}`,\n },\n });\n\n const result = (await response.json()) as {\n success: boolean;\n chatId?: string;\n messages?: Message[];\n error?: string;\n };\n\n spinner?.stop();\n spinner?.clear();\n\n if (!response.ok || !result.success) {\n outputError(\n result.error ?? `Failed to fetch messages: ${response.status}`,\n options\n );\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(result, options);\n } else {\n const messages = result.messages ?? [];\n if (messages.length === 0) {\n console.log(chalk.dim(\"No messages in this chat yet.\"));\n return;\n }\n\n console.log(chalk.bold(`Chat Messages (${messages.length}):\\n`));\n\n for (const msg of messages) {\n // Format the role with source if available\n let roleLabel = msg.role === \"user\" ? \"You\" : \"Assistant\";\n if (msg.source) {\n if (msg.source === \"cli:claude-code\") {\n roleLabel = \"Claude via CLI\";\n } else if (msg.source === \"cli:codex\") {\n roleLabel = \"Codex via CLI\";\n } else if (msg.source.startsWith(\"cli:\")) {\n roleLabel = `${roleLabel} via CLI`;\n }\n }\n\n // Get text content from parts\n const textContent = msg.parts\n .filter((p): p is MessagePart & { text: string } => p.type === \"text\" && !!p.text)\n .map((p) => p.text)\n .join(\"\\n\");\n\n // Get tool calls\n const toolCalls = msg.parts.filter(\n (p) => p.type === \"tool-invocation\" || p.type === \"tool-call\"\n );\n\n // Format timestamp\n const time = new Date(msg.createdAt).toLocaleTimeString();\n\n // Print message\n const roleColor = msg.role === \"user\" ? chalk.blue : chalk.green;\n console.log(roleColor(`[${time}] ${roleLabel}:`));\n\n if (textContent) {\n // Indent and truncate long messages\n const truncated =\n textContent.length > 500\n ? textContent.substring(0, 500) + \"...\"\n : textContent;\n console.log(\n truncated\n .split(\"\\n\")\n .map((line) => ` ${line}`)\n .join(\"\\n\")\n );\n }\n\n if (toolCalls.length > 0) {\n console.log(\n chalk.dim(` [${toolCalls.length} tool call(s)]`)\n );\n }\n\n console.log();\n }\n }\n } catch (error) {\n spinner?.stop();\n spinner?.clear();\n outputError(\n error instanceof Error ? error.message : \"Request failed\",\n options\n );\n process.exit(1);\n }\n}\n","import { outputSuccess } from \"../lib/output.js\";\nimport type {OutputOptions} from \"../lib/output.js\";\n\nexport interface DocsOptions extends OutputOptions {\n schema?: boolean;\n}\n\n// Command schema for agents\nconst COMMAND_SCHEMA = {\n name: \"program\",\n version: \"0.1.0\",\n description: \"CLI for interacting with the Program video creation platform\",\n commands: {\n auth: {\n description: \"Authentication commands\",\n subcommands: {\n login: {\n description: \"Authenticate with the Program platform\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth login\",\n },\n logout: {\n description: \"Log out from the Program platform\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth logout\",\n },\n status: {\n description: \"Check authentication status\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth status --json\",\n },\n },\n },\n project: {\n description: \"Project management commands\",\n subcommands: {\n create: {\n description: \"Create a new project\",\n options: {\n \"--title <title>\": \"Project title\",\n \"--description <desc>\": \"Project description\",\n \"--json\": \"Output as JSON\",\n },\n example: 'program project create --title \"My Video\" --json',\n },\n list: {\n description: \"List projects\",\n options: {\n \"--limit <n>\": \"Maximum number of projects to return\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program project list --json\",\n },\n },\n },\n workflow: {\n description: \"Workflow template commands\",\n subcommands: {\n list: {\n description: \"List available workflow templates\",\n options: {\n \"--limit <n>\": \"Maximum number of templates to return\",\n \"--public-only\": \"Only show public templates\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program workflow list --json\",\n },\n run: {\n description: \"Execute a workflow template\",\n args: {\n templateId: \"ID of the template to run\",\n },\n options: {\n \"--project <id>\": \"Project ID to associate with execution\",\n \"--input <json>\": \"JSON input for the workflow\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program workflow run tmpl_abc --project proj_123 --input '{\\\"files\\\":[\\\"src/main.ts\\\"]}' --json\",\n },\n status: {\n description: \"Check workflow execution status\",\n args: {\n executionId: \"ID of the execution to check\",\n },\n options: {\n \"--watch\": \"Continuously poll for status updates\",\n \"--interval <ms>\": \"Poll interval in milliseconds (default: 2000)\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program workflow status exec_789 --watch --json\",\n },\n },\n },\n docs: {\n description: \"Display CLI documentation\",\n options: {\n \"--schema\": \"Output full command schema as JSON\",\n },\n example: \"program docs --schema\",\n },\n },\n globalOptions: {\n \"--help\": \"Display help information\",\n \"--version\": \"Display version number\",\n },\n notes: [\n \"Always use --json flag for parseable output when integrating with agents\",\n \"Workflow inputs should be valid JSON strings\",\n \"Run 'program auth login' first to authenticate\",\n ],\n};\n\nexport function docsCommand(options: DocsOptions): void {\n if (options.schema ?? options.json) {\n outputSuccess(COMMAND_SCHEMA, { json: true });\n } else {\n printHumanDocs();\n }\n}\n\nfunction printHumanDocs(): void {\n console.log(`\nProgram CLI v${COMMAND_SCHEMA.version}\n${COMMAND_SCHEMA.description}\n\nCOMMANDS:\n\n auth login Authenticate with the Program platform\n auth logout Log out from the Program platform\n auth status Check authentication status\n\n project create Create a new project\n project list List projects\n\n workflow list List available workflow templates\n workflow run <id> Execute a workflow template\n workflow status <id> Check workflow execution status\n\n docs Display this documentation\n docs --schema Output full command schema as JSON\n\nGLOBAL OPTIONS:\n\n --json Output as JSON (recommended for agents)\n --help Display help information\n --version Display version number\n\nEXAMPLES:\n\n # Authenticate\n program auth login\n\n # Create a project\n program project create --title \"My Video\" --json\n\n # Run a workflow\n program workflow run tmpl_abc --project proj_123 --json\n\n # Watch execution progress\n program workflow status exec_789 --watch --json\n\nFor agent integration, always use the --json flag.\n`);\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\n\nexport interface ListOptions extends OutputOptions {\n limit?: number;\n publicOnly?: boolean;\n}\n\ninterface Template {\n _id: string;\n name: string;\n description?: string;\n public: boolean;\n steps?: unknown[];\n createdAt: number;\n updatedAt: number;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching templates...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<Template[]>(\"templates.list\", {\n category: options.publicOnly ? \"public\" : undefined,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to list templates\", options);\n process.exit(1);\n }\n\n const templates = result.data;\n\n if (options.json) {\n outputSuccess(\n templates.map((t) => ({\n id: t._id,\n name: t.name,\n description: t.description,\n public: t.public,\n stepCount: Array.isArray(t.steps) ? t.steps.length : 0,\n })),\n options,\n );\n } else {\n if (templates.length === 0) {\n console.log(chalk.dim(\"No templates found.\"));\n return;\n }\n\n console.log(\n `Found ${chalk.cyan(templates.length)} template${templates.length === 1 ? \"\" : \"s\"}:\\n`,\n );\n\n const rows = templates.map((t) => [\n t._id,\n t.name,\n t.description?.substring(0, 40) ?? chalk.dim(\"No description\"),\n String(Array.isArray(t.steps) ? t.steps.length : 0),\n t.public ? chalk.green(\"public\") : chalk.dim(\"private\"),\n ]);\n\n console.log(\n formatTable([\"ID\", \"Name\", \"Description\", \"Steps\", \"Visibility\"], rows),\n );\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport {\n formatKeyValue,\n formatTable,\n outputError,\n outputSuccess,\n} from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\n\nexport type GetOptions = OutputOptions;\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\ninterface Template {\n _id: string;\n name: string;\n description?: string;\n public: boolean;\n steps?: Step[];\n metadata?: Record<string, unknown>;\n createdAt: number;\n updatedAt: number;\n}\n\nexport async function getCommand(\n id: string | undefined,\n options: GetOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Fetching template...\").start()\n : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<Template>(\"templates.byId\", {\n id: templateId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Template not found\", options);\n process.exit(1);\n }\n\n const template = result.data;\n\n if (options.json) {\n outputSuccess(template, options);\n } else {\n console.log(\n formatKeyValue([\n { key: \"ID\", value: template._id },\n { key: \"Name\", value: template.name },\n {\n key: \"Description\",\n value: template.description ?? chalk.dim(\"None\"),\n },\n {\n key: \"Visibility\",\n value: template.public\n ? chalk.green(\"public\")\n : chalk.dim(\"private\"),\n },\n {\n key: \"Created\",\n value: new Date(template.createdAt).toLocaleString(),\n },\n {\n key: \"Updated\",\n value: new Date(template.updatedAt).toLocaleString(),\n },\n ]),\n );\n\n const steps = template.steps ?? [];\n if (steps.length === 0) {\n console.log(chalk.dim(\"\\nNo steps configured.\"));\n } else {\n console.log(`\\n${chalk.bold(\"Steps\")} (${steps.length}):\\n`);\n\n const rows = steps.map((s, i) => [\n String(i),\n s.id ?? chalk.dim(\"—\"),\n s.stepId,\n summarizeConfig(s.config),\n ]);\n\n console.log(formatTable([\"#\", \"ID\", \"Type\", \"Config\"], rows));\n }\n }\n}\n\nfunction summarizeConfig(config: Record<string, unknown>): string {\n const keys = Object.keys(config);\n if (keys.length === 0) return chalk.dim(\"{}\");\n const summary = keys\n .slice(0, 3)\n .map((k) => {\n const v = config[k];\n const vs =\n typeof v === \"string\"\n ? v.length > 20\n ? v.substring(0, 20) + \"...\"\n : v\n : JSON.stringify(v);\n return `${k}=${vs}`;\n })\n .join(\", \");\n return keys.length > 3 ? summary + `, +${keys.length - 3} more` : summary;\n}\n","import Conf from \"conf\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as os from \"node:os\";\n\ninterface ContextData {\n activeTemplateId: string | null;\n}\n\nconst CONTEXT_DIR = path.join(os.homedir(), \".program\");\n\nfunction ensureContextDir(): void {\n if (!fs.existsSync(CONTEXT_DIR)) {\n fs.mkdirSync(CONTEXT_DIR, { mode: 0o700, recursive: true });\n }\n}\n\nconst store = new Conf<ContextData>({\n projectName: \"program-cli\",\n cwd: CONTEXT_DIR,\n configName: \"context\",\n fileExtension: \"json\",\n defaults: {\n activeTemplateId: null,\n },\n});\n\nexport function setActiveTemplate(id: string): void {\n ensureContextDir();\n store.set(\"activeTemplateId\", id);\n}\n\nexport function getActiveTemplate(): string | null {\n return store.get(\"activeTemplateId\");\n}\n\nexport function clearActiveTemplate(): void {\n store.set(\"activeTemplateId\", null);\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { setActiveTemplate } from \"../../lib/context.js\";\n\nexport interface CreateOptions extends OutputOptions {\n name: string;\n description?: string;\n public?: boolean;\n}\n\nexport async function createCommand(options: CreateOptions): Promise<void> {\n if (!options.name) {\n outputError(\"--name is required\", options);\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Creating template...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.mutation<string>(\"templates.create\", {\n name: options.name,\n description: options.description,\n public: options.public ?? false,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to create template\", options);\n process.exit(1);\n }\n\n const templateId = result.data;\n\n // Auto-set as active template\n setActiveTemplate(templateId);\n\n if (options.json) {\n outputSuccess({ id: templateId, active: true }, options);\n } else {\n console.log(formatSuccess(\"Template created (now active)\"));\n console.log(chalk.dim(` ID: ${templateId}`));\n }\n}\n","import ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\n\nexport interface UpdateOptions extends OutputOptions {\n name?: string;\n description?: string;\n public?: boolean;\n steps?: string;\n}\n\nexport async function updateCommand(\n id: string | undefined,\n options: UpdateOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Updating template...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const params: Record<string, unknown> = { id: templateId };\n if (options.name !== undefined) params.name = options.name;\n if (options.description !== undefined) params.description = options.description;\n if (options.public !== undefined) params.public = options.public;\n if (options.steps !== undefined) {\n try {\n params.steps = JSON.parse(options.steps) as unknown[];\n } catch {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Invalid JSON in --steps parameter\", options);\n process.exit(1);\n }\n }\n\n const result = await client.mutation<string>(\"templates.update\", params);\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to update template\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess({ id: templateId, updated: true }, options);\n } else {\n console.log(formatSuccess(\"Template updated\"));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate, clearActiveTemplate } from \"../../lib/context.js\";\n\nexport interface RemoveOptions extends OutputOptions {\n force?: boolean;\n}\n\nexport async function removeCommand(\n id: string | undefined,\n options: RemoveOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n if (!options.force && !options.json) {\n // Prompt for confirmation\n const readline = await import(\"node:readline\");\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const answer = await new Promise<string>((resolve) => {\n rl.question(\n chalk.yellow(`Are you sure you want to delete template ${templateId}? (y/N) `),\n resolve,\n );\n });\n rl.close();\n\n if (answer.toLowerCase() !== \"y\") {\n console.log(chalk.dim(\"Cancelled.\"));\n return;\n }\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Deleting template...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.mutation<string>(\"templates.remove\", {\n id: templateId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to delete template\", options);\n process.exit(1);\n }\n\n // Clear active template if it was the deleted one\n if (getActiveTemplate() === templateId) {\n clearActiveTemplate();\n }\n\n if (options.json) {\n outputSuccess({ id: templateId, deleted: true }, options);\n } else {\n console.log(formatSuccess(\"Template deleted\"));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\n\nexport interface RunOptions extends OutputOptions {\n project?: string;\n input?: string;\n}\n\nexport async function runCommand(\n id: string | undefined,\n options: RunOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Starting workflow execution...\")\n .start()\n : null;\n\n // Parse input JSON if provided\n let input: Record<string, unknown> | undefined;\n if (options.input) {\n try {\n input = JSON.parse(options.input) as Record<string, unknown>;\n } catch {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Invalid JSON in --input parameter\", options);\n process.exit(1);\n }\n }\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.mutation<string>(\"workflows.run\", {\n templateId,\n projectId: options.project,\n input,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to start workflow\", options);\n process.exit(1);\n }\n\n const executionId = result.data;\n\n if (options.json) {\n outputSuccess({ executionId }, options);\n } else {\n console.log(formatSuccess(\"Workflow started\"));\n console.log(chalk.dim(` Execution ID: ${executionId}`));\n console.log(\n chalk.dim(` Check status with: program template status ${executionId}`),\n );\n }\n}\n","import chalk from \"chalk\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport {\n formatKeyValue,\n formatSuccess,\n formatWarning,\n outputError,\n outputSuccess,\n} from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport ora from \"ora\";\n\nexport interface StatusOptions extends OutputOptions {\n watch?: boolean;\n interval?: number;\n}\n\ninterface ExecutionStatus {\n status: \"pending\" | \"running\" | \"success\" | \"error\" | \"cancelled\";\n output?: unknown;\n error?: string;\n completedAt?: number;\n nodeStatuses?: { nodeId: string; status: string }[];\n}\n\nexport async function statusCommand(\n executionId: string,\n options: StatusOptions,\n): Promise<void> {\n const client = createConvexClient(convexConfig);\n const pollInterval = options.interval ?? 2000;\n\n if (options.watch) {\n await watchStatus(client, executionId, pollInterval, options);\n } else {\n await getStatusOnce(client, executionId, options);\n }\n}\n\nasync function getStatusOnce(\n client: ReturnType<typeof createConvexClient>,\n executionId: string,\n options: StatusOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Fetching execution status...\").start()\n : null;\n\n const result = await client.query<ExecutionStatus>(\"workflows.status\", {\n executionId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get status\", options);\n process.exit(1);\n }\n\n const status = result.data;\n\n if (!status) {\n outputError(\"Execution not found\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(status, options);\n } else {\n printStatus(status);\n }\n}\n\nasync function watchStatus(\n client: ReturnType<typeof createConvexClient>,\n executionId: string,\n pollInterval: number,\n options: StatusOptions,\n): Promise<void> {\n let lastStatus: string | null = null;\n\n const poll = async (): Promise<boolean> => {\n const result = await client.query<ExecutionStatus>(\"workflows.status\", {\n executionId,\n });\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get status\", options);\n return true;\n }\n\n const status = result.data;\n\n if (!status) {\n outputError(\"Execution not found\", options);\n return true;\n }\n\n if (options.json) {\n if (status.status !== lastStatus) {\n console.log(JSON.stringify(status));\n lastStatus = status.status;\n }\n } else {\n if (status.status !== lastStatus) {\n console.clear();\n console.log(chalk.dim(`Watching execution ${executionId}...\\n`));\n printStatus(status);\n lastStatus = status.status;\n }\n }\n\n if ([\"success\", \"error\", \"cancelled\"].includes(status.status)) {\n return true;\n }\n\n return false;\n };\n\n let done = await poll();\n\n while (!done) {\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n done = await poll();\n }\n}\n\nfunction printStatus(status: ExecutionStatus): void {\n const statusColor = getStatusColor(status.status);\n\n console.log(\n formatKeyValue([\n { key: \"Status\", value: statusColor(status.status) },\n ...(status.completedAt\n ? [\n {\n key: \"Completed\",\n value: new Date(status.completedAt).toLocaleString(),\n },\n ]\n : []),\n ]),\n );\n\n if (status.nodeStatuses && status.nodeStatuses.length > 0) {\n console.log(chalk.dim(\"\\nStep progress:\"));\n for (const node of status.nodeStatuses) {\n const nodeColor = getStatusColor(node.status);\n console.log(` ${nodeColor(getStatusIcon(node.status))} ${node.nodeId}`);\n }\n }\n\n if (status.error) {\n console.log(formatWarning(`\\nError: ${status.error}`));\n }\n\n if (status.status === \"success\" && status.output) {\n console.log(formatSuccess(\"\\nOutput:\"));\n console.log(JSON.stringify(status.output, null, 2));\n }\n}\n\nfunction getStatusColor(status: string): (text: string) => string {\n switch (status) {\n case \"success\":\n return chalk.green;\n case \"error\":\n return chalk.red;\n case \"cancelled\":\n return chalk.yellow;\n case \"running\":\n return chalk.blue;\n case \"pending\":\n default:\n return chalk.dim;\n }\n}\n\nfunction getStatusIcon(status: string): string {\n switch (status) {\n case \"success\":\n return \"✓\";\n case \"error\":\n return \"✕\";\n case \"running\":\n return \"●\";\n case \"pending\":\n default:\n return \"○\";\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../lib/convex.js\";\nimport { convexConfig } from \"../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { setActiveTemplate } from \"../../lib/context.js\";\n\nexport type UseOptions = OutputOptions;\n\ninterface Template {\n _id: string;\n name: string;\n}\n\nexport async function useCommand(\n id: string,\n options: UseOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Verifying template...\").start()\n : null;\n\n // Verify the template exists and is accessible\n const client = createConvexClient(convexConfig);\n const result = await client.query<Template>(\"templates.byId\", { id });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Template not found or not accessible\", options);\n process.exit(1);\n }\n\n setActiveTemplate(id);\n\n if (options.json) {\n outputSuccess({ id, name: result.data.name, active: true }, options);\n } else {\n console.log(formatSuccess(`Active template set to \"${result.data.name}\"`));\n console.log(chalk.dim(` ID: ${id}`));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\n\nexport interface StepListOptions extends OutputOptions {\n category?: string;\n}\n\ninterface StepType {\n id: string;\n name: string;\n description: string;\n category: string;\n isPrimitive: boolean;\n}\n\nexport async function stepListCommand(options: StepListOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching step types...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<StepType[]>(\"templates.steps\", {\n category: options.category,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to list step types\", options);\n process.exit(1);\n }\n\n const steps = result.data;\n\n if (options.json) {\n outputSuccess(steps, options);\n } else {\n if (steps.length === 0) {\n console.log(chalk.dim(\"No step types found.\"));\n return;\n }\n\n console.log(\n `Found ${chalk.cyan(steps.length)} step type${steps.length === 1 ? \"\" : \"s\"}:\\n`,\n );\n\n const rows = steps.map((s) => [\n s.id,\n s.name,\n s.category,\n s.isPrimitive ? chalk.yellow(\"primitive\") : \"\",\n ]);\n\n console.log(formatTable([\"Type\", \"Name\", \"Category\", \"\"], rows));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport {\n formatKeyValue,\n formatTable,\n outputError,\n outputSuccess,\n} from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\n\nexport type StepInfoOptions = OutputOptions;\n\ninterface StepInput {\n key: string;\n label: string;\n type: string;\n required: boolean;\n description: string;\n hidden?: boolean;\n}\n\ninterface StepOutput {\n key: string;\n label: string;\n type: string;\n description: string;\n}\n\ninterface StepType {\n id: string;\n name: string;\n description: string;\n category: string;\n inputs: StepInput[];\n outputs: StepOutput[];\n isPrimitive: boolean;\n}\n\nexport async function stepInfoCommand(\n stepType: string,\n options: StepInfoOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Fetching step info...\").start()\n : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<StepType | null>(\"templates.stepInfo\", {\n stepId: stepType,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get step info\", options);\n process.exit(1);\n }\n\n if (!result.data) {\n outputError(`Step type \"${stepType}\" not found`, options);\n process.exit(1);\n }\n\n const step = result.data;\n\n if (options.json) {\n outputSuccess(step, options);\n } else {\n console.log(\n formatKeyValue([\n { key: \"Type\", value: step.id },\n { key: \"Name\", value: step.name },\n { key: \"Category\", value: step.category },\n { key: \"Description\", value: step.description },\n {\n key: \"Primitive\",\n value: step.isPrimitive ? chalk.yellow(\"yes\") : \"no\",\n },\n ]),\n );\n\n // Show inputs\n const visibleInputs = step.inputs.filter((i) => !i.hidden);\n if (visibleInputs.length > 0) {\n console.log(`\\n${chalk.bold(\"Inputs\")}:\\n`);\n const inputRows = visibleInputs.map((i) => [\n i.key,\n i.type,\n i.required ? chalk.green(\"yes\") : chalk.dim(\"no\"),\n i.description,\n ]);\n console.log(\n formatTable([\"Key\", \"Type\", \"Required\", \"Description\"], inputRows),\n );\n }\n\n // Show outputs\n if (step.outputs.length > 0) {\n console.log(`\\n${chalk.bold(\"Outputs\")}:\\n`);\n const outputRows = step.outputs.map((o) => [\n o.key,\n o.type,\n o.description,\n ]);\n console.log(formatTable([\"Key\", \"Type\", \"Description\"], outputRows));\n }\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport crypto from \"node:crypto\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\n\nexport interface StepAddOptions extends OutputOptions {\n config?: string;\n at?: number;\n after?: string;\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\ninterface Template {\n _id: string;\n steps?: Step[];\n}\n\nexport async function stepAddCommand(\n stepType: string,\n options: StepAddOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n // Parse config\n let config: Record<string, unknown> = {};\n if (options.config) {\n try {\n config = JSON.parse(options.config) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --config parameter\", options);\n process.exit(1);\n }\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Adding step...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n // Fetch current template\n const getResult = await client.query<Template>(\"templates.byId\", {\n id: templateId,\n });\n\n if (!getResult.success || !getResult.data) {\n spinner?.stop();\n spinner?.clear();\n outputError(getResult.error ?? \"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = (getResult.data.steps ?? []).map((s) => ({ ...s }));\n\n // Generate unique ID for the new step\n const newId = crypto.randomUUID().slice(0, 8);\n\n // Determine insertion position\n let insertAt: number;\n if (options.at !== undefined) {\n insertAt = Math.max(0, Math.min(options.at, steps.length));\n } else if (options.after) {\n const afterIndex = steps.findIndex((s) => s.id === options.after);\n if (afterIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step with id \"${options.after}\" not found`, options);\n process.exit(1);\n }\n insertAt = afterIndex + 1;\n } else {\n insertAt = steps.length;\n }\n\n // Create the new step\n const newStep: Step = {\n id: newId,\n stepId: stepType,\n config,\n order: insertAt,\n };\n\n // Insert and re-number\n steps.splice(insertAt, 0, newStep);\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i];\n if (s) s.order = i;\n }\n\n // Update template\n const updateResult = await client.mutation<string>(\"templates.update\", {\n id: templateId,\n steps,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!updateResult.success) {\n outputError(updateResult.error ?? \"Failed to update template\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(\n { id: newId, stepId: stepType, order: insertAt, templateId },\n options,\n );\n } else {\n console.log(formatSuccess(`Step added: ${stepType}`));\n console.log(chalk.dim(` Step ID: ${newId}`));\n console.log(chalk.dim(` Position: ${insertAt}`));\n }\n}\n","import ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\n\nexport interface StepRemoveOptions extends OutputOptions {\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\ninterface Template {\n _id: string;\n steps?: Step[];\n}\n\nexport async function stepRemoveCommand(\n stepInstanceId: string,\n options: StepRemoveOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Removing step...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n // Fetch current template\n const getResult = await client.query<Template>(\"templates.byId\", {\n id: templateId,\n });\n\n if (!getResult.success || !getResult.data) {\n spinner?.stop();\n spinner?.clear();\n outputError(getResult.error ?? \"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = getResult.data.steps ?? [];\n const removeIndex = steps.findIndex((s) => s.id === stepInstanceId);\n\n if (removeIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step with id \"${stepInstanceId}\" not found in template`, options);\n process.exit(1);\n }\n\n const removed = steps[removeIndex];\n if (!removed) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step at index ${removeIndex} not found`, options);\n process.exit(1);\n }\n\n // Remove and re-number\n const newSteps = steps.filter((_, i) => i !== removeIndex);\n for (let i = 0; i < newSteps.length; i++) {\n const s = newSteps[i];\n if (s) s.order = i;\n }\n\n // Update template\n const updateResult = await client.mutation<string>(\"templates.update\", {\n id: templateId,\n steps: newSteps,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!updateResult.success) {\n outputError(updateResult.error ?? \"Failed to update template\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(\n { removed: stepInstanceId, stepId: removed.stepId, templateId },\n options,\n );\n } else {\n console.log(formatSuccess(`Removed step: ${removed.stepId} (${stepInstanceId})`));\n }\n}\n","import ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\n\nexport interface StepUpdateOptions extends OutputOptions {\n config?: string;\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\ninterface Template {\n _id: string;\n steps?: Step[];\n}\n\nexport async function stepUpdateCommand(\n stepInstanceId: string,\n options: StepUpdateOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n if (!options.config) {\n outputError(\"--config is required\", options);\n process.exit(1);\n }\n\n // Parse config to merge\n let configPatch: Record<string, unknown>;\n try {\n configPatch = JSON.parse(options.config) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --config parameter\", options);\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Updating step...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n // Fetch current template\n const getResult = await client.query<Template>(\"templates.byId\", {\n id: templateId,\n });\n\n if (!getResult.success || !getResult.data) {\n spinner?.stop();\n spinner?.clear();\n outputError(getResult.error ?? \"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = (getResult.data.steps ?? []).map((s) => ({ ...s }));\n const stepIndex = steps.findIndex((s) => s.id === stepInstanceId);\n\n if (stepIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step with id \"${stepInstanceId}\" not found in template`, options);\n process.exit(1);\n }\n\n const targetStep = steps[stepIndex];\n if (!targetStep) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step at index ${stepIndex} not found`, options);\n process.exit(1);\n }\n\n // Merge config\n targetStep.config = {\n ...targetStep.config,\n ...configPatch,\n };\n\n // Update template\n const updateResult = await client.mutation<string>(\"templates.update\", {\n id: templateId,\n steps,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!updateResult.success) {\n outputError(updateResult.error ?? \"Failed to update template\", options);\n process.exit(1);\n }\n\n if (options.json) {\n outputSuccess(\n {\n id: stepInstanceId,\n stepId: targetStep.stepId,\n config: targetStep.config,\n templateId,\n },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Updated step: ${targetStep.stepId} (${stepInstanceId})`,\n ),\n );\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\n\nexport type ModelListOptions = OutputOptions;\n\ninterface Model {\n _id: string;\n modelId: string;\n modelName: string;\n displayName?: string;\n provider: string;\n description?: string;\n}\n\nexport async function modelListCommand(\n category: string,\n options: ModelListOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching models...\").start() : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<Model[]>(\"models.list\", { category });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success || !result.data) {\n outputError(result.error ?? \"Failed to list models\", options);\n process.exit(1);\n }\n\n const models = result.data;\n\n if (options.json) {\n outputSuccess(\n models.map((m) => ({\n modelId: m.modelId,\n name: m.displayName ?? m.modelName,\n provider: m.provider,\n description: m.description,\n })),\n options,\n );\n } else {\n if (models.length === 0) {\n console.log(chalk.dim(`No ${category} models found.`));\n return;\n }\n\n console.log(\n `Found ${chalk.cyan(models.length)} ${category} model${models.length === 1 ? \"\" : \"s\"}:\\n`,\n );\n\n const rows = models.map((m) => [\n m.modelId,\n m.displayName ?? m.modelName,\n m.provider,\n ]);\n\n console.log(formatTable([\"Model ID\", \"Name\", \"Provider\"], rows));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\nimport { createConvexClient } from \"../../../lib/convex.js\";\nimport { convexConfig } from \"../../../lib/config.js\";\nimport {\n formatKeyValue,\n formatTable,\n outputError,\n outputSuccess,\n} from \"../../../lib/output.js\";\nimport type { OutputOptions } from \"../../../lib/output.js\";\n\nexport type ModelSchemaOptions = OutputOptions;\n\ninterface SchemaProperty {\n type?: string;\n description?: string;\n default?: unknown;\n enum?: unknown[];\n minimum?: number;\n maximum?: number;\n items?: { type?: string };\n}\n\ninterface InputSchema {\n type?: string;\n properties?: Record<string, SchemaProperty>;\n required?: string[];\n [key: string]: unknown;\n}\n\ninterface Model {\n _id: string;\n modelId: string;\n modelName: string;\n displayName?: string;\n provider: string;\n category: string;\n description?: string;\n inputSchema?: InputSchema;\n}\n\nexport async function modelSchemaCommand(\n modelId: string,\n options: ModelSchemaOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner\n ? ora(\"Fetching model schema...\").start()\n : null;\n\n const client = createConvexClient(convexConfig);\n\n const result = await client.query<Model | null>(\"models.byModelId\", {\n modelId,\n });\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result.success) {\n outputError(result.error ?? \"Failed to get model\", options);\n process.exit(1);\n }\n\n if (!result.data) {\n outputError(`Model \"${modelId}\" not found`, options);\n process.exit(1);\n }\n\n const model = result.data;\n\n if (options.json) {\n outputSuccess(\n {\n modelId: model.modelId,\n name: model.displayName ?? model.modelName,\n provider: model.provider,\n category: model.category,\n description: model.description,\n inputSchema: model.inputSchema,\n },\n options,\n );\n } else {\n console.log(\n formatKeyValue([\n { key: \"Model ID\", value: model.modelId },\n { key: \"Name\", value: model.displayName ?? model.modelName },\n { key: \"Provider\", value: model.provider },\n { key: \"Category\", value: model.category },\n {\n key: \"Description\",\n value: model.description ?? chalk.dim(\"None\"),\n },\n ]),\n );\n\n const schema = model.inputSchema;\n if (!schema?.properties) {\n console.log(chalk.dim(\"\\nNo input schema available.\"));\n return;\n }\n\n const required = new Set(schema.required ?? []);\n const props = schema.properties;\n\n console.log(`\\n${chalk.bold(\"Input Parameters\")}:\\n`);\n\n const rows = Object.entries(props).map(([key, prop]) => [\n key,\n prop.type ?? \"unknown\",\n required.has(key) ? chalk.green(\"yes\") : chalk.dim(\"no\"),\n formatDefault(prop.default),\n formatConstraints(prop),\n ]);\n\n console.log(\n formatTable(\n [\"Parameter\", \"Type\", \"Required\", \"Default\", \"Constraints\"],\n rows,\n ),\n );\n\n // Show detailed descriptions for each parameter\n const withDescriptions = Object.entries(props).filter(\n ([, p]) => p.description,\n );\n if (withDescriptions.length > 0) {\n console.log(`\\n${chalk.bold(\"Parameter Details\")}:\\n`);\n for (const [key, prop] of withDescriptions) {\n console.log(` ${chalk.cyan(key)}: ${prop.description}`);\n if (prop.enum) {\n console.log(\n ` Values: ${prop.enum.map((v) => chalk.green(String(v))).join(\", \")}`,\n );\n }\n }\n }\n }\n}\n\nfunction formatDefault(value: unknown): string {\n if (value === undefined || value === null) return chalk.dim(\"—\");\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value as string | number | boolean);\n}\n\nfunction formatConstraints(prop: SchemaProperty): string {\n const parts: string[] = [];\n\n if (prop.enum) {\n const enumStr = prop.enum.map(String).join(\"|\");\n parts.push(enumStr.length > 40 ? enumStr.substring(0, 37) + \"...\" : enumStr);\n }\n if (prop.minimum !== undefined) parts.push(`min:${prop.minimum}`);\n if (prop.maximum !== undefined) parts.push(`max:${prop.maximum}`);\n\n return parts.length > 0 ? parts.join(\", \") : chalk.dim(\"—\");\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;ACD9B,OAAOA,YAAW;AAClB,OAAO,UAAU;AACjB,OAAO,SAAS;;;ACFhB,OAAO,UAAU;AACjB,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AAYpB,IAAM,kBAAuB,UAAQ,WAAQ,GAAG,UAAU;AAC1D,IAAM,mBAAwB,UAAK,iBAAiB,kBAAkB;AAGtE,SAAS,uBAA6B;AACpC,MAAI,CAAI,cAAW,eAAe,G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iBAAiB,sDAAsD,EAC9E,OAAO,UAAU,gBAAgB,EACjC,OAAO,OAAO,MAAc,YAAgC;AAC3D,QAAM,YAAmB,MAAM,OAAO;AACxC,CAAC;AAGH,QACG,QAAQ,MAAM,EACd,YAAY,8CAA8C,EAC1D,OAAO,YAAY,oCAAoC,EACvD,OAAO,UAAU,gBAAgB,EACjC,OAAO,CAAC,YAAyB;AAChC,cAAY,OAAO;AACrB,CAAC;AAGH,QAAQ,MAAM;","names":["chalk","message","chalk","message","chalk","chalk","minutes","chalk","ora","ora","chalk","chalk","ora","ora","project","chalk","chalk","ora","ora","chalk","chalk","ora","listCommand","ora","chalk","chalk","ora","ora","chalk","chalk","ora","statusCommand","ora","chalk","chalk","ora","fs","path","ora","chalk","chalk","ora","listCommand","ora","chalk","tool","chalk","ora","ora","chalk","chalk","ora","listCommand","ora","chalk","chalk","ora","listCommand","ora","chalk","chalk","ora","Conf","fs","path","os","store","getCommand","ora","template","chalk","chalk","ora","createCommand","ora","chalk","ora","ora","chalk","ora","chalk","ora","chalk","ora","runCommand","ora","chalk","chalk","ora","statusCommand","watchStatus","getStatusOnce","printStatus","chalk","getStatusColor","getStatusIcon","chalk","ora","ora","chalk","chalk","ora","ora","chalk","chalk","ora","ora","step","chalk","chalk","ora","ora","chalk","ora","ora","ora","ora","chalk","ora","ora","chalk","chalk","ora","ora","model","chalk","require","listCommand","statusCommand","getCommand","createCommand","runCommand"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/commands/docs.ts","../src/commands/research/add.ts","../src/commands/research/analyze.ts","../src/lib/shell.ts","../src/commands/research/pipeline.ts","../src/commands/research/vision-providers.ts","../src/commands/research/assess.ts","../src/commands/research/insights.ts","../src/commands/research/list.ts","../src/commands/research/probe.ts","../src/commands/research/rank.ts","../src/commands/research/sample.ts","../src/commands/research/setup.ts","../src/commands/research/to-template.ts","../src/lib/context.ts","../src/commands/template/create.ts","../src/commands/template/get.ts","../src/commands/template/list.ts","../src/commands/template/model/list.ts","../src/commands/template/model/schema.ts","../src/commands/template/remove.ts","../src/commands/template/run.ts","../src/commands/template/status.ts","../src/commands/template/step/add.ts","../src/commands/template/step/info.ts","../src/commands/template/step/list.ts","../src/commands/template/step/remove.ts","../src/commands/template/step/update.ts","../src/commands/template/update.ts","../src/commands/template/use.ts","../src/commands/tool/execute.ts","../../../packages/steps/src/generate/generate-video.ts","../../../packages/steps/src/generate/generate-speech.ts","../src/lib/step-db.ts","../src/lib/workflow.ts","../src/commands/tool/list.ts","../src/commands/node/list.ts","../src/lib/node-graph.ts","../src/commands/node/add.ts","../src/commands/node/remove.ts","../src/commands/node/connect.ts","../src/commands/node/disconnect.ts","../src/commands/node/config.ts","../src/commands/node/execute.ts","../src/commands/node/layout.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { Command } from \"commander\";\n\nimport type { DocsOptions } from \"./commands/docs.js\";\nimport type { AddOptions as ResearchAddOptions } from \"./commands/research/add.js\";\nimport type { AnalyzeOptions } from \"./commands/research/analyze.js\";\nimport type { AssessOptions as ResearchAssessOptions } from \"./commands/research/assess.js\";\nimport type { InsightsOptions as ResearchInsightsOptions } from \"./commands/research/insights.js\";\nimport type { ListOptions as ResearchListOptions } from \"./commands/research/list.js\";\nimport type { ProbeOptions } from \"./commands/research/probe.js\";\nimport type { RankOptions as ResearchRankOptions } from \"./commands/research/rank.js\";\nimport type { SampleOptions as ResearchSampleOptions } from \"./commands/research/sample.js\";\nimport type { SetupOptions as ResearchSetupOptions } from \"./commands/research/setup.js\";\nimport type { ToTemplateOptions } from \"./commands/research/to-template.js\";\nimport type { CreateOptions as TemplateCreateOptions } from \"./commands/template/create.js\";\nimport type { GetOptions as TemplateGetOptions } from \"./commands/template/get.js\";\nimport type { ListOptions as TemplateListOptions } from \"./commands/template/list.js\";\nimport type { ModelListOptions } from \"./commands/template/model/list.js\";\nimport type { ModelSchemaOptions } from \"./commands/template/model/schema.js\";\nimport type { RemoveOptions as TemplateRemoveOptions } from \"./commands/template/remove.js\";\nimport type { RunOptions as TemplateRunOptions } from \"./commands/template/run.js\";\nimport type { StatusOptions as TemplateStatusOptions } from \"./commands/template/status.js\";\nimport type { StepAddOptions } from \"./commands/template/step/add.js\";\nimport type { StepInfoOptions } from \"./commands/template/step/info.js\";\nimport type { StepListOptions } from \"./commands/template/step/list.js\";\nimport type { StepRemoveOptions } from \"./commands/template/step/remove.js\";\nimport type { StepUpdateOptions } from \"./commands/template/step/update.js\";\nimport type { UpdateOptions as TemplateUpdateOptions } from \"./commands/template/update.js\";\nimport type { UseOptions as TemplateUseOptions } from \"./commands/template/use.js\";\nimport type { ExecuteOptions as ToolExecuteOptions } from \"./commands/tool/execute.js\";\nimport type { ToolListOptions } from \"./commands/tool/list.js\";\nimport type { NodeListOptions } from \"./commands/node/list.js\";\nimport type { NodeAddOptions } from \"./commands/node/add.js\";\nimport type { NodeRemoveOptions } from \"./commands/node/remove.js\";\nimport type { NodeConnectOptions } from \"./commands/node/connect.js\";\nimport type { NodeDisconnectOptions } from \"./commands/node/disconnect.js\";\nimport type { NodeConfigOptions } from \"./commands/node/config.js\";\nimport type { NodeExecuteOptions } from \"./commands/node/execute.js\";\nimport { docsCommand } from \"./commands/docs.js\";\nimport { addCommand as researchAddCommand } from \"./commands/research/add.js\";\nimport { analyzeCommand as researchAnalyzeCommand } from \"./commands/research/analyze.js\";\nimport { assessCommand as researchAssessCommand } from \"./commands/research/assess.js\";\nimport { insightsCommand as researchInsightsCommand } from \"./commands/research/insights.js\";\nimport { listCommand as researchListCommand } from \"./commands/research/list.js\";\nimport { probeCommand as researchProbeCommand } from \"./commands/research/probe.js\";\nimport { rankCommand as researchRankCommand } from \"./commands/research/rank.js\";\nimport { sampleCommand as researchSampleCommand } from \"./commands/research/sample.js\";\nimport { setupCommand as researchSetupCommand } from \"./commands/research/setup.js\";\nimport { toTemplateCommand as researchToTemplateCommand } from \"./commands/research/to-template.js\";\nimport { createCommand as templateCreateCommand } from \"./commands/template/create.js\";\nimport { getCommand as templateGetCommand } from \"./commands/template/get.js\";\nimport { listCommand as templateListCommand } from \"./commands/template/list.js\";\nimport { modelListCommand } from \"./commands/template/model/list.js\";\nimport { modelSchemaCommand } from \"./commands/template/model/schema.js\";\nimport { removeCommand as templateRemoveCommand } from \"./commands/template/remove.js\";\nimport { runCommand as templateRunCommand } from \"./commands/template/run.js\";\nimport { statusCommand as templateStatusCommand } from \"./commands/template/status.js\";\nimport { stepAddCommand } from \"./commands/template/step/add.js\";\nimport { stepInfoCommand } from \"./commands/template/step/info.js\";\nimport { stepListCommand } from \"./commands/template/step/list.js\";\nimport { stepRemoveCommand } from \"./commands/template/step/remove.js\";\nimport { stepUpdateCommand } from \"./commands/template/step/update.js\";\nimport { updateCommand as templateUpdateCommand } from \"./commands/template/update.js\";\nimport { useCommand as templateUseCommand } from \"./commands/template/use.js\";\nimport { executeCommand as toolExecCommand } from \"./commands/tool/execute.js\";\nimport { toolListCommand } from \"./commands/tool/list.js\";\nimport { nodeListCommand } from \"./commands/node/list.js\";\nimport { nodeAddCommand } from \"./commands/node/add.js\";\nimport { nodeRemoveCommand } from \"./commands/node/remove.js\";\nimport { nodeConnectCommand } from \"./commands/node/connect.js\";\nimport { nodeDisconnectCommand } from \"./commands/node/disconnect.js\";\nimport { nodeConfigCommand } from \"./commands/node/config.js\";\nimport { nodeExecuteCommand } from \"./commands/node/execute.js\";\nimport { nodeLayoutCommand } from \"./commands/node/layout.js\";\nimport type { NodeLayoutOptions } from \"./commands/node/layout.js\";\n\nconst program = new Command();\nconst require = createRequire(import.meta.url);\nconst packageJson = require(\"../package.json\") as { version: string };\n\nprogram\n .name(\"program\")\n .description(\"CLI for the Program desktop app (local-only)\")\n .version(packageJson.version);\n\n// ============================================\n// Tool commands\n// ============================================\nconst tool = program\n .command(\"tool\")\n .description(\"Execute composition tools directly\");\n\ntool\n .command(\"list\")\n .description(\"List available tools\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: ToolListOptions) => {\n toolListCommand(options);\n });\n\ntool\n .command(\"exec <toolName>\")\n .description(\"Execute a tool\")\n .option(\"--project <id>\", \"Composition ID\")\n .option(\"--params <json>\", \"Tool parameters as JSON\")\n .option(\"--params-file <path>\", \"Read tool parameters from a JSON file\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (toolName: string, options: ToolExecuteOptions) => {\n await toolExecCommand(toolName, options);\n });\n\n// ============================================\n// Template commands\n// ============================================\nconst template = program\n .command(\"template\")\n .description(\"Template management commands\");\n\ntemplate\n .command(\"list\")\n .description(\"List templates\")\n .option(\"--public-only\", \"Only show public templates\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: TemplateListOptions) => {\n await templateListCommand(options);\n });\n\ntemplate\n .command(\"get [id]\")\n .description(\"Get template details (uses active template if no ID)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateGetOptions) => {\n await templateGetCommand(id, options);\n });\n\ntemplate\n .command(\"create\")\n .description(\"Create a new template (auto-sets as active)\")\n .requiredOption(\"--name <name>\", \"Template name\")\n .option(\"--description <description>\", \"Template description\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: TemplateCreateOptions) => {\n await templateCreateCommand(options);\n });\n\ntemplate\n .command(\"update [id]\")\n .description(\"Update template metadata (uses active template if no ID)\")\n .option(\"--name <name>\", \"New template name\")\n .option(\"--description <description>\", \"New template description\")\n .option(\"--steps <json>\", \"Replace steps array with JSON\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateUpdateOptions) => {\n await templateUpdateCommand(id, options);\n });\n\ntemplate\n .command(\"remove [id]\")\n .description(\"Delete a template (uses active template if no ID)\")\n .option(\"--force\", \"Skip confirmation prompt\")\n .option(\"--json\", \"Output as JSON\")\n .action((id: string | undefined, options: TemplateRemoveOptions) => {\n templateRemoveCommand(id, options);\n });\n\ntemplate\n .command(\"run [id]\")\n .description(\"Execute a template (uses active template if no ID)\")\n .option(\"--input <json>\", \"JSON input for the workflow\")\n .option(\n \"--execution-id <id>\",\n \"Execution ID for tracking (created by desktop app)\",\n )\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: TemplateRunOptions) => {\n await templateRunCommand(id, options);\n });\n\ntemplate\n .command(\"status <executionId>\")\n .description(\"Check execution status\")\n .option(\"--watch\", \"Continuously poll for status updates\")\n .option(\"--interval <ms>\", \"Poll interval in milliseconds\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action((executionId: string, options: TemplateStatusOptions) => {\n templateStatusCommand(executionId, options);\n });\n\ntemplate\n .command(\"use <id>\")\n .description(\"Set the active template context\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: TemplateUseOptions) => {\n await templateUseCommand(id, options);\n });\n\n// Template step subgroup\nconst step = template\n .command(\"step\")\n .description(\"Manage template steps and discover step types\");\n\nstep\n .command(\"list\")\n .description(\"List available step types\")\n .option(\"--category <category>\", \"Filter by category\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: StepListOptions) => {\n stepListCommand(options);\n });\n\nstep\n .command(\"info <stepType>\")\n .description(\"Show step type details (inputs, outputs)\")\n .option(\"--json\", \"Output as JSON\")\n .action((stepType: string, options: StepInfoOptions) => {\n stepInfoCommand(stepType, options);\n });\n\nstep\n .command(\"add <stepType>\")\n .description(\"Add a step to the active template\")\n .option(\"--config <json>\", \"Step configuration as JSON\")\n .option(\"--at <position>\", \"Insert at position (0-indexed)\", parseInt)\n .option(\"--after <id>\", \"Insert after step with this ID\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (stepType: string, options: StepAddOptions) => {\n await stepAddCommand(stepType, options);\n });\n\nstep\n .command(\"remove <id>\")\n .description(\"Remove a step by its instance ID\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: StepRemoveOptions) => {\n await stepRemoveCommand(id, options);\n });\n\nstep\n .command(\"update <id>\")\n .description(\"Update a step's config by its instance ID\")\n .option(\"--config <json>\", \"Config to merge as JSON\")\n .option(\"--template <id>\", \"Template ID (overrides active template)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: StepUpdateOptions) => {\n await stepUpdateCommand(id, options);\n });\n\n// Template model subgroup\nconst model = template\n .command(\"model\")\n .description(\"Browse models and schemas\");\n\nmodel\n .command(\"list <category>\")\n .description(\"List models for a category (image, video, speech, text)\")\n .option(\"--json\", \"Output as JSON\")\n .action((category: string, options: ModelListOptions) => {\n modelListCommand(category, options);\n });\n\nmodel\n .command(\"schema <modelId>\")\n .description(\"Show full input schema for a model\")\n .option(\"--json\", \"Output as JSON\")\n .action((modelId: string, options: ModelSchemaOptions) => {\n modelSchemaCommand(modelId, options);\n });\n\n// ============================================\n// Research commands\n// ============================================\nconst research = program\n .command(\"research\")\n .description(\"Research item management and video analysis\");\n\nresearch\n .command(\"add <url>\")\n .description(\"Add a URL to the research database\")\n .option(\"--note <note>\", \"Optional note about this item\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (url: string, options: ResearchAddOptions) => {\n await researchAddCommand(url, options);\n });\n\nresearch\n .command(\"list\")\n .description(\"List research items\")\n .option(\n \"--platform <platform>\",\n \"Filter by platform (tiktok, instagram, youtube, twitter)\",\n )\n .option(\"--limit <limit>\", \"Maximum items to return\", parseInt)\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ResearchListOptions) => {\n await researchListCommand(options);\n });\n\nresearch\n .command(\"analyze <url-or-id>\")\n .description(\n \"Run full video analysis pipeline (download, transcribe, vision AI)\",\n )\n .option(\"--output <path>\", \"Write analysis JSON to file\")\n .option(\n \"--detail <mode>\",\n \"Analysis detail: transcript, quick (default), or full\",\n )\n .option(\"-y, --yes\", \"Skip cost confirmation prompt\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (urlOrId: string, options: AnalyzeOptions) => {\n await researchAnalyzeCommand(urlOrId, options);\n });\n\nresearch\n .command(\"probe <url-or-id>\")\n .description(\"Get video metadata (duration, title) without downloading\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (urlOrId: string, options: ProbeOptions) => {\n await researchProbeCommand(urlOrId, options);\n });\n\nresearch\n .command(\"to-template <id>\")\n .description(\"Convert a video analysis into a workflow template\")\n .option(\"--name <name>\", \"Template name\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: ToTemplateOptions) => {\n await researchToTemplateCommand(id, options);\n });\n\nresearch\n .command(\"setup\")\n .description(\"Download and set up all required analysis tools\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ResearchSetupOptions) => {\n await researchSetupCommand(options);\n });\n\nresearch\n .command(\"assess <id>\")\n .description(\"Store an agent-written assessment for a research item\")\n .option(\"--summary <text>\", \"Written assessment of the content\")\n .option(\"--verdict <verdict>\", \"keep or skip\")\n .option(\n \"--category <category>\",\n \"production-technique, format-pattern, platform-mechanics, tool-knowledge, audience-psychology, engagement-bait\",\n )\n .option(\n \"--techniques <list>\",\n 'Pipe-separated techniques (e.g. \"tech1|tech2\")',\n )\n .option(\n \"--tools <list>\",\n 'Pipe-separated tool names (e.g. \"ChatGPT|Cling 2.6\")',\n )\n .option(\"--key-quote <quote>\", \"Key quote from the transcript\")\n .option(\n \"--structured <json>\",\n \"Optional structured JSON data — only when the content contains genuinely reproducible visual or workflow DNA (see RESEARCH_AGENT.md)\",\n )\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: ResearchAssessOptions) => {\n await researchAssessCommand(id, options);\n });\n\nresearch\n .command(\"sample <id>\")\n .description(\"Extract keyframes from a research video at varying densities\")\n .option(\n \"--density <density>\",\n \"Sampling density: minimal (~6 frames), standard (1fps), dense (scene detection)\",\n )\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string, options: ResearchSampleOptions) => {\n await researchSampleCommand(id, options);\n });\n\nresearch\n .command(\"rank\")\n .description(\n \"Rank research items by content quality using local LLM (ollama)\",\n )\n .option(\"--model <model>\", \"Ollama model to use (default: llama3.2)\")\n .option(\"--platform <platform>\", \"Filter by platform\")\n .option(\"--limit <limit>\", \"Maximum items to rank\", parseInt)\n .option(\"--store\", \"Save rankings back to database\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: ResearchRankOptions) => {\n await researchRankCommand(options);\n });\n\nresearch\n .command(\"insights [id]\")\n .description(\n \"Extract actionable insights from transcripts using local LLM (ollama)\",\n )\n .option(\"--model <model>\", \"Ollama model to use (default: llama3.2)\")\n .option(\n \"--summary\",\n \"Synthesize all insights into consolidated knowledge base\",\n )\n .option(\"--platform <platform>\", \"Filter by platform\")\n .option(\n \"--min-score <score>\",\n \"Only process items ranked above this score\",\n parseInt,\n )\n .option(\"--json\", \"Output as JSON\")\n .action(async (id: string | undefined, options: ResearchInsightsOptions) => {\n await researchInsightsCommand(id, options);\n });\n\n// ============================================\n// Node commands\n// ============================================\nconst node = program\n .command(\"node\")\n .description(\"Scene node graph management\");\n\nnode\n .command(\"list\")\n .description(\"List nodes and edges in a scene's node graph\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: NodeListOptions) => {\n await nodeListCommand(options);\n });\n\nnode\n .command(\"add <type>\")\n .description(\"Add a node to the scene graph (prompt, number-value, reference-image, reference-video, model-select, generate-image, generate-video)\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--config <json>\", \"Initial config as JSON\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (type: string, options: NodeAddOptions) => {\n await nodeAddCommand(type, options);\n });\n\nnode\n .command(\"remove <nodeId>\")\n .description(\"Remove a node and its connected edges\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (nodeId: string, options: NodeRemoveOptions) => {\n await nodeRemoveCommand(nodeId, options);\n });\n\nnode\n .command(\"connect <sourceId> <targetId>\")\n .description(\"Connect two nodes with an edge\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .requiredOption(\"--source-handle <id>\", \"Source output handle name\")\n .requiredOption(\"--target-handle <id>\", \"Target input handle name\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (sourceId: string, targetId: string, options: NodeConnectOptions) => {\n await nodeConnectCommand(sourceId, targetId, options);\n });\n\nnode\n .command(\"disconnect <sourceId> [targetId]\")\n .description(\"Remove edges between two nodes, or all edges from a node with --all\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--source-handle <id>\", \"Filter by source output handle name\")\n .option(\"--target-handle <id>\", \"Filter by target input handle name\")\n .option(\"--all\", \"Remove all edges touching the node (no targetId needed)\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (sourceId: string, targetId: string | undefined, options: NodeDisconnectOptions) => {\n await nodeDisconnectCommand(sourceId, targetId, options);\n });\n\nnode\n .command(\"config <nodeId>\")\n .description(\"View or update a node's configuration\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--set <json>\", \"JSON to merge into node config\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (nodeId: string, options: NodeConfigOptions) => {\n await nodeConfigCommand(nodeId, options);\n });\n\nnode\n .command(\"execute\")\n .description(\"Execute the scene's node graph (topo sort, resolve inputs, run generation)\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--dry-run\", \"Show execution plan without running\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: NodeExecuteOptions) => {\n await nodeExecuteCommand(options);\n });\n\nnode\n .command(\"autolayout\")\n .description(\"Auto-layout nodes in a scene graph (left-to-right columns)\")\n .requiredOption(\"--scene <id>\", \"Scene ID\")\n .requiredOption(\"--project <id>\", \"Composition ID\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (options: NodeLayoutOptions) => {\n await nodeLayoutCommand(options);\n });\n\n// ============================================\n// Docs command\n// ============================================\nprogram\n .command(\"docs\")\n .description(\"Display CLI documentation and command schema\")\n .option(\"--schema\", \"Output full command schema as JSON\")\n .option(\"--json\", \"Output as JSON\")\n .action((options: DocsOptions) => {\n docsCommand(options);\n });\n\n// Parse arguments\nprogram.parse();\n","import type { OutputOptions } from \"../lib/output.js\";\nimport { outputSuccess } from \"../lib/output.js\";\n\nexport interface DocsOptions extends OutputOptions {\n schema?: boolean;\n}\n\n// Command schema for agents\nconst COMMAND_SCHEMA = {\n name: \"program\",\n version: \"0.1.0\",\n description: \"CLI for interacting with the Program video creation platform\",\n commands: {\n auth: {\n description: \"Authentication commands\",\n subcommands: {\n login: {\n description: \"Authenticate with the Program platform\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth login\",\n },\n logout: {\n description: \"Log out from the Program platform\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth logout\",\n },\n status: {\n description: \"Check authentication status\",\n options: {\n \"--json\": \"Output as JSON\",\n },\n example: \"program auth status --json\",\n },\n },\n },\n project: {\n description: \"Project management commands\",\n subcommands: {\n create: {\n description: \"Create a new project\",\n options: {\n \"--title <title>\": \"Project title\",\n \"--description <desc>\": \"Project description\",\n \"--json\": \"Output as JSON\",\n },\n example: 'program project create --title \"My Video\" --json',\n },\n list: {\n description: \"List projects\",\n options: {\n \"--limit <n>\": \"Maximum number of projects to return\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program project list --json\",\n },\n },\n },\n workflow: {\n description: \"Workflow template commands\",\n subcommands: {\n list: {\n description: \"List available workflow templates\",\n options: {\n \"--limit <n>\": \"Maximum number of templates to return\",\n \"--public-only\": \"Only show public templates\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program workflow list --json\",\n },\n run: {\n description: \"Execute a workflow template\",\n args: {\n templateId: \"ID of the template to run\",\n },\n options: {\n \"--project <id>\": \"Project ID to associate with execution\",\n \"--input <json>\": \"JSON input for the workflow\",\n \"--json\": \"Output as JSON\",\n },\n example:\n 'program workflow run tmpl_abc --project proj_123 --input \\'{\"files\":[\"src/main.ts\"]}\\' --json',\n },\n status: {\n description: \"Check workflow execution status\",\n args: {\n executionId: \"ID of the execution to check\",\n },\n options: {\n \"--watch\": \"Continuously poll for status updates\",\n \"--interval <ms>\": \"Poll interval in milliseconds (default: 2000)\",\n \"--json\": \"Output as JSON\",\n },\n example: \"program workflow status exec_789 --watch --json\",\n },\n },\n },\n docs: {\n description: \"Display CLI documentation\",\n options: {\n \"--schema\": \"Output full command schema as JSON\",\n },\n example: \"program docs --schema\",\n },\n },\n globalOptions: {\n \"--help\": \"Display help information\",\n \"--version\": \"Display version number\",\n },\n notes: [\n \"Always use --json flag for parseable output when integrating with agents\",\n \"Workflow inputs should be valid JSON strings\",\n \"Run 'program auth login' first to authenticate\",\n ],\n};\n\nexport function docsCommand(options: DocsOptions): void {\n if (options.schema ?? options.json) {\n outputSuccess(COMMAND_SCHEMA, { json: true });\n } else {\n printHumanDocs();\n }\n}\n\nfunction printHumanDocs(): void {\n console.log(`\nProgram CLI v${COMMAND_SCHEMA.version}\n${COMMAND_SCHEMA.description}\n\nCOMMANDS:\n\n auth login Authenticate with the Program platform\n auth logout Log out from the Program platform\n auth status Check authentication status\n\n project create Create a new project\n project list List projects\n\n workflow list List available workflow templates\n workflow run <id> Execute a workflow template\n workflow status <id> Check workflow execution status\n\n docs Display this documentation\n docs --schema Output full command schema as JSON\n\nGLOBAL OPTIONS:\n\n --json Output as JSON (recommended for agents)\n --help Display help information\n --version Display version number\n\nEXAMPLES:\n\n # Authenticate\n program auth login\n\n # Create a project\n program project create --title \"My Video\" --json\n\n # Run a workflow\n program workflow run tmpl_abc --project proj_123 --json\n\n # Watch execution progress\n program workflow status exec_789 --watch --json\n\nFor agent integration, always use the --json flag.\n`);\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { createResearch, isLocalAvailable } from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface AddOptions extends OutputOptions {\n note?: string;\n}\n\nexport async function addCommand(\n url: string,\n options: AddOptions,\n): Promise<void> {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\n \"Local Convex backend not running. Start the desktop app or run the backend manually.\",\n options,\n );\n return;\n }\n\n try {\n const itemId = await createResearch(url, options.note);\n\n if (options.json) {\n outputSuccess({ id: itemId, url }, options);\n } else {\n console.log(chalk.green(\"Added research item\"));\n console.log(chalk.dim(` ID: ${itemId}`));\n console.log(chalk.dim(` URL: ${url}`));\n }\n } catch (error: unknown) {\n const err = error as Error;\n outputError(err.message, options);\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { access, mkdir, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport type { AnalysisDetail, VideoAnalysis } from \"./types.js\";\nimport type { VisionProvider } from \"./vision-providers.js\";\nimport { setupAll } from \"../../lib/binary-manager.js\";\nimport {\n clearSteps,\n createResearch,\n getResearch,\n isLocalAvailable,\n patchResearch,\n upsertStep,\n} from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport { checkPrerequisites } from \"../../lib/shell.js\";\nimport {\n analyzeFrames,\n downloadVideo,\n extractAudio,\n extractFrames,\n getVideoDuration,\n mergeAnalysis,\n transcribeAudio,\n} from \"./pipeline.js\";\nimport { resolveVisionProvider } from \"./vision-providers.js\";\n\nexport interface AnalyzeOptions extends OutputOptions {\n output?: string;\n yes?: boolean;\n detail?: string;\n}\n\nexport async function analyzeCommand(\n urlOrId: string,\n options: AnalyzeOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const detail: AnalysisDetail =\n options.detail === \"full\"\n ? \"full\"\n : options.detail === \"transcript\"\n ? \"transcript\"\n : \"quick\";\n\n // 1. Check prerequisites — auto-setup if anything is missing\n let prereqSpinner = showSpinner ? ora(\"Checking tools...\").start() : null;\n\n const { ok, missing } = await checkPrerequisites();\n if (!ok) {\n if (prereqSpinner)\n prereqSpinner.text = `Setting up tools (${missing.join(\", \")})...`;\n if (!showSpinner) {\n console.log(`Setting up missing tools: ${missing.join(\", \")}`);\n }\n\n try {\n await setupAll(\n showSpinner\n ? {\n onStart: (name) => {\n if (prereqSpinner)\n prereqSpinner.text = `Downloading ${name}...`;\n },\n onProgress: (name, downloaded, total) => {\n if (total > 0) {\n const pct = Math.round((downloaded / total) * 100);\n if (prereqSpinner)\n prereqSpinner.text = `Downloading ${name}... ${pct}%`;\n }\n },\n onDone: (name) => {\n if (prereqSpinner) prereqSpinner.succeed(`${name} ready`);\n prereqSpinner = ora().start();\n },\n onSkip: () => {\n /* noop */\n },\n onError: (name, error) => {\n if (prereqSpinner) prereqSpinner.warn(`${name}: ${error}`);\n prereqSpinner = ora().start();\n },\n }\n : undefined,\n );\n } catch (error: unknown) {\n const err = error as Error;\n prereqSpinner?.fail(\"Setup failed\");\n outputError(`Failed to set up tools: ${err.message}`, options);\n return;\n }\n\n // Re-check after setup\n const recheck = await checkPrerequisites();\n if (!recheck.ok) {\n prereqSpinner?.fail(\"Setup incomplete\");\n outputError(\n `Still missing: ${recheck.missing.join(\", \")}. Try running 'program research setup' manually.`,\n options,\n );\n return;\n }\n }\n prereqSpinner?.succeed(\"Tools ready\");\n\n // Resolve vision API provider (not needed for transcript-only mode)\n let visionProvider: VisionProvider | null = null;\n if (detail !== \"transcript\") {\n const providerSpinner = showSpinner\n ? ora(\"Resolving vision provider...\").start()\n : null;\n try {\n visionProvider = await resolveVisionProvider();\n providerSpinner?.succeed(`Vision provider: ${visionProvider.name}`);\n } catch (error: unknown) {\n const err = error as Error;\n providerSpinner?.fail(\"No vision provider\");\n outputError(err.message, options);\n return;\n }\n }\n\n // 2. Resolve video URL\n let videoUrl: string;\n let researchItemId: string | null = null;\n\n // Heuristic: Convex IDs don't look like URLs\n const isUrl = urlOrId.startsWith(\"http://\") || urlOrId.startsWith(\"https://\");\n\n if (!isUrl) {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n const item = await getResearch(urlOrId);\n if (!item) {\n outputError(`Research item not found: ${urlOrId}`, options);\n return;\n }\n videoUrl = item.sourceUrl;\n researchItemId = item._id;\n\n if (!options.json) {\n console.log(chalk.dim(`Resolved: ${item.platform} — ${videoUrl}`));\n }\n } else {\n // Auto-create research item when given a URL with --local\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n videoUrl = urlOrId;\n try {\n researchItemId = await createResearch(videoUrl);\n if (!options.json) {\n console.log(chalk.dim(`Created research item: ${researchItemId}`));\n }\n } catch (error: unknown) {\n const err = error as Error;\n if (!options.json) {\n console.log(\n chalk.dim(`Note: Could not create research item: ${err.message}`),\n );\n }\n }\n }\n\n // 3. Create temp work directory\n const workDir = join(tmpdir(), `program-analyze-${randomUUID().slice(0, 8)}`);\n await mkdir(workDir, { recursive: true });\n\n let analysis: VideoAnalysis;\n\n // Helper to report step progress to local Convex\n const trackLocal = !!researchItemId;\n const track = async (\n step: string,\n label: string,\n status: \"pending\" | \"running\" | \"success\" | \"error\",\n extra?: { startedAt?: number; completedAt?: number; error?: string },\n ) => {\n if (trackLocal && researchItemId)\n await upsertStep(researchItemId, step, label, status, extra);\n };\n\n // Clear any previous steps and seed pipeline stages as pending\n const isTranscriptOnly = detail === \"transcript\";\n if (trackLocal) {\n if (researchItemId) await clearSteps(researchItemId);\n await track(\"download\", \"Downloading video\", \"pending\");\n await track(\n \"extract\",\n isTranscriptOnly ? \"Extracting audio\" : \"Extracting audio & frames\",\n \"pending\",\n );\n await track(\"transcribe\", \"Transcribing audio\", \"pending\");\n if (!isTranscriptOnly) {\n await track(\"analyze\", \"Analyzing video frames\", \"pending\");\n await track(\"merge\", \"Building analysis\", \"pending\");\n }\n }\n\n const errorSteps = isTranscriptOnly\n ? [\"download\", \"extract\", \"transcribe\"]\n : [\"download\", \"extract\", \"transcribe\", \"analyze\", \"merge\"];\n\n try {\n // 4a. Download video (or reuse desktop's cached copy)\n const dlSpinner = showSpinner ? ora(\"Downloading video...\").start() : null;\n await track(\"download\", \"Downloading video\", \"running\", {\n startedAt: Date.now(),\n });\n\n let videoPath: string;\n const cachedPath = researchItemId\n ? `/tmp/program-video-cache/${researchItemId.replace(/[^a-zA-Z0-9_-]/g, \"_\")}.mp4`\n : null;\n const hasCached = cachedPath\n ? await access(cachedPath).then(\n () => true,\n () => false,\n )\n : false;\n\n if (hasCached) {\n videoPath = cachedPath ?? \"\";\n dlSpinner?.succeed(\"Using cached video\");\n } else {\n videoPath = await downloadVideo(videoUrl, workDir);\n dlSpinner?.succeed(\"Video downloaded\");\n }\n await track(\"download\", \"Downloading video\", \"success\", {\n completedAt: Date.now(),\n });\n\n if (isTranscriptOnly) {\n // --- Transcript-only path: audio extraction + transcription, no vision ---\n\n const extractSpinner = showSpinner\n ? ora(\"Extracting audio...\").start()\n : null;\n await track(\"extract\", \"Extracting audio\", \"running\", {\n startedAt: Date.now(),\n });\n const [audioPath, duration] = await Promise.all([\n extractAudio(videoPath, workDir),\n getVideoDuration(videoPath),\n ]);\n await track(\"extract\", \"Extracting audio\", \"success\", {\n completedAt: Date.now(),\n });\n extractSpinner?.succeed(`Extracted audio (${duration.toFixed(1)}s)`);\n\n const transcribeSpinner = showSpinner\n ? ora(\"Transcribing audio...\").start()\n : null;\n await track(\"transcribe\", \"Transcribing audio\", \"running\", {\n startedAt: Date.now(),\n });\n const transcript = await transcribeAudio(audioPath, workDir);\n await track(\"transcribe\", \"Transcribing audio\", \"success\", {\n completedAt: Date.now(),\n });\n transcribeSpinner?.succeed(\n `Transcribed: ${transcript.segments.length} segments`,\n );\n\n // Build minimal analysis with transcript only\n analysis = {\n sourceUrl: videoUrl,\n duration,\n detail: \"transcript\",\n transcript,\n visualTranscript: [],\n scenes: [],\n style: {\n pacing: \"unknown\",\n format: \"unknown\",\n hooks: [],\n callToAction: \"\",\n },\n templateSuggestion: {\n steps:\n transcript.text.length > 0\n ? [\n {\n stepId: \"generateSpeech\",\n config: { text: \"${script}\", voice: \"default\" },\n },\n ]\n : [],\n },\n };\n } else {\n // --- Visual analysis path (quick / full) ---\n\n const extractSpinner = showSpinner\n ? ora(\"Extracting audio and frames...\").start()\n : null;\n await track(\"extract\", \"Extracting audio & frames\", \"running\", {\n startedAt: Date.now(),\n });\n\n const [audioPath, frameResult] = await Promise.all([\n extractAudio(videoPath, workDir),\n extractFrames(videoPath, workDir),\n ]);\n await track(\"extract\", \"Extracting audio & frames\", \"success\", {\n completedAt: Date.now(),\n });\n extractSpinner?.succeed(\n `Extracted ${frameResult.framePaths.length} frames (${frameResult.duration.toFixed(1)}s)`,\n );\n\n // Transcribe audio\n const transcribeSpinner = showSpinner\n ? ora(\"Transcribing audio...\").start()\n : null;\n await track(\"transcribe\", \"Transcribing audio\", \"running\", {\n startedAt: Date.now(),\n });\n const transcript = await transcribeAudio(audioPath, workDir);\n await track(\"transcribe\", \"Transcribing audio\", \"success\", {\n completedAt: Date.now(),\n });\n transcribeSpinner?.succeed(\n `Transcribed: ${transcript.segments.length} segments`,\n );\n\n // Cost estimate + confirmation\n const totalFrames = frameResult.framePaths.length;\n const costPerPrediction = 0.007;\n const costMultiplier = detail === \"full\" ? 1.5 : 1;\n const apiCalls = totalFrames + 1;\n const estimatedCost = apiCalls * costPerPrediction * costMultiplier;\n const modeLabel =\n detail === \"full\" ? \"full (structured JSON)\" : \"quick (text)\";\n\n if (!options.json) {\n console.log();\n console.log(\n chalk.bold(\"Cost Estimate\") +\n chalk.dim(` (${visionProvider?.name ?? \"unknown\"})`),\n );\n console.log(chalk.dim(\"─\".repeat(50)));\n console.log(`Mode: ${modeLabel}`);\n console.log(\n `Frames: ${totalFrames} (${frameResult.duration.toFixed(1)}s video)`,\n );\n console.log(\n `API calls: ${apiCalls} (${totalFrames} vision + 1 synthesis)`,\n );\n console.log(\n `Est. cost: ${chalk.yellow(`$${estimatedCost.toFixed(3)}`)}`,\n );\n if (detail === \"quick\") {\n console.log(\n chalk.dim(\n ` Use --detail full for structured per-frame analysis`,\n ),\n );\n }\n console.log();\n }\n\n if (!options.yes && !options.json && process.stdout.isTTY) {\n const confirmed = await confirm(\"Proceed with analysis?\");\n if (!confirmed) {\n console.log(chalk.dim(\"Aborted.\"));\n return;\n }\n console.log();\n }\n\n // Vision analysis\n const visionSpinner = showSpinner\n ? ora(`Analyzing ${totalFrames} frames (0/${totalFrames})...`).start()\n : null;\n await track(\"analyze\", `Analyzing ${totalFrames} frames`, \"running\", {\n startedAt: Date.now(),\n });\n const visionResult = await analyzeFrames(\n frameResult.framePaths,\n frameResult.frameTimes,\n frameResult.duration,\n detail,\n visionProvider ?? {\n name: \"none\",\n analyze: () => {\n throw new Error(\"No vision provider\");\n },\n },\n (completed, total) => {\n if (visionSpinner) {\n visionSpinner.text =\n completed < total\n ? `Analyzing frames (${completed}/${total})...`\n : `Synthesizing ${total} frame descriptions...`;\n }\n },\n );\n await track(\"analyze\", \"Analyzing video frames\", \"success\", {\n completedAt: Date.now(),\n });\n visionSpinner?.succeed(\n `Analyzed ${totalFrames} frames, identified ${visionResult.scenes.length} scenes`,\n );\n\n // Merge\n await track(\"merge\", \"Building analysis\", \"running\", {\n startedAt: Date.now(),\n });\n analysis = mergeAnalysis(\n transcript,\n visionResult,\n videoUrl,\n frameResult.duration,\n detail,\n );\n await track(\"merge\", \"Building analysis\", \"success\", {\n completedAt: Date.now(),\n });\n }\n } catch (error: unknown) {\n if (trackLocal) {\n const err = error as Error;\n for (const step of errorSteps) {\n await track(step, step, \"error\", { error: err.message }).catch(() => {\n /* noop */\n });\n }\n }\n throw error;\n } finally {\n await rm(workDir, { recursive: true, force: true }).catch(() => {\n /* noop */\n });\n }\n\n // 6. Store results\n if (options.output) {\n await writeFile(options.output, JSON.stringify(analysis, null, 2));\n if (!options.json) {\n console.log(chalk.green(\"✓\") + ` Analysis written to ${options.output}`);\n }\n }\n\n if (researchItemId) {\n const storeSpinner = showSpinner\n ? ora(\"Storing analysis...\").start()\n : null;\n try {\n await patchResearch(researchItemId, { analysis });\n storeSpinner?.succeed(\"Analysis stored to research item\");\n } catch (error: unknown) {\n const err = error as Error;\n storeSpinner?.fail(`Failed to store: ${err.message}`);\n }\n }\n\n // 7. Output\n if (options.json) {\n outputSuccess(analysis, options);\n } else {\n console.log();\n printAnalysisSummary(analysis);\n }\n}\n\nfunction printAnalysisSummary(analysis: VideoAnalysis): void {\n console.log(chalk.bold(\"Analysis Summary\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n console.log(`Duration: ${analysis.duration.toFixed(1)}s`);\n console.log(`Detail: ${analysis.detail}`);\n\n if (analysis.detail !== \"transcript\") {\n console.log(`Scenes: ${analysis.scenes.length}`);\n console.log(`Format: ${analysis.style.format}`);\n console.log(`Pacing: ${analysis.style.pacing}`);\n\n if (analysis.style.hooks.length > 0) {\n console.log(`Hooks: ${analysis.style.hooks.join(\", \")}`);\n }\n if (analysis.style.callToAction) {\n console.log(`CTA: ${analysis.style.callToAction}`);\n }\n }\n\n console.log(`Segments: ${analysis.transcript.segments.length}`);\n\n console.log();\n console.log(chalk.bold(\"Transcript\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n if (analysis.transcript.text) {\n if (analysis.detail === \"transcript\") {\n // Show full transcript with segment timings for transcript-only mode\n for (const seg of analysis.transcript.segments) {\n const ts = formatTime(seg.start);\n console.log(` ${chalk.cyan(ts)} ${seg.text}`);\n }\n } else {\n const preview =\n analysis.transcript.text.length > 200\n ? analysis.transcript.text.slice(0, 197) + \"...\"\n : analysis.transcript.text;\n console.log(preview);\n }\n } else {\n console.log(chalk.dim(\"(no speech detected)\"));\n }\n\n if (analysis.detail !== \"transcript\") {\n // Detailed visual transcript (full mode)\n if (\n analysis.detailedVisualTranscript &&\n analysis.detailedVisualTranscript.length > 0\n ) {\n console.log();\n console.log(chalk.bold(\"Visual Transcript\") + chalk.dim(\" (detailed)\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (const frame of analysis.detailedVisualTranscript) {\n const ts = `${frame.time}s`.padStart(6);\n console.log(chalk.cyan(ts) + chalk.bold(` ${frame.scene.location}`));\n for (const s of frame.subjects) {\n console.log(` ${s.description} — ${s.action}`);\n if (s.appearance) console.log(chalk.dim(` ${s.appearance}`));\n }\n if (frame.textOverlays.length > 0) {\n console.log(\n ` ${chalk.yellow(\"text:\")} ${frame.textOverlays.join(\" | \")}`,\n );\n }\n console.log(\n chalk.dim(\n ` ${frame.camera.framing} / ${frame.camera.angle} / ${frame.visualStyle}`,\n ) +\n (frame.colorPalette.length > 0\n ? chalk.dim(` — ${frame.colorPalette.join(\", \")}`)\n : \"\"),\n );\n }\n } else if (analysis.visualTranscript.length > 0) {\n console.log();\n console.log(chalk.bold(\"Visual Transcript\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (const frame of analysis.visualTranscript) {\n const ts = `${frame.time}s`.padStart(6);\n console.log(` ${chalk.cyan(ts)} ${frame.description}`);\n }\n }\n\n console.log();\n console.log(chalk.bold(\"Scene Breakdown\"));\n console.log(chalk.dim(\"─\".repeat(50)));\n for (const scene of analysis.scenes) {\n const time = `${formatTime(scene.startTime)}-${formatTime(scene.endTime)}`;\n console.log(\n ` ${chalk.cyan(time)} ${chalk.dim(scene.visualStyle)} ${scene.description}`,\n );\n if (scene.textOverlays.length > 0) {\n console.log(\n ` ${chalk.yellow(\"text:\")} ${scene.textOverlays.join(\" | \")}`,\n );\n }\n }\n }\n\n if (analysis.templateSuggestion.steps.length > 0) {\n console.log();\n console.log(\n chalk.bold(\n `Template Suggestion: ${analysis.templateSuggestion.steps.length} steps`,\n ),\n );\n for (const step of analysis.templateSuggestion.steps) {\n console.log(` → ${step.stepId}`);\n }\n }\n}\n\nfunction formatTime(seconds: number): string {\n const m = Math.floor(seconds / 60);\n const s = Math.floor(seconds % 60);\n return `${m}:${s.toString().padStart(2, \"0\")}`;\n}\n\nfunction confirm(question: string): Promise<boolean> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n return new Promise((resolve) => {\n rl.question(`${question} [Y/n] `, (answer) => {\n rl.close();\n resolve(answer.trim().toLowerCase() !== \"n\");\n });\n });\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nimport { resolveBinary } from \"./binary-manager.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface ShellResult {\n stdout: string;\n stderr: string;\n}\n\n/**\n * Run a managed binary. Resolves the binary path automatically\n * (prefers ~/.program/bin/, falls back to system PATH).\n */\nexport async function runShell(\n command: string,\n args: string[],\n options?: { timeout?: number; cwd?: string },\n): Promise<ShellResult> {\n const binPath = await resolveBinary(command);\n try {\n return await execFileAsync(binPath, args, {\n timeout: options?.timeout ?? 300_000,\n cwd: options?.cwd,\n maxBuffer: 50 * 1024 * 1024,\n });\n } catch (error: unknown) {\n const err = error as { stderr?: string; message?: string };\n throw new Error(`${command} failed: ${err.stderr ?? err.message}`);\n }\n}\n\n/**\n * Run a command using an explicit absolute path (no resolution).\n */\nexport async function runShellAbsolute(\n binPath: string,\n args: string[],\n options?: { timeout?: number; cwd?: string },\n): Promise<ShellResult> {\n try {\n return await execFileAsync(binPath, args, {\n timeout: options?.timeout ?? 300_000,\n cwd: options?.cwd,\n maxBuffer: 50 * 1024 * 1024,\n });\n } catch (error: unknown) {\n const err = error as { stderr?: string; message?: string };\n throw new Error(`${binPath} failed: ${err.stderr ?? err.message}`);\n }\n}\n\nexport async function checkBinary(name: string): Promise<boolean> {\n try {\n await execFileAsync(\"which\", [name]);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Check prerequisites using the binary manager.\n * Returns ready=true if all tools are available (managed or system).\n */\nexport async function checkPrerequisites(): Promise<{\n ok: boolean;\n missing: string[];\n}> {\n const { checkSetup } = await import(\"./binary-manager.js\");\n const result = await checkSetup();\n return { ok: result.ready, missing: result.missing };\n}\n","import { access, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type {\n AnalysisDetail,\n Scene,\n TemplateSuggestion,\n Transcript,\n TranscriptSegment,\n VideoAnalysis,\n VideoStyle,\n} from \"./types.js\";\nimport type { AnalyzeResult, VisionProvider } from \"./vision-providers.js\";\nimport {\n getWhisperModelPath,\n resolveBinary,\n} from \"../../lib/binary-manager.js\";\nimport { checkBinary, runShell, runShellAbsolute } from \"../../lib/shell.js\";\n\n// ============================================\n// PIPELINE STEP 1: Download video\n// ============================================\n\nexport async function downloadVideo(\n url: string,\n workDir: string,\n): Promise<string> {\n const outPath = join(workDir, \"video.mp4\");\n await runShell(\n \"yt-dlp\",\n [\n \"-f\",\n \"mp4/bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best\",\n \"--merge-output-format\",\n \"mp4\",\n \"-o\",\n outPath,\n \"--no-playlist\",\n \"--no-warnings\",\n url,\n ],\n { timeout: 120_000, cwd: workDir },\n );\n return outPath;\n}\n\n// ============================================\n// PIPELINE STEP 2: Extract audio\n// ============================================\n\nexport async function extractAudio(\n videoPath: string,\n workDir: string,\n): Promise<string> {\n const outPath = join(workDir, \"audio.wav\");\n await runShell(\n \"ffmpeg\",\n [\n \"-i\",\n videoPath,\n \"-vn\",\n \"-acodec\",\n \"pcm_s16le\",\n \"-ar\",\n \"16000\",\n \"-ac\",\n \"1\",\n \"-y\",\n outPath,\n ],\n { timeout: 60_000 },\n );\n return outPath;\n}\n\n// ============================================\n// PIPELINE STEP 3: Extract frames\n// ============================================\n\nexport interface FrameExtractionResult {\n framePaths: string[];\n frameTimes: number[]; // timestamps in seconds (0.5, 1, 2, 3, ...)\n duration: number;\n}\n\n/** Get video duration in seconds via ffprobe. */\nexport async function getVideoDuration(videoPath: string): Promise<number> {\n const probeResult = await runShell(\n \"ffprobe\",\n [\n \"-v\",\n \"error\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"csv=p=0\",\n videoPath,\n ],\n { timeout: 30_000 },\n );\n return parseFloat(probeResult.stdout.trim()) || 0;\n}\n\nexport async function extractFrames(\n videoPath: string,\n workDir: string,\n): Promise<FrameExtractionResult> {\n const duration = await getVideoDuration(videoPath);\n\n // Extract hook frame at 0.5s (the first visual impression)\n const hookFrame = join(workDir, \"frame_hook.jpg\");\n await runShell(\n \"ffmpeg\",\n [\n \"-i\",\n videoPath,\n \"-vf\",\n \"scale=512:-1:flags=lanczos\",\n \"-ss\",\n \"0.5\",\n \"-frames:v\",\n \"1\",\n \"-q:v\",\n \"2\",\n \"-y\",\n hookFrame,\n ],\n { timeout: 30_000 },\n );\n\n // Extract frames at 1 FPS (starts at 1s)\n const framePattern = join(workDir, \"frame_%04d.jpg\");\n await runShell(\n \"ffmpeg\",\n [\n \"-i\",\n videoPath,\n \"-vf\",\n \"fps=1,scale=512:-1:flags=lanczos\",\n \"-q:v\",\n \"2\",\n \"-y\",\n framePattern,\n ],\n { timeout: 120_000 },\n );\n\n // Collect: hook frame first, then 1fps frames\n const files = await readdir(workDir);\n const fpsFrames = files\n .filter(\n (f) =>\n f.startsWith(\"frame_\") && f !== \"frame_hook.jpg\" && f.endsWith(\".jpg\"),\n )\n .sort()\n .map((f) => join(workDir, f));\n\n // Build ordered list: 0.5s hook, then 1s, 2s, 3s, ...\n const framePaths = [hookFrame, ...fpsFrames];\n const frameTimes = [0.5, ...fpsFrames.map((_, i) => i + 1)];\n\n return { framePaths, frameTimes, duration };\n}\n\n// ============================================\n// PIPELINE STEP 4: Transcribe audio\n// ============================================\n\nexport async function transcribeAudio(\n wavPath: string,\n workDir: string,\n): Promise<Transcript> {\n // Priority: mlx_whisper (system) > whisper (system) > managed whisper-cli (whisper.cpp)\n const hasMlxWhisper = await checkBinary(\"mlx_whisper\");\n const hasPythonWhisper = await checkBinary(\"whisper\");\n\n if (hasMlxWhisper || hasPythonWhisper) {\n // Use Python-based whisper\n const whisperCmd = hasMlxWhisper ? \"mlx_whisper\" : \"whisper\";\n await runShell(\n whisperCmd,\n [\n wavPath,\n \"--output_format\",\n \"json\",\n \"--output_dir\",\n workDir,\n \"--language\",\n \"en\",\n ...(hasMlxWhisper ? [] : [\"--model\", \"base\"]),\n ],\n { timeout: 300_000, cwd: workDir },\n );\n } else {\n // Use managed whisper.cpp binary\n const whisperCliPath = await resolveBinary(\"whisper-cli\");\n const modelPath = getWhisperModelPath();\n\n // Verify model exists\n try {\n await access(modelPath);\n } catch {\n throw new Error(\n \"Whisper model not found. Run 'program research setup' first.\",\n );\n }\n\n const outJson = join(workDir, \"audio\");\n await runShellAbsolute(\n whisperCliPath,\n [\n \"-m\",\n modelPath,\n \"-f\",\n wavPath,\n \"-l\",\n \"en\",\n \"--output-json-full\",\n \"-of\",\n outJson,\n ],\n { timeout: 300_000, cwd: workDir },\n );\n }\n\n // Parse the JSON output\n const jsonPath = join(workDir, \"audio.json\");\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf-8\");\n } catch {\n // Some whisper versions output with different names\n const files = await readdir(workDir);\n const jsonFile = files.find(\n (f) => f.endsWith(\".json\") && !f.startsWith(\"frame\"),\n );\n if (!jsonFile) {\n return { text: \"\", segments: [] };\n }\n raw = await readFile(join(workDir, jsonFile), \"utf-8\");\n }\n\n const data = JSON.parse(raw) as {\n // Python whisper / mlx_whisper format\n text?: string;\n segments?: {\n start: number;\n end: number;\n text: string;\n }[];\n // whisper.cpp --output-json-full format\n transcription?: {\n offsets: { from: number; to: number };\n text: string;\n }[];\n };\n\n let segments: TranscriptSegment[];\n\n if (data.segments && data.segments.length > 0) {\n // Python whisper format: { text, segments: [{ start, end, text }] }\n segments = data.segments.map((s) => ({\n start: s.start,\n end: s.end,\n text: s.text.trim(),\n }));\n } else if (data.transcription && data.transcription.length > 0) {\n // whisper.cpp format: { transcription: [{ offsets: { from, to }, text }] }\n // offsets are in milliseconds\n segments = data.transcription.map((t) => ({\n start: t.offsets.from / 1000,\n end: t.offsets.to / 1000,\n text: t.text.trim(),\n }));\n } else {\n segments = [];\n }\n\n return {\n text: data.text?.trim() ?? segments.map((s) => s.text).join(\" \"),\n segments,\n };\n}\n\n// ============================================\n// PIPELINE STEP 5: Analyze frames via Vision API\n// ============================================\n\nconst VISION_PROMPT = `You are analyzing frames extracted at 1 FPS from a short-form social media video (TikTok/Instagram Reel).\n\nEach image is one frame. Frame 1 = 0:00, Frame 2 = 0:01, etc.\n\nAnalyze the video and return a JSON object with this exact structure:\n\n{\n \"scenes\": [\n {\n \"index\": 0,\n \"startTime\": 0,\n \"endTime\": 3,\n \"description\": \"Brief description of what happens in this scene\",\n \"textOverlays\": [\"Any text visible on screen\"],\n \"transition\": \"cut|fade|swipe|zoom|dissolve|none\",\n \"visualStyle\": \"talking-head|b-roll|text-on-screen|product-shot|screen-recording|montage|split-screen\",\n \"audioMood\": \"energetic|calm|dramatic|humorous|informative|urgent\"\n }\n ],\n \"style\": {\n \"pacing\": \"fast|medium|slow\",\n \"format\": \"tutorial|story|review|transformation|comparison|day-in-life|educational|entertainment|promotion\",\n \"hooks\": [\"List the opening hooks used in first 3 seconds\"],\n \"callToAction\": \"The call to action at the end, if any\"\n }\n}\n\nGroup consecutive frames with the same visual content into a single scene. Be specific about text overlays — transcribe them exactly. Return ONLY valid JSON, no markdown or explanation.`;\n\nexport async function analyzeFrames(\n framePaths: string[],\n frameTimes: number[],\n duration: number,\n detail: AnalysisDetail,\n provider: VisionProvider,\n onFrame?: (completed: number, total: number) => void,\n): Promise<{\n scenes: Scene[];\n style: VideoStyle;\n visionResult: AnalyzeResult;\n}> {\n const visionResult = await provider.analyze(\n framePaths,\n frameTimes,\n VISION_PROMPT,\n duration,\n detail,\n onFrame,\n );\n const { raw } = visionResult;\n\n // Extract JSON from synthesis response (model might wrap in markdown)\n const jsonMatch = /\\{[\\s\\S]*\\}/.exec(raw);\n if (!jsonMatch) {\n throw new Error(\"Failed to extract JSON from vision model response\");\n }\n\n const parsed = JSON.parse(jsonMatch[0]) as {\n scenes?: Partial<Scene>[];\n style?: Partial<VideoStyle>;\n };\n\n return {\n visionResult,\n scenes: (parsed.scenes ?? []).map((s, i) => ({\n index: s.index ?? i,\n startTime: s.startTime ?? 0,\n endTime: s.endTime ?? 0,\n description: s.description ?? \"\",\n textOverlays: s.textOverlays ?? [],\n transition: s.transition ?? \"cut\",\n visualStyle: s.visualStyle ?? \"unknown\",\n audioMood: s.audioMood ?? \"unknown\",\n })),\n style: {\n pacing: parsed.style?.pacing ?? \"medium\",\n format: parsed.style?.format ?? \"unknown\",\n hooks: parsed.style?.hooks ?? [],\n callToAction: parsed.style?.callToAction ?? \"\",\n },\n };\n}\n\n// ============================================\n// PIPELINE STEP 6: Merge analysis\n// ============================================\n\nexport function mergeAnalysis(\n transcript: Transcript,\n analysisResult: {\n scenes: Scene[];\n style: VideoStyle;\n visionResult: AnalyzeResult;\n },\n sourceUrl: string,\n duration: number,\n detail: AnalysisDetail,\n): VideoAnalysis {\n const { scenes, style, visionResult } = analysisResult;\n\n // Generate template suggestion based on analysis\n const templateSuggestion = generateTemplateSuggestion(\n scenes,\n style,\n transcript,\n );\n\n return {\n sourceUrl,\n duration,\n detail,\n transcript,\n visualTranscript: visionResult.visualTranscript,\n detailedVisualTranscript: visionResult.detailedTranscript,\n scenes,\n style,\n templateSuggestion,\n };\n}\n\n// ============================================\n// TEMPLATE SUGGESTION GENERATOR\n// ============================================\n\nfunction generateTemplateSuggestion(\n scenes: Scene[],\n style: VideoStyle,\n transcript: Transcript,\n): TemplateSuggestion {\n const steps: TemplateSuggestion[\"steps\"] = [];\n\n // Step 1: Generate script based on the style/format\n steps.push({\n stepId: \"generateScript\",\n config: {\n prompt: `Write a ${style.format} style short-form video script. Pacing: ${style.pacing}. ${style.hooks.length > 0 ? `Opening hook style: ${style.hooks[0]}` : \"\"}${style.callToAction ? ` End with CTA: \"${style.callToAction}\"` : \"\"}`,\n style: style.format,\n duration:\n scenes.length > 0\n ? (scenes[scenes.length - 1]?.endTime ?? 30) -\n (scenes[0]?.startTime ?? 0)\n : 30,\n },\n });\n\n // Step 2: Set composition metadata\n steps.push({\n stepId: \"setMetadata\",\n config: {\n title: \"${title}\",\n description: `${style.format} video - ${style.pacing} pacing`,\n fps: 30,\n width: 1080,\n height: 1920,\n },\n });\n\n // Step 3: Plan scenes based on analysis\n for (const scene of scenes) {\n steps.push({\n stepId: \"planScene\",\n config: {\n type:\n scene.visualStyle === \"text-on-screen\" ? \"code_scene\" : \"video_scene\",\n description: scene.description,\n duration: scene.endTime - scene.startTime,\n textOverlays: scene.textOverlays,\n visualStyle: scene.visualStyle,\n transition: scene.transition,\n },\n });\n }\n\n // Step 4: Generate speech if there's a transcript\n if (transcript.text.length > 0) {\n steps.push({\n stepId: \"generateSpeech\",\n config: {\n text: \"${script}\",\n voice: \"default\",\n },\n });\n }\n\n return { steps };\n}\n","import { readFile } from \"node:fs/promises\";\n\nimport type { AnalysisDetail, DetailedFrameDescription } from \"./types.js\";\nimport { getIntegrationApiKey } from \"../../lib/local-convex.js\";\n\n// ============================================\n// VISION PROVIDER ABSTRACTION\n// ============================================\n\nexport interface FrameDescription {\n time: number; // seconds\n description: string;\n}\n\nexport interface AnalyzeResult {\n raw: string;\n visualTranscript: FrameDescription[];\n detailedTranscript?: DetailedFrameDescription[];\n}\n\nexport interface VisionProvider {\n name: string;\n analyze(\n framePaths: string[],\n frameTimes: number[],\n prompt: string,\n duration: number,\n detail: AnalysisDetail,\n onFrame?: (completed: number, total: number) => void,\n ): Promise<AnalyzeResult>;\n}\n\n// ============================================\n// PROMPTS\n// ============================================\n\nconst QUICK_FRAME_PROMPT = `Describe this single frame from a short-form social media video.\nBe specific and concise (2-3 sentences). Include:\n- What is visually happening (people, objects, actions, camera angle)\n- Any text overlays on screen — transcribe them exactly\n- Visual style: talking-head / b-roll / text-on-screen / product-shot / screen-recording / montage / split-screen\nDo NOT include timestamps or frame numbers in your response.`;\n\nconst FULL_FRAME_PROMPT = `Analyze this single frame from a short-form social media video and return a JSON object with this exact structure. Be extremely specific and detailed — this data feeds a video generation pipeline.\n\n{\n \"scene\": {\n \"location\": \"specific setting (e.g. 'modern kitchen with marble countertops', 'outdoor cafe patio')\",\n \"background\": [\"list every visible background element\"],\n \"lighting\": \"detailed lighting description (direction, quality, color temperature, shadows)\"\n },\n \"subjects\": [\n {\n \"description\": \"who/what is the main subject\",\n \"action\": \"exactly what they are doing\",\n \"position\": \"where in frame (center, left-third, etc.)\",\n \"appearance\": \"clothing, hair, distinguishing features — be specific\"\n }\n ],\n \"textOverlays\": [\"transcribe every text overlay exactly as shown, empty array if none\"],\n \"camera\": {\n \"angle\": \"eye-level / high / low / overhead / dutch\",\n \"framing\": \"extreme-close-up / close-up / medium / medium-wide / wide / full-body\",\n \"movement\": \"static / pan-left / pan-right / tilt-up / tilt-down / zoom-in / zoom-out / tracking / handheld\"\n },\n \"visualStyle\": \"talking-head / b-roll / text-on-screen / product-shot / screen-recording / montage / split-screen / transition\",\n \"colorPalette\": [\"3-5 dominant colors as descriptive names (e.g. 'warm gold', 'deep navy')\"],\n \"mood\": \"one or two words capturing the emotional tone\"\n}\n\nReturn ONLY valid JSON, no markdown fences or explanation. Do NOT include timestamps.`;\n\n// ============================================\n// REPLICATE PROVIDER\n// ============================================\n\nconst REPLICATE_API = \"https://api.replicate.com/v1/predictions\";\nconst REPLICATE_MODEL = \"lucataco/ollama-llama3.2-vision-90b\";\nconst PREDICTION_TIMEOUT = 60_000; // 60s per prediction\nconst CONCURRENCY = 5;\n\nfunction createReplicateProvider(apiKey: string): VisionProvider {\n return {\n name: \"replicate\",\n async analyze(framePaths, frameTimes, prompt, duration, detail, onFrame) {\n const framePromptTemplate =\n detail === \"full\" ? FULL_FRAME_PROMPT : QUICK_FRAME_PROMPT;\n const maxTokensPerFrame = detail === \"full\" ? 512 : 256;\n\n // Phase 1: Analyze EVERY frame\n const frameDescriptions = await analyzeAllFrames(\n apiKey,\n framePaths,\n frameTimes,\n framePromptTemplate,\n maxTokensPerFrame,\n onFrame,\n );\n\n // Build visual transcript (always present — plain text summary)\n const visualTranscript: FrameDescription[] = [];\n let detailedTranscript: DetailedFrameDescription[] | undefined;\n\n if (detail === \"full\") {\n detailedTranscript = [];\n for (let i = 0; i < frameDescriptions.length; i++) {\n const time = frameTimes[i] ?? i;\n const parsed = parseDetailedFrame(frameDescriptions[i] ?? \"\", time);\n detailedTranscript.push(parsed);\n // Also build a plain-text summary for the synthesis step\n visualTranscript.push({\n time,\n description: summarizeDetailedFrame(parsed),\n });\n }\n } else {\n for (let i = 0; i < frameDescriptions.length; i++) {\n visualTranscript.push({\n time: frameTimes[i] ?? i,\n description: frameDescriptions[i] ?? \"\",\n });\n }\n }\n\n // Phase 2: Synthesis — scenes/style JSON from per-frame descriptions\n const synthesisInput = buildSynthesisPrompt(\n visualTranscript,\n duration,\n prompt,\n );\n const raw = await replicateTextPrediction(apiKey, synthesisInput);\n\n return { raw, visualTranscript, detailedTranscript };\n },\n };\n}\n\n// ============================================\n// FRAME ANALYSIS\n// ============================================\n\nasync function analyzeAllFrames(\n apiKey: string,\n framePaths: string[],\n frameTimes: number[],\n framePrompt: string,\n maxTokens: number,\n onFrame?: (completed: number, total: number) => void,\n): Promise<string[]> {\n const results: string[] = new Array<string>(framePaths.length).fill(\"\");\n let nextIdx = 0;\n let completed = 0;\n const videoDuration = frameTimes[frameTimes.length - 1] ?? framePaths.length;\n\n async function worker() {\n while (nextIdx < framePaths.length) {\n const i = nextIdx++;\n const framePath = framePaths[i] ?? \"\";\n const time = frameTimes[i] ?? i;\n\n const buffer = await readFile(framePath);\n const imageDataUri = `data:image/jpeg;base64,${buffer.toString(\"base64\")}`;\n\n const prompt = `This is frame at ${time}s of a ${videoDuration}s video.\\n\\n${framePrompt}`;\n\n results[i] = await replicateVisionPrediction(\n apiKey,\n imageDataUri,\n prompt,\n maxTokens,\n );\n\n completed++;\n onFrame?.(completed, framePaths.length);\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < Math.min(CONCURRENCY, framePaths.length); w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n\n return results;\n}\n\n// ============================================\n// DETAILED FRAME PARSING\n// ============================================\n\nfunction parseDetailedFrame(\n raw: string,\n time: number,\n): DetailedFrameDescription {\n try {\n const jsonMatch = /\\{[\\s\\S]*\\}/.exec(raw);\n if (!jsonMatch) throw new Error(\"No JSON found\");\n const data = JSON.parse(jsonMatch[0]) as Record<string, unknown>;\n\n const scene = data.scene as Record<string, unknown> | undefined;\n const subjects = (data.subjects ?? []) as Record<string, unknown>[];\n const camera = data.camera as Record<string, unknown> | undefined;\n\n return {\n time,\n scene: {\n location: String((scene?.location as string | undefined) ?? \"unknown\"),\n background: Array.isArray(scene?.background)\n ? (scene.background as string[])\n : [],\n lighting: String((scene?.lighting as string | undefined) ?? \"unknown\"),\n },\n subjects: subjects.map((s) => ({\n description: String((s.description as string | undefined) ?? \"\"),\n action: String((s.action as string | undefined) ?? \"\"),\n position: String((s.position as string | undefined) ?? \"center\"),\n appearance: s.appearance ? String(s.appearance as string) : undefined,\n })),\n textOverlays: Array.isArray(data.textOverlays)\n ? (data.textOverlays as string[])\n : [],\n camera: {\n angle: String((camera?.angle as string | undefined) ?? \"eye-level\"),\n framing: String((camera?.framing as string | undefined) ?? \"medium\"),\n movement: String((camera?.movement as string | undefined) ?? \"static\"),\n },\n visualStyle: String(\n (data.visualStyle as string | undefined) ?? \"unknown\",\n ),\n colorPalette: Array.isArray(data.colorPalette)\n ? (data.colorPalette as string[])\n : [],\n mood: String((data.mood as string | undefined) ?? \"neutral\"),\n description: buildDescriptionFromDetailed(data),\n };\n } catch {\n // Fallback: model returned plain text instead of JSON\n return {\n time,\n scene: { location: \"unknown\", background: [], lighting: \"unknown\" },\n subjects: [],\n textOverlays: [],\n camera: { angle: \"eye-level\", framing: \"medium\", movement: \"static\" },\n visualStyle: \"unknown\",\n colorPalette: [],\n mood: \"neutral\",\n description: raw.trim(),\n };\n }\n}\n\nfunction buildDescriptionFromDetailed(data: Record<string, unknown>): string {\n const parts: string[] = [];\n const scene = data.scene as Record<string, unknown> | undefined;\n const subjects = (data.subjects ?? []) as Record<string, unknown>[];\n\n if (scene?.location) parts.push(String(scene.location as string));\n for (const s of subjects) {\n if (s.description && s.action) {\n parts.push(`${s.description as string} ${s.action as string}`);\n }\n }\n if (data.visualStyle) parts.push(`[${data.visualStyle as string}]`);\n\n return parts.join(\". \") || \"No description available\";\n}\n\nfunction summarizeDetailedFrame(frame: DetailedFrameDescription): string {\n const parts: string[] = [];\n if (frame.scene.location !== \"unknown\") parts.push(frame.scene.location);\n for (const s of frame.subjects) {\n parts.push(`${s.description} ${s.action}`.trim());\n }\n if (frame.textOverlays.length > 0) {\n parts.push(`Text: \"${frame.textOverlays.join('\" \"')}\"`);\n }\n parts.push(`[${frame.visualStyle}]`);\n return parts.join(\". \");\n}\n\n// ============================================\n// SYNTHESIS\n// ============================================\n\nfunction buildSynthesisPrompt(\n visualTranscript: FrameDescription[],\n duration: number,\n structuredPrompt: string,\n): string {\n const frameLines = visualTranscript\n .map((f) => `[${f.time}s]: ${f.description}`)\n .join(\"\\n\");\n\n return `You have per-second visual descriptions of a ${duration.toFixed(1)}s video (${visualTranscript.length} frames).\n\nVISUAL TRANSCRIPT:\n${frameLines}\n\nUsing the visual transcript above, ${structuredPrompt}`;\n}\n\n// ============================================\n// REPLICATE API CALLS\n// ============================================\n\ninterface ReplicatePrediction {\n id: string;\n status: string;\n output?: string | string[];\n error?: string;\n}\n\nfunction extractOutput(prediction: ReplicatePrediction): string {\n if (Array.isArray(prediction.output)) {\n return prediction.output.join(\"\");\n }\n return prediction.output ?? \"\";\n}\n\nasync function replicateVisionPrediction(\n apiKey: string,\n imageDataUri: string,\n prompt: string,\n maxTokens: number,\n): Promise<string> {\n const res = await fetch(REPLICATE_API, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n Prefer: \"wait\",\n },\n signal: AbortSignal.timeout(PREDICTION_TIMEOUT),\n body: JSON.stringify({\n model: REPLICATE_MODEL,\n input: {\n image: imageDataUri,\n prompt,\n temperature: 0.1,\n max_tokens: maxTokens,\n },\n }),\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(`Replicate API error: ${res.status} ${text}`);\n }\n\n const prediction = (await res.json()) as ReplicatePrediction;\n\n if (prediction.status === \"succeeded\") {\n return extractOutput(prediction);\n }\n if (prediction.status === \"failed\") {\n throw new Error(`Replicate prediction failed: ${prediction.error}`);\n }\n\n return await pollPrediction(apiKey, prediction.id);\n}\n\nasync function replicateTextPrediction(\n apiKey: string,\n prompt: string,\n): Promise<string> {\n const res = await fetch(REPLICATE_API, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n Prefer: \"wait\",\n },\n signal: AbortSignal.timeout(PREDICTION_TIMEOUT),\n body: JSON.stringify({\n model: REPLICATE_MODEL,\n input: {\n prompt,\n temperature: 0.1,\n max_tokens: 4096,\n },\n }),\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(`Replicate API error: ${res.status} ${text}`);\n }\n\n const prediction = (await res.json()) as ReplicatePrediction;\n\n if (prediction.status === \"succeeded\") {\n return extractOutput(prediction);\n }\n if (prediction.status === \"failed\") {\n throw new Error(`Replicate prediction failed: ${prediction.error}`);\n }\n\n return await pollPrediction(apiKey, prediction.id);\n}\n\nasync function pollPrediction(\n apiKey: string,\n predictionId: string,\n): Promise<string> {\n const deadline = Date.now() + PREDICTION_TIMEOUT;\n\n while (Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 2000));\n\n const res = await fetch(`${REPLICATE_API}/${predictionId}`, {\n headers: { Authorization: `Bearer ${apiKey}` },\n });\n\n if (!res.ok) {\n throw new Error(`Replicate poll error: ${res.status}`);\n }\n\n const prediction = (await res.json()) as ReplicatePrediction;\n\n if (prediction.status === \"succeeded\") {\n return extractOutput(prediction);\n }\n\n if (prediction.status === \"failed\" || prediction.status === \"canceled\") {\n throw new Error(\n `Replicate prediction ${prediction.status}: ${prediction.error}`,\n );\n }\n }\n\n throw new Error(\"Replicate prediction timed out\");\n}\n\n// ============================================\n// STUB PROVIDERS\n// ============================================\n\nfunction createFalProvider(_apiKey: string): VisionProvider {\n return {\n name: \"fal\",\n analyze() {\n return Promise.reject(\n new Error(\"Fal vision provider not yet implemented. Use Replicate.\"),\n );\n },\n };\n}\n\nfunction createHuggingFaceProvider(_apiKey: string): VisionProvider {\n return {\n name: \"huggingface\",\n analyze() {\n return Promise.reject(\n new Error(\n \"HuggingFace vision provider not yet implemented. Use Replicate.\",\n ),\n );\n },\n };\n}\n\n// ============================================\n// FACTORY + RESOLVER\n// ============================================\n\nexport function createVisionProvider(\n name: string,\n apiKey: string,\n): VisionProvider {\n switch (name) {\n case \"replicate\":\n return createReplicateProvider(apiKey);\n case \"fal\":\n return createFalProvider(apiKey);\n case \"huggingface\":\n return createHuggingFaceProvider(apiKey);\n default:\n throw new Error(`Unknown vision provider: ${name}`);\n }\n}\n\nconst PROVIDER_PRIORITY = [\"replicate\", \"fal\", \"huggingface\"] as const;\n\nexport async function resolveVisionProvider(): Promise<VisionProvider> {\n for (const provider of PROVIDER_PRIORITY) {\n const key = await getIntegrationApiKey(provider);\n if (key) {\n return createVisionProvider(provider, key);\n }\n }\n\n throw new Error(\n \"No vision API key configured. Add a Replicate, Fal, or HuggingFace API key in Settings.\",\n );\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n getResearch,\n isLocalAvailable,\n patchResearch,\n} from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface AssessOptions extends OutputOptions {\n summary?: string;\n verdict?: string;\n category?: string;\n techniques?: string;\n tools?: string;\n keyQuote?: string;\n structured?: string;\n}\n\nconst VALID_VERDICTS = [\"keep\", \"skip\"] as const;\nconst _VALID_CATEGORIES = [\n \"production-technique\",\n \"format-pattern\",\n \"platform-mechanics\",\n \"tool-knowledge\",\n \"audience-psychology\",\n \"engagement-bait\",\n] as const;\n\nexport async function assessCommand(\n id: string,\n options: AssessOptions,\n): Promise<void> {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n if (!options.summary) {\n outputError(\n \"Assessment requires --summary. Write your analysis of this content.\",\n options,\n );\n return;\n }\n\n if (\n !options.verdict ||\n !VALID_VERDICTS.includes(options.verdict as (typeof VALID_VERDICTS)[number])\n ) {\n outputError(\n `Assessment requires --verdict (${VALID_VERDICTS.join(\" | \")}).`,\n options,\n );\n return;\n }\n\n const item = await getResearch(id);\n if (!item) {\n outputError(`Research item not found: ${id}`, options);\n return;\n }\n\n const category = options.category ?? \"unknown\";\n const techniques = options.techniques\n ? options.techniques\n .split(\"|\")\n .map((t) => t.trim())\n .filter(Boolean)\n : [];\n const tools = options.tools\n ? options.tools\n .split(\"|\")\n .map((t) => t.trim())\n .filter(Boolean)\n : [];\n\n // Parse structured data if provided\n let structured: Record<string, unknown> | undefined;\n if (options.structured) {\n try {\n structured = JSON.parse(options.structured) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --structured. Must be valid JSON.\", options);\n return;\n }\n }\n\n const assessment: Record<string, unknown> = {\n summary: options.summary,\n verdict: options.verdict as \"keep\" | \"skip\",\n category,\n techniques,\n tools,\n keyQuote: options.keyQuote ?? \"\",\n assessedAt: Date.now(),\n source: \"agent\",\n };\n\n if (structured) {\n assessment.structured = structured;\n }\n\n // Store assessment alongside existing analysis data\n const meta = item.metadata ?? {};\n const analysis = (meta.analysis ?? {}) as Record<string, unknown>;\n await patchResearch(item._id, {\n ...meta,\n analysis: { ...analysis, assessment },\n });\n\n if (options.json) {\n outputSuccess(\n {\n id: item._id,\n title: item.title ?? item.sourceUrl,\n assessment,\n },\n options,\n );\n return;\n }\n\n const verdictBadge =\n options.verdict === \"keep\"\n ? chalk.green.bold(\"KEEP\")\n : chalk.red.bold(\"SKIP\");\n\n console.log();\n console.log(\n `${verdictBadge} ${chalk.dim(`[${category}]`)} ${chalk.bold((item.title ?? item.sourceUrl).slice(0, 60))}`,\n );\n console.log();\n console.log(` ${options.summary}`);\n if (techniques.length > 0) {\n console.log();\n console.log(chalk.dim(\" Techniques:\"));\n for (const tech of techniques) {\n console.log(` - ${tech}`);\n }\n }\n if (tools.length > 0) {\n console.log(chalk.dim(\" Tools:\"), tools.join(\", \"));\n }\n if (options.keyQuote) {\n console.log(\n chalk.dim(\" Key quote:\"),\n chalk.italic(`\"${options.keyQuote}\"`),\n );\n }\n if (structured) {\n console.log();\n console.log(chalk.dim(\" Structured data:\"), chalk.dim(\"attached\"));\n }\n console.log();\n console.log(chalk.green(\"Assessment stored.\"));\n}\n","import chalk from \"chalk\";\n\nimport type { LocalResearchItem } from \"../../lib/local-convex.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n getResearch,\n isLocalAvailable,\n listResearch,\n patchResearch,\n} from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface InsightsOptions extends OutputOptions {\n model?: string;\n summary?: boolean;\n platform?: string;\n minScore?: number;\n}\n\nconst OLLAMA_URL = \"http://127.0.0.1:11434\";\n\n// ============================================\n// PROMPTS — designed to work on 3B+ models\n// ============================================\n\nconst EXTRACT_PROMPT = `Analyse this video transcript as a content strategist. Be direct and honest.\n\nSUMMARY: 2-3 sentences. What is the creator showing? Is the technique replicable? What's useful vs filler? If it's engagement bait, say so.\nTECHNIQUES: Follow-able instructions. Empty array if none real.\nCONTENT PATTERNS: How is the VIDEO structured? Hook, pacing, CTA.\nTOOLS: Specific names. Empty array if none.\nKEY QUOTE: Most insightful sentence from transcript.\nONE-LINER: Your synthesis — what you learned, not what they said.\nVERDICT: \"keep\" if replicable value, \"skip\" if noise.\nCATEGORY: production-technique, format-pattern, platform-mechanics, tool-knowledge, audience-psychology, or engagement-bait.\n\nRespond with ONLY valid JSON:\n{\"summary\": \"...\", \"techniques\": [], \"contentPatterns\": [], \"tools\": [], \"keyQuote\": \"...\", \"oneLiner\": \"...\", \"verdict\": \"keep\", \"category\": \"...\"}`;\n\nconst SUMMARIZE_PROMPT = `You are building a knowledge base from video research insights. Your job is to organise by CAPABILITY, not by source.\n\nGroup insights into these categories:\n- Production techniques: Specific workflows for creating content (prompting, generation, editing)\n- Format patterns: Structures that work (hook types, pacing, scene composition, CTA placement)\n- Platform mechanics: What platforms reward (algorithm signals, engagement patterns)\n- Tool knowledge: What specific tools do well, their limitations, version-specific capabilities\n- Audience psychology: Why certain content performs (curiosity gaps, pattern interrupts, social proof)\n\nOnly include techniques confirmed by multiple sources. One video is an observation. Three is evidence.\n\nRespond with ONLY valid JSON:\n{\n \"themes\": [\n {\n \"name\": \"<capability category>\",\n \"insights\": [\"<specific actionable insight written as instruction>\"],\n \"sources\": <number of videos supporting this>\n }\n ],\n \"topTechniques\": [\"<top 5 most replicable techniques, written as instructions>\"],\n \"toolStack\": [\"<tools confirmed across multiple videos with version info>\"],\n \"templateRecommendations\": [\"<content structures ready to templatise, with evidence count>\"]\n}`;\n\ninterface OllamaResponse {\n response: string;\n done: boolean;\n}\n\ninterface ItemInsights {\n summary: string;\n techniques: string[];\n contentPatterns: string[];\n tools: string[];\n keyQuote: string;\n oneLiner: string;\n verdict: \"keep\" | \"skip\";\n category: string;\n model: string;\n extractedAt: number;\n}\n\ninterface ConsolidatedSummary {\n themes: {\n name: string;\n insights: string[];\n sources: number;\n }[];\n topTechniques: string[];\n toolStack: string[];\n templateRecommendations: string[];\n}\n\nasync function isOllamaRunning(): Promise<boolean> {\n try {\n const res = await fetch(`${OLLAMA_URL}/api/tags`, {\n signal: AbortSignal.timeout(2000),\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n\nasync function ollamaGenerate(model: string, prompt: string): Promise<string> {\n const res = await fetch(`${OLLAMA_URL}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n prompt,\n stream: false,\n options: { temperature: 0.3, num_predict: 500 },\n }),\n });\n\n if (!res.ok) {\n throw new Error(`Ollama request failed: ${res.status} ${res.statusText}`);\n }\n\n const data = (await res.json()) as OllamaResponse;\n return data.response;\n}\n\nfunction getTranscript(item: LocalResearchItem): string | null {\n const meta = item.metadata;\n const analysis = meta?.analysis as Record<string, unknown> | undefined;\n const transcript = analysis?.transcript as { text?: string } | undefined;\n return transcript?.text ?? null;\n}\n\nfunction getExistingInsights(item: LocalResearchItem): ItemInsights | null {\n const meta = item.metadata;\n const analysis = meta?.analysis as Record<string, unknown> | undefined;\n return (analysis?.insights as ItemInsights | undefined) ?? null;\n}\n\nfunction getRanking(item: LocalResearchItem): { score: number } | null {\n const meta = item.metadata;\n const analysis = meta?.analysis as Record<string, unknown> | undefined;\n return (analysis?.ranking as { score: number } | undefined) ?? null;\n}\n\nasync function extractInsights(\n model: string,\n item: LocalResearchItem,\n transcriptText: string,\n): Promise<ItemInsights> {\n const maxChars = 2000;\n const truncated =\n transcriptText.length > maxChars\n ? transcriptText.slice(0, maxChars) + \"...\"\n : transcriptText;\n\n const prompt = `${EXTRACT_PROMPT}\\n\\nVideo: \"${item.title ?? item.sourceUrl}\"\\nPlatform: ${item.platform}\\nAuthor: ${item.authorName ?? \"Unknown\"}\\n\\nTranscript:\\n${truncated}`;\n\n const raw = await ollamaGenerate(model, prompt);\n\n const jsonMatch = /\\{[\\s\\S]*\\}/.exec(raw);\n if (!jsonMatch) {\n return {\n summary: \"Could not extract insights from this transcript.\",\n techniques: [],\n contentPatterns: [],\n tools: [],\n keyQuote: \"\",\n oneLiner: \"Could not extract insights\",\n verdict: \"skip\" as const,\n category: \"unknown\",\n model,\n extractedAt: Date.now(),\n };\n }\n\n try {\n const parsed = JSON.parse(jsonMatch[0]) as Partial<ItemInsights>;\n return {\n summary: parsed.summary ?? \"\",\n techniques: Array.isArray(parsed.techniques) ? parsed.techniques : [],\n contentPatterns: Array.isArray(parsed.contentPatterns)\n ? parsed.contentPatterns\n : [],\n tools: Array.isArray(parsed.tools) ? parsed.tools : [],\n keyQuote: parsed.keyQuote ?? \"\",\n oneLiner: parsed.oneLiner ?? \"\",\n verdict:\n parsed.verdict === \"keep\" ? (\"keep\" as const) : (\"skip\" as const),\n category: parsed.category ?? \"unknown\",\n model,\n extractedAt: Date.now(),\n };\n } catch {\n return {\n summary: \"Could not parse LLM response.\",\n techniques: [],\n contentPatterns: [],\n tools: [],\n keyQuote: \"\",\n oneLiner: \"Could not parse LLM response\",\n verdict: \"skip\" as const,\n category: \"unknown\",\n model,\n extractedAt: Date.now(),\n };\n }\n}\n\nexport async function insightsCommand(\n idOrAll: string | undefined,\n options: InsightsOptions,\n): Promise<void> {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\n \"Local Convex backend not running. Start the desktop app or run the backend manually.\",\n options,\n );\n return;\n }\n\n const model = options.model ?? \"llama3.2\";\n\n // ── Summary mode: aggregate existing insights ──\n if (options.summary) {\n return summarizeInsights(model, options);\n }\n\n // ── Extraction mode ──\n const ollamaUp = await isOllamaRunning();\n if (!ollamaUp) {\n outputError(\"Ollama is not running. Start it with: ollama serve\", options);\n return;\n }\n\n // Single item or all\n let items: LocalResearchItem[];\n if (idOrAll) {\n const item = await getResearch(idOrAll);\n if (!item) {\n outputError(`Research item not found: ${idOrAll}`, options);\n return;\n }\n items = [item];\n } else {\n items = await listResearch(options.platform);\n }\n\n // Filter to items with transcripts, optionally by min rank score\n const minScore = options.minScore ?? 0;\n const candidates = items.filter((item) => {\n const transcript = getTranscript(item);\n if (!transcript || transcript.length === 0) return false;\n if (minScore > 0) {\n const ranking = getRanking(item);\n if (!ranking || ranking.score < minScore) return false;\n }\n // Skip items that already have insights (unless single item)\n if (!idOrAll && getExistingInsights(item)) return false;\n return true;\n });\n\n if (candidates.length === 0) {\n if (options.json) {\n outputSuccess([], options);\n } else {\n console.log(\n chalk.dim(\n \"No items need insight extraction. All transcribed items already have insights, or no transcripts found.\",\n ),\n );\n }\n return;\n }\n\n if (!options.json) {\n console.log(\n chalk.bold(\n `Extracting insights from ${candidates.length} items with ${model}...`,\n ),\n );\n console.log();\n }\n\n const results: { item: LocalResearchItem; insights: ItemInsights }[] = [];\n\n for (let i = 0; i < candidates.length; i++) {\n const item = candidates[i];\n if (!item) continue;\n const transcript = getTranscript(item);\n if (!transcript) continue;\n\n if (!options.json) {\n process.stdout.write(\n chalk.dim(\n ` [${i + 1}/${candidates.length}] ${(item.title ?? item.sourceUrl).slice(0, 50)}...`,\n ),\n );\n }\n\n const insights = await extractInsights(model, item, transcript);\n results.push({ item, insights });\n\n // Store insights back to Convex\n const meta = item.metadata ?? {};\n const analysis = (meta.analysis ?? {}) as Record<string, unknown>;\n await patchResearch(item._id, {\n ...meta,\n analysis: { ...analysis, insights },\n });\n\n if (!options.json) {\n process.stdout.write(\n `\\r ${chalk.green(\"done\")} ${(item.title ?? item.sourceUrl).slice(0, 50)}\\n`,\n );\n }\n }\n\n if (options.json) {\n outputSuccess(\n results.map(({ item, insights }) => ({\n id: item._id,\n title: item.title ?? item.sourceUrl,\n platform: item.platform,\n author: item.authorName,\n summary: insights.summary,\n verdict: insights.verdict,\n category: insights.category,\n techniques: insights.techniques,\n contentPatterns: insights.contentPatterns,\n tools: insights.tools,\n keyQuote: insights.keyQuote,\n oneLiner: insights.oneLiner,\n })),\n options,\n );\n return;\n }\n\n // Print results\n console.log();\n for (const { item, insights } of results) {\n const title = item.title ?? item.sourceUrl;\n const verdictBadge =\n insights.verdict === \"keep\"\n ? chalk.green.bold(\" KEEP \")\n : chalk.red.bold(\" SKIP \");\n const categoryBadge = chalk.dim(`[${insights.category}]`);\n\n console.log(\n `${verdictBadge} ${categoryBadge} ${chalk.bold(title.slice(0, 60))}`,\n );\n console.log();\n console.log(` ${insights.summary}`);\n console.log();\n if (insights.techniques.length > 0) {\n console.log(chalk.dim(\" Techniques:\"));\n for (const tech of insights.techniques) {\n console.log(` - ${tech}`);\n }\n }\n if (insights.tools.length > 0) {\n console.log(chalk.dim(\" Tools:\"), insights.tools.join(\", \"));\n }\n if (insights.keyQuote) {\n console.log(\n chalk.dim(\" Key quote:\"),\n chalk.italic(`\"${insights.keyQuote.slice(0, 100)}\"`),\n );\n }\n console.log(chalk.cyan(` >> ${insights.oneLiner}`));\n console.log();\n console.log(chalk.dim(\" ---\"));\n console.log();\n }\n\n const kept = results.filter((r) => r.insights.verdict === \"keep\").length;\n const skipped = results.length - kept;\n console.log(chalk.green(`Done. ${kept} worth keeping, ${skipped} to skip.`));\n}\n\n// ============================================\n// SUMMARY MODE\n// ============================================\n\nasync function summarizeInsights(\n model: string,\n options: InsightsOptions,\n): Promise<void> {\n const items = await listResearch(options.platform);\n\n // Collect all existing insights\n const allInsights: {\n item: LocalResearchItem;\n insights: ItemInsights;\n }[] = [];\n\n for (const item of items) {\n const insights = getExistingInsights(item);\n if (insights) {\n allInsights.push({ item, insights });\n }\n }\n\n if (allInsights.length === 0) {\n if (options.json) {\n outputSuccess({ items: 0, themes: [] }, options);\n } else {\n console.log(\n chalk.dim(\n \"No insights found. Run 'program research insights --local' first to extract them.\",\n ),\n );\n }\n return;\n }\n\n // Check if ollama is needed for the LLM summary\n const ollamaUp = await isOllamaRunning();\n\n if (!ollamaUp) {\n // Fallback: just aggregate without LLM\n return printRawSummary(allInsights, options);\n }\n\n if (!options.json) {\n console.log(\n chalk.bold(\n `Synthesizing insights from ${allInsights.length} items with ${model}...`,\n ),\n );\n console.log();\n }\n\n // Build the prompt with all insights\n const insightsText = allInsights\n .map(({ item, insights }) => {\n const title = item.title ?? item.sourceUrl;\n return `[${title}]\\nSummary: ${insights.oneLiner}\\nTechniques: ${insights.techniques.join(\", \")}\\nPatterns: ${insights.contentPatterns.join(\", \")}\\nTools: ${insights.tools.join(\", \")}`;\n })\n .join(\"\\n\\n\");\n\n // Truncate if too long for small model context\n const maxChars = 4000;\n const truncated =\n insightsText.length > maxChars\n ? insightsText.slice(0, maxChars) + \"\\n...(truncated)\"\n : insightsText;\n\n const prompt = `${SUMMARIZE_PROMPT}\\n\\n${truncated}`;\n const raw = await ollamaGenerate(model, prompt);\n const jsonMatch = /\\{[\\s\\S]*\\}/.exec(raw);\n\n if (!jsonMatch) {\n return printRawSummary(allInsights, options);\n }\n\n try {\n const summary = JSON.parse(jsonMatch[0]) as ConsolidatedSummary;\n\n if (options.json) {\n outputSuccess(\n {\n itemCount: allInsights.length,\n ...summary,\n },\n options,\n );\n return;\n }\n\n console.log(chalk.bold.underline(\"Research Insights Summary\"));\n console.log(chalk.dim(`Based on ${allInsights.length} analyzed items`));\n console.log();\n\n if (summary.themes.length > 0) {\n console.log(chalk.bold(\"Themes:\"));\n for (const theme of summary.themes) {\n console.log(` ${chalk.cyan(theme.name)} (${theme.sources} sources)`);\n for (const insight of theme.insights) {\n console.log(` - ${insight}`);\n }\n }\n console.log();\n }\n\n if (summary.topTechniques.length > 0) {\n console.log(chalk.bold(\"Top Techniques:\"));\n for (const tech of summary.topTechniques) {\n console.log(` - ${tech}`);\n }\n console.log();\n }\n\n if (summary.toolStack.length > 0) {\n console.log(chalk.bold(\"Tool Stack:\"));\n console.log(` ${summary.toolStack.join(\", \")}`);\n console.log();\n }\n\n if (summary.templateRecommendations.length > 0) {\n console.log(chalk.bold(\"Template Recommendations:\"));\n for (const rec of summary.templateRecommendations) {\n console.log(` - ${rec}`);\n }\n console.log();\n }\n } catch {\n return printRawSummary(allInsights, options);\n }\n}\n\nfunction printRawSummary(\n allInsights: { item: LocalResearchItem; insights: ItemInsights }[],\n options: InsightsOptions,\n): void {\n // Simple aggregation without LLM\n const allTechniques = new Map<string, number>();\n const allTools = new Set<string>();\n const allPatterns = new Set<string>();\n\n for (const { insights } of allInsights) {\n for (const tech of insights.techniques) {\n allTechniques.set(tech, (allTechniques.get(tech) ?? 0) + 1);\n }\n for (const tool of insights.tools) {\n allTools.add(tool);\n }\n for (const pattern of insights.contentPatterns) {\n allPatterns.add(pattern);\n }\n }\n\n if (options.json) {\n outputSuccess(\n {\n itemCount: allInsights.length,\n techniques: Object.fromEntries(allTechniques),\n tools: [...allTools],\n patterns: [...allPatterns],\n },\n options,\n );\n return;\n }\n\n console.log(chalk.bold.underline(\"Research Insights (Raw Aggregate)\"));\n console.log(chalk.dim(`Based on ${allInsights.length} analyzed items`));\n console.log();\n\n console.log(chalk.bold(\"Techniques:\"));\n const sorted = [...allTechniques.entries()].sort((a, b) => b[1] - a[1]);\n for (const [tech, count] of sorted.slice(0, 15)) {\n console.log(` ${chalk.dim(`(${count}x)`)} ${tech}`);\n }\n console.log();\n\n if (allTools.size > 0) {\n console.log(chalk.bold(\"Tools mentioned:\"));\n console.log(` ${[...allTools].join(\", \")}`);\n console.log();\n }\n\n if (allPatterns.size > 0) {\n console.log(chalk.bold(\"Content Patterns:\"));\n for (const pattern of [...allPatterns].slice(0, 10)) {\n console.log(` - ${pattern}`);\n }\n console.log();\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { isLocalAvailable, listResearch } from \"../../lib/local-convex.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface ListOptions extends OutputOptions {\n platform?: string;\n limit?: number;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\n \"Local Convex backend not running. Start the desktop app or run the backend manually.\",\n options,\n );\n return;\n }\n\n try {\n const items = await listResearch(options.platform, options.limit);\n\n if (options.json) {\n outputSuccess(items, options);\n return;\n }\n\n if (items.length === 0) {\n console.log(chalk.dim(\"No research items found.\"));\n return;\n }\n\n console.log(chalk.bold(`Research Items (${items.length})`));\n console.log();\n\n const rows = items.map((item) => {\n const analysis = item.metadata?.analysis as\n | Record<string, unknown>\n | undefined;\n const assessment = analysis?.assessment as\n | { verdict?: string }\n | undefined;\n const insights = analysis?.insights as { verdict?: string } | undefined;\n const scenes = analysis?.scenes as unknown[] | undefined;\n const transcript = analysis?.transcript as { text?: string } | undefined;\n\n let status: string;\n if (assessment?.verdict) {\n status =\n assessment.verdict === \"keep\"\n ? chalk.green(\"keep\")\n : chalk.red(\"skip\");\n } else if (insights?.verdict) {\n status =\n insights.verdict === \"keep\" ? chalk.green(\"keep\") : chalk.red(\"skip\");\n } else if (scenes && scenes.length > 0) {\n status = chalk.green(\"analyzed\");\n } else if (transcript?.text) {\n status = chalk.blue(\"transcribed\");\n } else {\n status = chalk.dim(\"pending\");\n }\n const title = item.title ?? item.sourceUrl;\n const displayTitle =\n title.length > 50 ? title.slice(0, 47) + \"...\" : title;\n\n return [\n item._id.slice(0, 12) + \"...\",\n platformBadge(item.platform),\n displayTitle,\n item.authorName ?? chalk.dim(\"-\"),\n status,\n ];\n });\n\n console.log(\n formatTable([\"ID\", \"Platform\", \"Title / URL\", \"Author\", \"Status\"], rows),\n );\n } catch (error: unknown) {\n const err = error as Error;\n outputError(err.message, options);\n }\n}\n\nfunction platformBadge(platform: string): string {\n switch (platform) {\n case \"tiktok\":\n return chalk.bgBlack.white(\" TT \");\n case \"instagram\":\n return chalk.bgMagenta.white(\" IG \");\n case \"youtube\":\n return chalk.bgRed.white(\" YT \");\n case \"twitter\":\n return chalk.bgBlack.white(\" X \");\n default:\n return chalk.bgGray.white(\" ?? \");\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n getResearch,\n isLocalAvailable,\n patchResearch,\n} from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport { runShell } from \"../../lib/shell.js\";\n\nexport type ProbeOptions = OutputOptions;\n\nexport interface VideoProbe {\n duration: number;\n title?: string;\n uploader?: string;\n viewCount?: number;\n likeCount?: number;\n resolution?: string;\n}\n\n/**\n * TikTok fallback: yt-dlp's TikTok extractor is broken upstream.\n * Scrapes the page source for stats embedded in server-rendered JSON.\n * TikTok embeds playCount, diggCount, duration as raw JSON in the HTML.\n * Short URLs (vt.tiktok.com) are resolved via HEAD redirect first.\n * Note: TikTok may rate-limit or IP-block heavy usage.\n */\nexport async function probeTikTok(\n videoUrl: string,\n): Promise<VideoProbe | null> {\n let resolvedUrl = videoUrl;\n try {\n const res = await fetch(videoUrl, { method: \"HEAD\", redirect: \"follow\" });\n if (res.url) resolvedUrl = res.url;\n } catch {\n // Use original URL\n }\n\n try {\n const res = await fetch(resolvedUrl, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n },\n });\n const html = await res.text();\n const stats = parseTikTokStats(html);\n if (!stats) return null;\n return {\n duration: stats.duration ?? 0,\n viewCount: stats.viewCount,\n likeCount: stats.likeCount,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Instagram view counts via public GraphQL endpoint.\n * Uses Instagram's web GraphQL API (doc_id=8845758582119845) with the\n * public X-IG-App-ID header — no auth, cookies, or user credentials needed.\n * Extracts video_view_count and edge_media_preview_like.count from\n * the xdt_shortcode_media response.\n */\nexport async function probeInstagramViews(\n videoUrl: string,\n): Promise<{ viewCount?: number; likeCount?: number } | null> {\n const shortcode = extractInstagramShortcode(videoUrl);\n if (!shortcode) return null;\n\n try {\n const variables = JSON.stringify({ shortcode });\n const url = `https://www.instagram.com/graphql/query/?doc_id=8845758582119845&variables=${encodeURIComponent(variables)}`;\n const res = await fetch(url, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \"X-IG-App-ID\": \"936619743392459\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n });\n if (!res.ok) return null;\n\n const data = (await res.json()) as Record<string, unknown>;\n return parseInstagramGraphQL(data);\n } catch {\n return null;\n }\n}\n\nexport function isTikTokUrl(url: string): boolean {\n return url.includes(\"tiktok.com\");\n}\n\nexport function isInstagramUrl(url: string): boolean {\n return url.includes(\"instagram.com\");\n}\n\n/** Extract Instagram shortcode from /reel/ or /p/ URLs */\nexport function extractInstagramShortcode(url: string): string | null {\n const match = /\\/(reel|p)\\/([A-Za-z0-9_-]+)/.exec(url);\n return match?.[2] ?? null;\n}\n\n/** Extract TikTok video ID from various URL formats */\nexport function extractTikTokVideoId(url: string): string | null {\n const match = /\\/video\\/(\\d+)/.exec(url);\n return match?.[1] ?? null;\n}\n\n/** Parse TikTok HTML for stats embedded as server-rendered JSON */\nexport function parseTikTokStats(\n html: string,\n): { duration?: number; viewCount?: number; likeCount?: number } | null {\n const getFirst = (key: string): number | undefined => {\n const match = new RegExp(`\"${key}\":(\\\\d+)`).exec(html);\n return match ? Number(match[1]) : undefined;\n };\n const duration = getFirst(\"duration\");\n if (duration == null) return null;\n return {\n duration,\n viewCount: getFirst(\"playCount\"),\n likeCount: getFirst(\"diggCount\"),\n };\n}\n\n/** Parse Instagram GraphQL response for video stats */\nexport function parseInstagramGraphQL(\n data: Record<string, unknown>,\n): { viewCount?: number; likeCount?: number } | null {\n const media = (data.data as Record<string, unknown> | undefined)\n ?.xdt_shortcode_media as Record<string, unknown> | undefined;\n if (!media) return null;\n const viewCount = (media.video_view_count as number | undefined) ?? undefined;\n const likeCount =\n ((media.edge_media_preview_like as Record<string, unknown> | undefined)\n ?.count as number | undefined) ?? undefined;\n if (viewCount == null && likeCount == null) return null;\n return { viewCount, likeCount };\n}\n\nexport async function probeCommand(\n urlOrId: string,\n options: ProbeOptions,\n): Promise<void> {\n let videoUrl: string;\n let researchItemId: string | null = null;\n\n const isUrl = urlOrId.startsWith(\"http://\") || urlOrId.startsWith(\"https://\");\n\n if (!isUrl) {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n const item = await getResearch(urlOrId);\n if (!item) {\n outputError(`Research item not found: ${urlOrId}`, options);\n return;\n }\n videoUrl = item.sourceUrl;\n researchItemId = item._id;\n } else {\n videoUrl = urlOrId;\n }\n\n let probe: VideoProbe | null = null;\n\n // Try yt-dlp first\n try {\n const result = await runShell(\n \"yt-dlp\",\n [\n \"--dump-json\",\n \"--no-download\",\n \"--no-playlist\",\n \"--no-warnings\",\n videoUrl,\n ],\n { timeout: 30_000 },\n );\n\n const data = JSON.parse(result.stdout) as Record<string, unknown>;\n probe = {\n duration: (data.duration as number | undefined) ?? 0,\n title: data.title as string | undefined,\n uploader: data.uploader as string | undefined,\n viewCount: data.view_count as number | undefined,\n likeCount: data.like_count as number | undefined,\n resolution: data.resolution as string | undefined,\n };\n } catch {\n // yt-dlp failed — try platform-specific fallback\n }\n\n // TikTok fallback: scrape page source\n if (!probe && isTikTokUrl(videoUrl)) {\n probe = await probeTikTok(videoUrl);\n }\n\n // Instagram: yt-dlp doesn't return view counts — fetch from public embed page\n if (probe && !probe.viewCount && isInstagramUrl(videoUrl)) {\n const igStats = await probeInstagramViews(videoUrl);\n if (igStats?.viewCount != null) probe.viewCount = igStats.viewCount;\n if (igStats?.likeCount != null) probe.likeCount = igStats.likeCount;\n }\n\n if (!probe) {\n outputError(\"Failed to probe video\", options);\n return;\n }\n\n // Store on research item if local\n if (researchItemId) {\n try {\n await patchResearch(researchItemId, {\n videoDuration: probe.duration,\n ...(probe.viewCount != null && { viewCount: probe.viewCount }),\n ...(probe.likeCount != null && { likeCount: probe.likeCount }),\n });\n } catch {\n // Best-effort\n }\n }\n\n if (options.json) {\n outputSuccess(probe, options);\n } else {\n console.log(chalk.bold(\"Video Info\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n if (probe.title) console.log(`Title: ${probe.title}`);\n if (probe.uploader) console.log(`Author: ${probe.uploader}`);\n console.log(`Duration: ${probe.duration.toFixed(1)}s`);\n if (probe.resolution) console.log(`Resolution: ${probe.resolution}`);\n if (probe.viewCount != null)\n console.log(`Views: ${probe.viewCount.toLocaleString()}`);\n if (probe.likeCount != null)\n console.log(`Likes: ${probe.likeCount.toLocaleString()}`);\n\n const frames = Math.ceil(probe.duration) + 1;\n const costPerCall = 0.007;\n const quickCost = (frames + 1) * costPerCall;\n const fullCost = (frames + 1) * costPerCall * 1.5;\n console.log();\n console.log(chalk.bold(\"Analysis Cost Estimate\"));\n console.log(chalk.dim(\"─\".repeat(40)));\n console.log(`Frames: ~${frames}`);\n console.log(`Quick: ${chalk.yellow(`$${quickCost.toFixed(3)}`)}`);\n console.log(`Full: ${chalk.yellow(`$${fullCost.toFixed(3)}`)}`);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { LocalResearchItem } from \"../../lib/local-convex.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n isLocalAvailable,\n listResearch,\n patchResearch,\n} from \"../../lib/local-convex.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface RankOptions extends OutputOptions {\n model?: string;\n platform?: string;\n limit?: number;\n store?: boolean;\n}\n\nconst OLLAMA_URL = \"http://127.0.0.1:11434\";\n\nconst RANK_PROMPT = `You are evaluating a short-form video transcript. Your job is to determine whether this content contains genuinely replicable techniques or is just engagement bait.\n\nScore 8-10: Names specific tools with specific settings. Gives numbered steps you could follow as-is. Explains WHY something works, not just what. Would change how you create content.\nScore 6-7: Useful angle or pattern confirmation. Adds to understanding but isn't revelatory.\nScore 4-5: Some value buried in filler. Maybe one extractable insight.\nScore 1-3: Engagement bait, vague advice (\"just be authentic\"), heavy self-promotion, or \"comment X to get Y\" with no substance delivered.\n\nBe harsh. Most content is a 2-4. Reserve 8+ for genuinely specific, actionable techniques.\n\nRespond with ONLY valid JSON, no markdown:\n{\"score\": <1-10>, \"reason\": \"<one sentence explaining the score>\", \"tags\": [\"<1-3 topic tags>\"]}`;\n\ninterface OllamaResponse {\n response: string;\n done: boolean;\n}\n\ninterface RankResult {\n score: number;\n reason: string;\n tags: string[];\n}\n\nasync function isOllamaRunning(): Promise<boolean> {\n try {\n const res = await fetch(`${OLLAMA_URL}/api/tags`, {\n signal: AbortSignal.timeout(2000),\n });\n return res.ok;\n } catch {\n return false;\n }\n}\n\nasync function ollamaGenerate(model: string, prompt: string): Promise<string> {\n const res = await fetch(`${OLLAMA_URL}/api/generate`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n prompt,\n stream: false,\n options: { temperature: 0.3, num_predict: 200 },\n }),\n });\n\n if (!res.ok) {\n throw new Error(`Ollama request failed: ${res.status} ${res.statusText}`);\n }\n\n const data = (await res.json()) as OllamaResponse;\n return data.response;\n}\n\nfunction extractTranscript(item: LocalResearchItem): string | null {\n const meta = item.metadata;\n const analysis = meta?.analysis as Record<string, unknown> | undefined;\n const transcript = analysis?.transcript as { text?: string } | undefined;\n return transcript?.text ?? null;\n}\n\nasync function rankItem(\n model: string,\n item: LocalResearchItem,\n transcriptText: string,\n): Promise<RankResult> {\n // Truncate long transcripts to keep within context window\n const maxChars = 2000;\n const truncated =\n transcriptText.length > maxChars\n ? transcriptText.slice(0, maxChars) + \"...\"\n : transcriptText;\n\n const prompt = `${RANK_PROMPT}\\n\\nVideo: \"${item.title ?? item.sourceUrl}\"\\nPlatform: ${item.platform}\\nAuthor: ${item.authorName ?? \"Unknown\"}\\n\\nTranscript:\\n${truncated}`;\n\n const raw = await ollamaGenerate(model, prompt);\n\n // Extract JSON from response\n const jsonMatch = /\\{[\\s\\S]*\\}/.exec(raw);\n if (!jsonMatch) {\n return { score: 5, reason: \"Could not parse LLM response\", tags: [] };\n }\n\n try {\n const parsed = JSON.parse(jsonMatch[0]) as Partial<RankResult>;\n return {\n score: Math.min(10, Math.max(1, parsed.score ?? 5)),\n reason: parsed.reason ?? \"\",\n tags: Array.isArray(parsed.tags) ? parsed.tags.slice(0, 3) : [],\n };\n } catch {\n return { score: 5, reason: \"Could not parse LLM response\", tags: [] };\n }\n}\n\nexport async function rankCommand(options: RankOptions): Promise<void> {\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\n \"Local Convex backend not running. Start the desktop app or run the backend manually.\",\n options,\n );\n return;\n }\n\n const ollamaUp = await isOllamaRunning();\n if (!ollamaUp) {\n outputError(\"Ollama is not running. Start it with: ollama serve\", options);\n return;\n }\n\n const model = options.model ?? \"llama3.2\";\n\n try {\n const items = await listResearch(options.platform, options.limit);\n\n // Filter to items with transcripts\n const withTranscripts = items\n .map((item) => ({\n item,\n transcript: extractTranscript(item),\n }))\n .filter(\n (x): x is { item: LocalResearchItem; transcript: string } =>\n x.transcript !== null && x.transcript.length > 0,\n );\n\n if (withTranscripts.length === 0) {\n if (options.json) {\n outputSuccess([], options);\n } else {\n console.log(\n chalk.dim(\n \"No items with transcripts found. Run 'program research analyze <id> --local --detail transcript' first.\",\n ),\n );\n }\n return;\n }\n\n if (!options.json) {\n console.log(\n chalk.bold(`Ranking ${withTranscripts.length} items with ${model}...`),\n );\n console.log();\n }\n\n // Score each item sequentially (avoid hammering the GPU)\n const results: {\n item: LocalResearchItem;\n rank: RankResult;\n }[] = [];\n\n for (let i = 0; i < withTranscripts.length; i++) {\n const entry = withTranscripts[i];\n if (!entry) continue;\n const { item, transcript } = entry;\n if (!options.json) {\n process.stdout.write(\n chalk.dim(\n ` [${i + 1}/${withTranscripts.length}] ${(item.title ?? item.sourceUrl).slice(0, 50)}...`,\n ),\n );\n }\n\n const rank = await rankItem(model, item, transcript);\n results.push({ item, rank });\n\n if (!options.json) {\n process.stdout.write(\n `\\r ${scoreColor(rank.score)} ${(item.title ?? item.sourceUrl).slice(0, 50)}\\n`,\n );\n }\n }\n\n // Sort by score descending\n results.sort((a, b) => b.rank.score - a.rank.score);\n\n // Store rankings back to Convex if requested\n if (options.store) {\n for (const { item, rank } of results) {\n const meta = item.metadata ?? {};\n const analysis = (meta.analysis ?? {}) as Record<string, unknown>;\n await patchResearch(item._id, {\n ...meta,\n analysis: {\n ...analysis,\n ranking: {\n score: rank.score,\n reason: rank.reason,\n tags: rank.tags,\n model,\n rankedAt: Date.now(),\n },\n },\n });\n }\n }\n\n // Output\n if (options.json) {\n outputSuccess(\n results.map(({ item, rank }) => ({\n id: item._id,\n title: item.title ?? item.sourceUrl,\n platform: item.platform,\n author: item.authorName,\n score: rank.score,\n reason: rank.reason,\n tags: rank.tags,\n })),\n options,\n );\n return;\n }\n\n console.log();\n console.log(chalk.bold(\"Rankings:\"));\n console.log();\n\n const rows = results.map(({ item, rank }, i) => {\n const title = item.title ?? item.sourceUrl;\n const displayTitle =\n title.length > 40 ? title.slice(0, 37) + \"...\" : title;\n\n return [\n chalk.dim(`${i + 1}.`),\n scoreColor(rank.score),\n displayTitle,\n rank.tags.map((t) => chalk.cyan(t)).join(\", \") || chalk.dim(\"-\"),\n chalk.dim(rank.reason.slice(0, 60)),\n ];\n });\n\n console.log(formatTable([\"#\", \"Score\", \"Title\", \"Tags\", \"Reason\"], rows));\n\n if (options.store) {\n console.log();\n console.log(chalk.green(\"Rankings stored to database.\"));\n }\n } catch (error: unknown) {\n const err = error as Error;\n outputError(err.message, options);\n }\n}\n\nfunction scoreColor(score: number): string {\n if (score >= 8) return chalk.green.bold(`${score}/10`);\n if (score >= 6) return chalk.yellow(`${score}/10`);\n return chalk.red(`${score}/10`);\n}\n","import { execFile } from \"node:child_process\";\nimport { access, mkdir, readdir, rename, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { resolveBinary } from \"../../lib/binary-manager.js\";\nimport { getResearch, isLocalAvailable } from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport { runShell } from \"../../lib/shell.js\";\nimport { getVideoDuration } from \"./pipeline.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport type SampleDensity = \"minimal\" | \"standard\" | \"dense\";\n\nexport interface SampleOptions extends OutputOptions {\n density?: string;\n}\n\nexport interface SampleResult {\n itemId: string;\n frameDir: string;\n framePaths: string[];\n frameTimes: number[];\n duration: number;\n density: SampleDensity;\n frameCount: number;\n}\n\nconst CACHE_DIR = \"/tmp/program-video-cache\";\nconst FRAME_SCALE = \"512:-1:flags=lanczos\";\n\nexport function cacheVideoPath(itemId: string): string {\n const safe = itemId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n return `${CACHE_DIR}/${safe}.mp4`;\n}\n\nfunction frameDirPath(itemId: string, density: SampleDensity): string {\n const safe = itemId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n return `${CACHE_DIR}/${safe}_frames_${density}`;\n}\n\n/**\n * Run ffmpeg and capture stderr without throwing on it.\n * ffmpeg writes all output (progress, showinfo) to stderr.\n */\nasync function runFfmpeg(\n args: string[],\n timeout = 120_000,\n): Promise<{ stdout: string; stderr: string }> {\n const binPath = await resolveBinary(\"ffmpeg\");\n try {\n return await execFileAsync(binPath, args, {\n timeout,\n maxBuffer: 50 * 1024 * 1024,\n });\n } catch (error: unknown) {\n const err = error as {\n code?: number;\n stderr?: string;\n stdout?: string;\n message?: string;\n };\n // ffmpeg often exits non-zero but still produces valid output\n // Only truly fail if there's no useful stderr to parse\n if (err.stderr) {\n return { stdout: err.stdout ?? \"\", stderr: err.stderr };\n }\n throw new Error(`ffmpeg failed: ${err.message}`);\n }\n}\n\nexport async function sampleCommand(\n id: string,\n options: SampleOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const density: SampleDensity =\n options.density === \"dense\"\n ? \"dense\"\n : options.density === \"minimal\"\n ? \"minimal\"\n : \"standard\";\n\n // 1. Resolve research item\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n const item = await getResearch(id);\n if (!item) {\n outputError(`Research item not found: ${id}`, options);\n return;\n }\n\n if (!options.json) {\n console.log(\n chalk.dim(\n `${item.title ?? item.authorName ?? item.sourceUrl} — ${density} sampling`,\n ),\n );\n }\n\n // 2. Check for existing frames\n const outDir = frameDirPath(id, density);\n const existingFrames = await collectFrames(outDir);\n if (existingFrames.length > 0) {\n const duration = await safeGetDuration(id);\n if (!options.json) {\n console.log(\n chalk.green(\"✓\") +\n ` ${existingFrames.length} frames already sampled → ${outDir}`,\n );\n }\n if (options.json) {\n outputSuccess(\n buildResult(id, outDir, existingFrames, duration, density),\n options,\n );\n }\n return;\n }\n\n // 3. Ensure we have the video\n const dlSpinner = showSpinner ? ora(\"Locating video...\").start() : null;\n const videoPath = await ensureVideo(id, item.sourceUrl);\n dlSpinner?.succeed(\"Video ready\");\n\n // 4. Get duration\n const duration = await getVideoDuration(videoPath);\n\n // 5. Extract frames\n await mkdir(outDir, { recursive: true });\n\n const extractSpinner = showSpinner\n ? ora(`Sampling frames (${density})...`).start()\n : null;\n\n let frameTimes: number[];\n\n switch (density) {\n case \"minimal\":\n frameTimes = await sampleMinimal(videoPath, outDir, duration);\n break;\n case \"standard\":\n frameTimes = await sampleStandard(videoPath, outDir);\n break;\n case \"dense\":\n frameTimes = await sampleDense(videoPath, outDir, duration);\n break;\n }\n\n const frames = await collectFrames(outDir);\n extractSpinner?.succeed(\n `Sampled ${frames.length} frames (${density}, ${duration.toFixed(1)}s video)`,\n );\n\n if (!options.json) {\n console.log(chalk.dim(`Frames → ${outDir}`));\n if (density === \"dense\" && frameTimes.length > 1) {\n const gaps = [];\n for (let i = 1; i < frameTimes.length; i++) {\n gaps.push((frameTimes[i] ?? 0) - (frameTimes[i - 1] ?? 0));\n }\n const avgGap = gaps.reduce((a, b) => a + b, 0) / gaps.length;\n const minGap = Math.min(...gaps);\n console.log(\n chalk.dim(\n `Scene changes: avg ${avgGap.toFixed(2)}s apart, fastest ${minGap.toFixed(2)}s`,\n ),\n );\n }\n }\n\n const result = buildResult(id, outDir, frames, duration, density);\n if (options.json) {\n outputSuccess(result, options);\n }\n}\n\n// ── Sampling strategies ──────────────────────────────────\n\n/**\n * Minimal: ~6-8 evenly spaced frames. For quick visual triage.\n */\nasync function sampleMinimal(\n videoPath: string,\n outDir: string,\n duration: number,\n): Promise<number[]> {\n const count = Math.min(8, Math.max(4, Math.ceil(duration / 5)));\n const interval = duration / count;\n\n await runFfmpeg(\n [\n \"-i\",\n videoPath,\n \"-vf\",\n `select='isnan(prev_selected_t)+gte(t-prev_selected_t\\\\,${interval.toFixed(2)})',scale=${FRAME_SCALE}`,\n \"-vsync\",\n \"vfr\",\n \"-q:v\",\n \"2\",\n \"-y\",\n join(outDir, \"frame_%04d.jpg\"),\n ],\n 60_000,\n );\n\n const times: number[] = [];\n for (let i = 0; i < count; i++) {\n times.push(i * interval);\n }\n return times;\n}\n\n/**\n * Standard: 1 FPS + hook frame at 0.5s. Reliable scene-by-scene coverage.\n */\nasync function sampleStandard(\n videoPath: string,\n outDir: string,\n): Promise<number[]> {\n // Hook frame\n await runFfmpeg(\n [\n \"-i\",\n videoPath,\n \"-vf\",\n `scale=${FRAME_SCALE}`,\n \"-ss\",\n \"0.5\",\n \"-frames:v\",\n \"1\",\n \"-q:v\",\n \"2\",\n \"-y\",\n join(outDir, \"frame_0000.jpg\"),\n ],\n 30_000,\n );\n\n // 1 FPS\n await runFfmpeg(\n [\n \"-i\",\n videoPath,\n \"-vf\",\n `fps=1,scale=${FRAME_SCALE}`,\n \"-q:v\",\n \"2\",\n \"-y\",\n join(outDir, \"frame_%04d.jpg\"),\n ],\n 120_000,\n );\n\n const frames = await collectFrames(outDir);\n return [0.5, ...frames.slice(1).map((_, i) => i + 1)];\n}\n\n/**\n * Dense: Scene change detection + 2 FPS baseline.\n * Captures every visual transition. Fast-paced content = lots of frames.\n * Talking head = very few. Adapts automatically.\n */\nasync function sampleDense(\n videoPath: string,\n outDir: string,\n _duration: number,\n): Promise<number[]> {\n // Pass 1: Scene detection — extract frames at every visual change\n // showinfo writes timestamps to stderr\n const sceneDir = join(outDir, \"_scene\");\n await mkdir(sceneDir, { recursive: true });\n\n const sceneResult = await runFfmpeg([\n \"-i\",\n videoPath,\n \"-vf\",\n `select='gt(scene\\\\,0.25)',showinfo,scale=${FRAME_SCALE}`,\n \"-vsync\",\n \"vfr\",\n \"-q:v\",\n \"2\",\n \"-y\",\n join(sceneDir, \"scene_%04d.jpg\"),\n ]);\n\n const sceneTimes = parseShowInfoTimes(sceneResult.stderr);\n\n // Pass 2: Regular 2 FPS to fill gaps\n const regularDir = join(outDir, \"_regular\");\n await mkdir(regularDir, { recursive: true });\n\n await runFfmpeg([\n \"-i\",\n videoPath,\n \"-vf\",\n `fps=2,scale=${FRAME_SCALE}`,\n \"-q:v\",\n \"2\",\n \"-y\",\n join(regularDir, \"regular_%04d.jpg\"),\n ]);\n\n // Merge: combine scene change frames + regular frames, deduplicate\n const sceneFrames = await collectFramePaths(sceneDir, \"scene_\");\n const regularFrames = await collectFramePaths(regularDir, \"regular_\");\n\n const allFrames: { time: number; path: string }[] = [];\n\n for (let i = 0; i < sceneFrames.length; i++) {\n allFrames.push({\n time: sceneTimes[i] ?? i * 0.5,\n path: sceneFrames[i] ?? \"\",\n });\n }\n for (let i = 0; i < regularFrames.length; i++) {\n allFrames.push({ time: i * 0.5, path: regularFrames[i] ?? \"\" });\n }\n\n // Sort by time and deduplicate — keep frames > 0.3s apart\n allFrames.sort((a, b) => a.time - b.time);\n const deduped: { time: number; path: string }[] = [];\n for (const f of allFrames) {\n if (\n deduped.length === 0 ||\n f.time - (deduped[deduped.length - 1]?.time ?? 0) > 0.3\n ) {\n deduped.push(f);\n }\n }\n\n // Move final frames to output dir with sequential names\n const times: number[] = [];\n for (let i = 0; i < deduped.length; i++) {\n const entry = deduped[i];\n if (!entry) continue;\n const destPath = join(outDir, `frame_${String(i).padStart(4, \"0\")}.jpg`);\n await rename(entry.path, destPath).catch(async () => {\n // Cross-device rename fallback: copy + delete\n const { copyFile, unlink } = await import(\"node:fs/promises\");\n await copyFile(entry.path, destPath);\n await unlink(entry.path).catch(() => {\n /* noop */\n });\n });\n times.push(entry.time);\n }\n\n // Clean up temp dirs\n await rm(sceneDir, { recursive: true, force: true }).catch(() => {\n /* noop */\n });\n await rm(regularDir, { recursive: true, force: true }).catch(() => {\n /* noop */\n });\n\n return times;\n}\n\n// ── Helpers ──────────────────────────────────────────────\n\nfunction parseShowInfoTimes(stderr: string): number[] {\n const times: number[] = [];\n const regex = /pts_time:\\s*([\\d.]+)/g;\n let match;\n while ((match = regex.exec(stderr)) !== null) {\n times.push(parseFloat(match[1] ?? \"0\"));\n }\n return times;\n}\n\nasync function collectFrames(dir: string): Promise<string[]> {\n try {\n const files = await readdir(dir);\n return files\n .filter((f) => f.startsWith(\"frame_\") && f.endsWith(\".jpg\"))\n .sort()\n .map((f) => join(dir, f));\n } catch {\n return [];\n }\n}\n\nasync function collectFramePaths(\n dir: string,\n prefix: string,\n): Promise<string[]> {\n try {\n const files = await readdir(dir);\n return files\n .filter((f) => f.startsWith(prefix) && f.endsWith(\".jpg\"))\n .sort()\n .map((f) => join(dir, f));\n } catch {\n return [];\n }\n}\n\nexport async function ensureVideo(itemId: string, sourceUrl: string): Promise<string> {\n const cached = cacheVideoPath(itemId);\n const hasCached = await access(cached)\n .then(() => true)\n .catch(() => false);\n\n if (hasCached) return cached;\n\n // Download to cache using yt-dlp directly\n await mkdir(CACHE_DIR, { recursive: true });\n await runShell(\n \"yt-dlp\",\n [\n \"-f\",\n \"mp4/bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best\",\n \"--merge-output-format\",\n \"mp4\",\n \"-o\",\n cached,\n \"--no-playlist\",\n \"--no-warnings\",\n sourceUrl,\n ],\n { timeout: 120_000 },\n );\n\n return cached;\n}\n\nasync function safeGetDuration(itemId: string): Promise<number> {\n try {\n const videoPath = cacheVideoPath(itemId);\n await access(videoPath);\n return await getVideoDuration(videoPath);\n } catch {\n return 0;\n }\n}\n\nfunction buildResult(\n itemId: string,\n outDir: string,\n framePaths: string[],\n duration: number,\n density: SampleDensity,\n): SampleResult {\n const frameTimes =\n density === \"standard\"\n ? framePaths.map((_, i) => (i === 0 ? 0.5 : i))\n : framePaths.map(\n (_, i) => (i * duration) / Math.max(framePaths.length, 1),\n );\n\n return {\n itemId,\n frameDir: outDir,\n framePaths,\n frameTimes,\n duration,\n density,\n frameCount: framePaths.length,\n };\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { SetupProgress } from \"../../lib/binary-manager.js\";\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { checkSetup, setupAll } from \"../../lib/binary-manager.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport type SetupOptions = OutputOptions;\n\nexport async function setupCommand(options: SetupOptions): Promise<void> {\n if (options.json) {\n // Non-interactive: just check status\n const status = await checkSetup();\n outputSuccess(status, options);\n return;\n }\n\n console.log(chalk.bold(\"Program Video Analysis — Tool Setup\"));\n console.log(chalk.dim(\"Downloads required tools to ~/.program/bin/\\n\"));\n\n const spinners = new Map<string, ReturnType<typeof ora>>();\n\n const progress: SetupProgress = {\n onStart: (name) => {\n const spinner = ora(`Downloading ${name}...`).start();\n spinners.set(name, spinner);\n },\n onProgress: (name, downloaded, total) => {\n const spinner = spinners.get(name);\n if (spinner && total > 0) {\n const pct = Math.round((downloaded / total) * 100);\n const mb = (downloaded / 1024 / 1024).toFixed(1);\n spinner.text = `Downloading ${name}... ${pct}% (${mb} MB)`;\n }\n },\n onDone: (name) => {\n const spinner = spinners.get(name);\n spinner?.succeed(`${name} ${chalk.green(\"ready\")}`);\n spinners.delete(name);\n },\n onSkip: (name) => {\n console.log(\n ` ${chalk.dim(\"○\")} ${name} ${chalk.dim(\"already installed\")}`,\n );\n },\n onError: (name, error) => {\n const spinner = spinners.get(name);\n if (spinner) {\n spinner.fail(`${name}: ${chalk.red(error)}`);\n } else {\n console.log(` ${chalk.red(\"✗\")} ${name}: ${error}`);\n }\n spinners.delete(name);\n },\n };\n\n try {\n await setupAll(progress);\n } catch (error: unknown) {\n const err = error as Error;\n outputError(err.message, options);\n return;\n }\n\n // Final check\n console.log();\n const status = await checkSetup();\n if (status.ready) {\n console.log(\n chalk.green(\"✓\") +\n \" All tools ready. Run \" +\n chalk.cyan(\"program research analyze <url>\") +\n \" to get started.\",\n );\n } else {\n console.log(\n chalk.yellow(\"⚠\") +\n ` Some tools could not be set up: ${status.missing.join(\", \")}`,\n );\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport type { VideoAnalysis } from \"./types.js\";\nimport { setActiveTemplate } from \"../../lib/context.js\";\nimport {\n createTemplate,\n getResearch,\n isLocalAvailable,\n} from \"../../lib/local-convex.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface ToTemplateOptions extends OutputOptions {\n name?: string;\n}\n\nexport async function toTemplateCommand(\n id: string,\n options: ToTemplateOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n return;\n }\n\n const item = await getResearch(id);\n if (!item) {\n outputError(`Research item not found: ${id}`, options);\n return;\n }\n\n // 2. Validate analysis exists\n const metadata = item.metadata;\n const analysis = metadata?.analysis as VideoAnalysis | undefined;\n\n if (!analysis?.templateSuggestion) {\n outputError(\n \"This research item hasn't been analyzed yet. Run 'program research analyze' first.\",\n options,\n );\n return;\n }\n\n // 3. Create template locally\n const templateName =\n options.name ??\n `${item.platform} - ${analysis.style.format} (${new Date().toLocaleDateString()})`;\n\n const description = `Auto-generated from ${item.platform} video analysis. Format: ${analysis.style.format}, Pacing: ${analysis.style.pacing}. Source: ${item.sourceUrl}`;\n\n const steps = analysis.templateSuggestion.steps.map((step, i) => ({\n stepId: step.stepId,\n config: step.config,\n order: i,\n }));\n\n const spinner = showSpinner ? ora(\"Creating template...\").start() : null;\n\n try {\n const templateId = await createTemplate(templateName, steps, description, {\n sourceResearchId: id,\n sourceUrl: item.sourceUrl,\n });\n\n spinner?.succeed(\"Template created\");\n\n // Set as active template\n setActiveTemplate(templateId);\n\n if (options.json) {\n outputSuccess(\n {\n templateId,\n name: templateName,\n steps: steps.length,\n },\n options,\n );\n } else {\n console.log();\n console.log(formatSuccess(`Template: ${templateName}`));\n console.log(chalk.dim(` ID: ${templateId}`));\n console.log(chalk.dim(` Steps: ${steps.length}`));\n console.log(chalk.dim(` Set as active template`));\n console.log();\n console.log(\n `Run ${chalk.cyan(\"program template get\")} to view, or ${chalk.cyan(\"program template run --local\")} to execute.`,\n );\n }\n } catch (error: unknown) {\n spinner?.fail(\"Failed to create template\");\n const err = error as Error;\n outputError(err.message, options);\n }\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport Conf from \"conf\";\n\ninterface ContextData {\n activeTemplateId: string | null;\n}\n\nconst CONTEXT_DIR = path.join(os.homedir(), \".program\");\n\nfunction ensureContextDir(): void {\n if (!fs.existsSync(CONTEXT_DIR)) {\n fs.mkdirSync(CONTEXT_DIR, { mode: 0o700, recursive: true });\n }\n}\n\nconst store = new Conf<ContextData>({\n projectName: \"program-cli\",\n cwd: CONTEXT_DIR,\n configName: \"context\",\n fileExtension: \"json\",\n defaults: {\n activeTemplateId: null,\n },\n});\n\nexport function setActiveTemplate(id: string): void {\n ensureContextDir();\n store.set(\"activeTemplateId\", id);\n}\n\nexport function getActiveTemplate(): string | null {\n return store.get(\"activeTemplateId\");\n}\n\nexport function clearActiveTemplate(): void {\n store.set(\"activeTemplateId\", null);\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { setActiveTemplate } from \"../../lib/context.js\";\nimport {\n createTemplate as localCreateTemplate,\n isLocalAvailable,\n} from \"../../lib/local-convex.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface CreateOptions extends OutputOptions {\n name: string;\n description?: string;\n}\n\nexport async function createCommand(options: CreateOptions): Promise<void> {\n if (!options.name) {\n outputError(\"--name is required\", options);\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Creating template...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n const templateId = await localCreateTemplate(\n options.name,\n [],\n options.description,\n );\n\n spinner?.stop();\n spinner?.clear();\n\n // Auto-set as active template\n setActiveTemplate(templateId);\n\n if (options.json) {\n outputSuccess({ id: templateId, active: true }, options);\n } else {\n console.log(formatSuccess(\"Template created (now active)\"));\n console.log(chalk.dim(` ID: ${templateId}`));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\nimport {\n getTemplate as localGetTemplate,\n isLocalAvailable,\n} from \"../../lib/local-convex.js\";\nimport {\n formatKeyValue,\n formatTable,\n outputError,\n outputSuccess,\n} from \"../../lib/output.js\";\n\nexport type GetOptions = OutputOptions;\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\ninterface Template {\n _id: string;\n name: string;\n description?: string;\n public: boolean;\n steps?: Step[];\n metadata?: Record<string, unknown>;\n createdAt: number;\n updatedAt: number;\n}\n\nexport async function getCommand(\n id: string | undefined,\n options: GetOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching template...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n const result = await localGetTemplate(templateId);\n spinner?.stop();\n spinner?.clear();\n if (!result) {\n outputError(\"Template not found\", options);\n process.exit(1);\n }\n const template = result as unknown as Template;\n\n if (options.json) {\n outputSuccess(template, options);\n } else {\n console.log(\n formatKeyValue([\n { key: \"ID\", value: template._id },\n { key: \"Name\", value: template.name },\n {\n key: \"Description\",\n value: template.description ?? chalk.dim(\"None\"),\n },\n {\n key: \"Visibility\",\n value: template.public ? chalk.green(\"public\") : chalk.dim(\"private\"),\n },\n {\n key: \"Created\",\n value: new Date(template.createdAt).toLocaleString(),\n },\n {\n key: \"Updated\",\n value: new Date(template.updatedAt).toLocaleString(),\n },\n ]),\n );\n\n const steps = template.steps ?? [];\n if (steps.length === 0) {\n console.log(chalk.dim(\"\\nNo steps configured.\"));\n } else {\n console.log(`\\n${chalk.bold(\"Steps\")} (${steps.length}):\\n`);\n\n const rows = steps.map((s, i) => [\n String(i),\n s.id ?? chalk.dim(\"--\"),\n s.stepId,\n summarizeConfig(s.config),\n ]);\n\n console.log(formatTable([\"#\", \"ID\", \"Type\", \"Config\"], rows));\n }\n }\n}\n\nfunction summarizeConfig(config: Record<string, unknown>): string {\n const keys = Object.keys(config);\n if (keys.length === 0) return chalk.dim(\"{}\");\n const summary = keys\n .slice(0, 3)\n .map((k) => {\n const v = config[k];\n const vs =\n typeof v === \"string\"\n ? v.length > 20\n ? v.substring(0, 20) + \"...\"\n : v\n : JSON.stringify(v);\n return `${k}=${vs}`;\n })\n .join(\", \");\n return keys.length > 3 ? summary + `, +${keys.length - 3} more` : summary;\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n isLocalAvailable,\n listTemplates,\n} from \"../../lib/local-convex.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface ListOptions extends OutputOptions {\n limit?: number;\n publicOnly?: boolean;\n}\n\nexport async function listCommand(options: ListOptions): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Fetching templates...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n const templates = await listTemplates(options.limit);\n\n spinner?.stop();\n spinner?.clear();\n\n if (options.json) {\n outputSuccess(\n templates.map((t) => ({\n id: t._id,\n name: t.name,\n description: t.description,\n stepCount: Array.isArray(t.steps) ? t.steps.length : 0,\n })),\n options,\n );\n } else {\n if (templates.length === 0) {\n console.log(chalk.dim(\"No templates found.\"));\n return;\n }\n\n console.log(\n `Found ${chalk.cyan(templates.length)} template${templates.length === 1 ? \"\" : \"s\"}:\\n`,\n );\n\n const rows = templates.map((t) => [\n t._id,\n t.name,\n (t.description ?? \"\").substring(0, 40) || chalk.dim(\"No description\"),\n String(Array.isArray(t.steps) ? t.steps.length : 0),\n ]);\n\n console.log(\n formatTable([\"ID\", \"Name\", \"Description\", \"Steps\"], rows),\n );\n }\n}\n","import type { OutputOptions } from \"../../../lib/output.js\";\nimport { outputError } from \"../../../lib/output.js\";\n\nexport type ModelListOptions = OutputOptions;\n\nexport function modelListCommand(\n _category: string,\n options: ModelListOptions,\n): void {\n outputError(\n \"Model listing is not yet available for the local backend. Check the desktop app for available models.\",\n options,\n );\n process.exit(1);\n}\n","import type { OutputOptions } from \"../../../lib/output.js\";\nimport { outputError } from \"../../../lib/output.js\";\n\nexport type ModelSchemaOptions = OutputOptions;\n\nexport function modelSchemaCommand(\n _modelId: string,\n options: ModelSchemaOptions,\n): void {\n outputError(\n \"Model schema is not yet available for the local backend. Check the desktop app for model details.\",\n options,\n );\n process.exit(1);\n}\n","import type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\nimport { outputError } from \"../../lib/output.js\";\n\nexport interface RemoveOptions extends OutputOptions {\n force?: boolean;\n}\n\nexport function removeCommand(\n id: string | undefined,\n options: RemoveOptions,\n): void {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n // TODO: Add deleteTemplate to local-convex.ts and Convex backend\n outputError(\n \"Template deletion is not yet supported for the local backend. Delete templates from the desktop app.\",\n options,\n );\n process.exit(1);\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\nimport {\n addScene,\n createComposition,\n createExecution,\n createExecutionLog,\n deleteAllScenes,\n deleteScene,\n getComposition,\n getIntegrationApiKey,\n getTemplate,\n isLocalAvailable,\n updateComposition,\n updateExecution,\n updateExecutionLog,\n updateScene,\n} from \"../../lib/local-convex.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface RunOptions extends OutputOptions {\n input?: string;\n executionId?: string;\n}\n\ninterface StepDef {\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: StepDef[];\n}\n\ninterface StepReference {\n type: \"reference\";\n stepIndex: number;\n outputKey: string;\n}\n\nfunction isStepReference(value: unknown): value is StepReference {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"type\" in value &&\n (value as { type: unknown }).type === \"reference\" &&\n \"stepIndex\" in value &&\n \"outputKey\" in value\n );\n}\n\n/**\n * Resolve a single input value, handling references and template inputs.\n */\nfunction resolveInputValue(\n value: unknown,\n stepOutputs: Map<number, Record<string, unknown>>,\n templateInputs: Record<string, unknown>,\n): unknown {\n if (isStepReference(value)) {\n const output = stepOutputs.get(value.stepIndex);\n if (!output) {\n throw new Error(`Reference to step ${value.stepIndex} not found`);\n }\n const keys = value.outputKey.split(\".\");\n let result: unknown = output;\n for (const key of keys) {\n if (typeof result === \"object\" && result !== null && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n throw new Error(\n `Output key '${value.outputKey}' not found in step ${value.stepIndex}`,\n );\n }\n }\n return result;\n }\n\n if (\n typeof value === \"string\" &&\n value.startsWith(\"${\") &&\n value.endsWith(\"}\")\n ) {\n const key = value.slice(2, -1);\n return templateInputs[key];\n }\n\n if (typeof value === \"string\") {\n // Interpolate {step1.field} references\n return value.replace(\n /\\{step(\\d+)\\.([^}]+)\\}/g,\n (match, stepNum: string, outputKey: string) => {\n const stepIndex = Number.parseInt(stepNum, 10) - 1;\n const output = stepOutputs.get(stepIndex);\n if (!output) return match;\n const keys = outputKey.split(\".\");\n let result: unknown = output;\n for (const key of keys) {\n if (typeof result === \"object\" && result !== null && key in result) {\n result = (result as Record<string, unknown>)[key];\n } else {\n return match;\n }\n }\n return typeof result === \"string\" ? result : JSON.stringify(result);\n },\n );\n }\n\n if (Array.isArray(value)) {\n return value.map((item) =>\n resolveInputValue(item, stepOutputs, templateInputs),\n );\n }\n\n if (typeof value === \"object\" && value !== null) {\n const resolved: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n resolved[k] = resolveInputValue(v, stepOutputs, templateInputs);\n }\n return resolved;\n }\n\n return value;\n}\n\n/**\n * Resolve all inputs for a step.\n */\nfunction resolveStepInputs(\n step: StepDef,\n stepOutputs: Map<number, Record<string, unknown>>,\n templateInputs: Record<string, unknown>,\n): Record<string, unknown> {\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(step.config)) {\n resolved[key] = resolveInputValue(value, stepOutputs, templateInputs);\n }\n return resolved;\n}\n\n/**\n * Execute a single step locally using Replicate inference + AI Gateway.\n */\nasync function executeStepLocally(\n stepId: string,\n inputs: Record<string, unknown>,\n tokens: { replicate: string | null; aiGateway: string | null },\n): Promise<Record<string, unknown>> {\n switch (stepId) {\n case \"generateScript\": {\n const prompt = (inputs.prompt ?? inputs.text) as string | undefined;\n if (!prompt) throw new Error(\"generateScript requires a prompt\");\n\n const aiGatewayKey = tokens.aiGateway;\n if (!aiGatewayKey) {\n throw new Error(\n \"No AI Gateway API key found. Add one in Settings > Integrations.\",\n );\n }\n\n const { createGateway, generateText } = await import(\"ai\");\n\n const modelToUse =\n (inputs.model as string | undefined) ?? \"google/gemini-2.5-flash\";\n const modelString = modelToUse.includes(\"/\")\n ? modelToUse\n : `openai/${modelToUse}`;\n\n const gateway = createGateway({ apiKey: aiGatewayKey });\n\n const { text, usage } = await generateText({\n model: gateway(modelString),\n prompt: `Write exactly what the user requested. Do not add scene directions, formatting, or extra content. Just write the text as requested.\\n\\nUser request: ${prompt}\\n\\nWrite the text:`,\n temperature: 0.3,\n });\n\n return {\n script: text,\n model: modelString,\n usage: {\n inputTokens: (usage as Record<string, unknown>).promptTokens as\n | number\n | undefined,\n outputTokens: (usage as Record<string, unknown>).completionTokens as\n | number\n | undefined,\n totalTokens: (usage as Record<string, unknown> | undefined)\n ?.totalTokens as number | undefined,\n },\n message: `Script generated with ${modelString}`,\n };\n }\n\n case \"generateImage\": {\n const model =\n (inputs.model as string | undefined) ??\n \"stability-ai/sdxl:39ed52f2a78e934b3ba6e2a89f5b1c712de7dfea535525255b1aa35c5565e08b\";\n const prompt = inputs.prompt as string;\n if (!prompt) throw new Error(\"generateImage requires a prompt\");\n if (!tokens.replicate)\n throw new Error(\n \"No Replicate API key found. Add one in Settings > Integrations.\",\n );\n\n const { default: Replicate } = await import(\"replicate\");\n const replicate = new Replicate({ auth: tokens.replicate });\n\n const output = (await replicate.run(model as `${string}/${string}`, {\n input: {\n prompt,\n ...((inputs.modelInputs as Record<string, unknown> | undefined) ??\n {}),\n },\n })) as unknown;\n\n const imageUrl = extractFileUrl(output);\n\n return {\n imageUrl: imageUrl ?? \"unknown\",\n prompt,\n success: true,\n message: `Image generated with ${model}`,\n };\n }\n\n case \"generateVideo\": {\n const model = (inputs.model as string | undefined) ?? \"minimax/video-01\";\n const prompt = inputs.prompt as string;\n if (!prompt) throw new Error(\"generateVideo requires a prompt\");\n if (!tokens.replicate)\n throw new Error(\n \"No Replicate API key found. Add one in Settings > Integrations.\",\n );\n\n const { default: Replicate } = await import(\"replicate\");\n const replicate = new Replicate({ auth: tokens.replicate });\n\n const output = (await replicate.run(model as `${string}/${string}`, {\n input: {\n prompt,\n ...((inputs.modelInputs as Record<string, unknown> | undefined) ??\n {}),\n },\n })) as unknown;\n\n const videoUrl = extractFileUrl(output);\n\n return {\n videoUrl: videoUrl ?? \"unknown\",\n success: true,\n message: `Video generated with ${model}`,\n };\n }\n\n case \"generateSpeech\": {\n const text = inputs.text as string;\n if (!text) throw new Error(\"generateSpeech requires text\");\n const model =\n (inputs.model as string | undefined) ?? \"resemble-ai/chatterbox-turbo\";\n if (!tokens.replicate)\n throw new Error(\n \"No Replicate API key found. Add one in Settings > Integrations.\",\n );\n\n const { default: Replicate } = await import(\"replicate\");\n const replicate = new Replicate({ auth: tokens.replicate });\n\n const output = (await replicate.run(model as `${string}/${string}`, {\n input: {\n text,\n ...((inputs.modelInputs as Record<string, unknown> | undefined) ??\n {}),\n },\n })) as unknown;\n\n const audioUrl = extractFileUrl(output);\n\n return {\n audioUrl: audioUrl ?? \"unknown\",\n success: true,\n message: `Speech generated with ${model}`,\n };\n }\n\n case \"setMetadata\": {\n return {\n success: true,\n title: inputs.title,\n description: inputs.description,\n message: \"Metadata set\",\n };\n }\n\n case \"forEach\": {\n // forEach is handled at the orchestration level\n return { result: [] };\n }\n\n case \"if\": {\n return { result: {} };\n }\n\n // ── Composition Steps ─────────────────────────────────────────────\n\n case \"createComposition\": {\n const title = (inputs.title as string | undefined) ?? \"Untitled Composition\";\n const compositionId = await createComposition(title, {\n width: (inputs.width as number | undefined) ?? 1920,\n height: (inputs.height as number | undefined) ?? 1080,\n fps: (inputs.fps as number | undefined) ?? 30,\n description: inputs.description as string | undefined,\n });\n return { compositionId, success: true, message: `Composition created: ${title}` };\n }\n\n case \"planScene\":\n case \"addScene\": {\n const compositionId = inputs.compositionId as string;\n if (!compositionId) throw new Error(`${stepId} requires compositionId`);\n\n const sceneId = (inputs.sceneId as string | undefined) ?? `scene-${Date.now().toString(36)}`;\n const sceneType = (inputs.type as string | undefined) ?? \"code_scene\";\n const start = (inputs.start as number | undefined) ?? 0;\n const sceneDuration = (inputs.duration as number | undefined) ?? 5;\n const end = (inputs.end as number | undefined) ?? start + sceneDuration;\n const order = (inputs.order as number | undefined) ?? 0;\n\n const scene: Record<string, unknown> = {\n id: sceneId,\n type: sceneType,\n start,\n end,\n duration: sceneDuration,\n order,\n };\n\n if (sceneType === \"code_scene\") {\n scene.componentId = (inputs.componentId as string | undefined) ?? \"\";\n scene.props = (inputs.props as Record<string, unknown> | undefined) ?? {};\n const code = inputs.code as string | undefined;\n scene.metadata = {\n ...(inputs.metadata as Record<string, unknown> | undefined),\n ...(code ? { code, files: { \"index.tsx\": code }, entryPoint: \"index.tsx\" } : {}),\n };\n } else {\n scene.config = (inputs.config as Record<string, unknown> | undefined) ?? {};\n }\n\n await addScene(compositionId, scene);\n return { compositionId, sceneId, success: true, message: `Scene added: ${sceneId}` };\n }\n\n case \"generateSceneContent\": {\n const compositionId = inputs.compositionId as string;\n const sceneId = inputs.sceneId as string;\n if (!compositionId || !sceneId) {\n throw new Error(\"generateSceneContent requires compositionId and sceneId\");\n }\n\n const aiGatewayKey = tokens.aiGateway;\n if (!aiGatewayKey) {\n throw new Error(\"No AI Gateway API key found. Add one in Settings > Integrations.\");\n }\n\n const { createGateway, generateText } = await import(\"ai\");\n\n const modelToUse = (inputs.model as string | undefined) ?? \"google/gemini-2.5-flash\";\n const modelString = modelToUse.includes(\"/\") ? modelToUse : `openai/${modelToUse}`;\n const gateway = createGateway({ apiKey: aiGatewayKey });\n\n const title = (inputs.title as string | undefined) ?? \"Scene\";\n const description = (inputs.description as string | undefined) ?? \"\";\n const visualStyle = (inputs.visualStyle as string | undefined) ?? \"modern, clean\";\n const animationType = (inputs.animationType as string | undefined) ?? \"fade\";\n const sceneDuration = (inputs.duration as number | undefined) ?? 5;\n\n const prompt = `You are a Remotion video scene developer. Generate a complete React component for a video scene.\n\nScene Title: ${title}\nDescription: ${description}\nVisual Style: ${visualStyle}\nAnimation Type: ${animationType}\nDuration: ${sceneDuration} seconds\n\nRequirements:\n- Use export default for the main component\n- Import from \"remotion\": AbsoluteFill, useCurrentFrame, useVideoConfig, interpolate, spring\n- Use inline styles or Tailwind classes\n- Create smooth animations using useCurrentFrame and interpolate/spring\n- The component will render at 1920x1080\n- Make it visually engaging and professional\n\nGenerate ONLY the code, no explanations:`;\n\n const { text: code } = await generateText({\n model: gateway(modelString),\n prompt,\n temperature: 0.3,\n });\n\n // Strip markdown fences if present\n const cleanCode = code\n .replace(/^```(?:tsx?|jsx?|javascript|typescript)?\\n?/m, \"\")\n .replace(/\\n?```$/m, \"\")\n .trim();\n\n // Update the scene with generated code\n const composition = await getComposition(compositionId);\n if (!composition) throw new Error(`Composition not found: ${compositionId}`);\n\n const scenes = (composition.scenes ?? []) as { id: string; metadata?: Record<string, unknown> }[];\n const updatedScenes = scenes.map((s) =>\n s.id === sceneId\n ? {\n ...s,\n metadata: {\n ...(s.metadata ?? {}),\n code: cleanCode,\n files: { \"index.tsx\": cleanCode },\n entryPoint: \"index.tsx\",\n title,\n description,\n visualStyle,\n animationType,\n status: \"final\",\n },\n }\n : s,\n );\n\n await updateComposition(compositionId, { scenes: updatedScenes as unknown[] });\n\n return {\n compositionId,\n sceneId,\n success: true,\n model: modelString,\n message: `Scene content generated for ${sceneId}`,\n };\n }\n\n case \"updateScene\": {\n const compositionId = inputs.compositionId as string;\n const sceneId = inputs.sceneId as string;\n if (!compositionId || !sceneId) {\n throw new Error(\"updateScene requires compositionId and sceneId\");\n }\n\n const updates: Record<string, unknown> = {};\n if (inputs.start !== undefined) updates.start = inputs.start;\n if (inputs.end !== undefined) updates.end = inputs.end;\n if (inputs.duration !== undefined) updates.duration = inputs.duration;\n if (inputs.order !== undefined) updates.order = inputs.order;\n\n await updateScene(compositionId, sceneId, updates);\n return { compositionId, sceneId, success: true, message: `Scene updated: ${sceneId}` };\n }\n\n case \"updateSceneTiming\": {\n const compositionId = inputs.compositionId as string;\n const sceneId = inputs.sceneId as string;\n if (!compositionId || !sceneId) {\n throw new Error(\"updateSceneTiming requires compositionId and sceneId\");\n }\n\n const updates: Record<string, unknown> = {};\n if (inputs.start !== undefined) updates.start = inputs.start;\n if (inputs.end !== undefined) updates.end = inputs.end;\n if (inputs.duration !== undefined) updates.duration = inputs.duration;\n\n await updateScene(compositionId, sceneId, updates);\n return { compositionId, sceneId, success: true, message: `Scene timing updated: ${sceneId}` };\n }\n\n case \"deleteScene\": {\n const compositionId = inputs.compositionId as string;\n const sceneId = inputs.sceneId as string;\n if (!compositionId || !sceneId) {\n throw new Error(\"deleteScene requires compositionId and sceneId\");\n }\n await deleteScene(compositionId, sceneId);\n return { compositionId, sceneId, success: true, message: `Scene deleted: ${sceneId}` };\n }\n\n case \"deleteAllScenes\": {\n const compositionId = inputs.compositionId as string;\n if (!compositionId) throw new Error(\"deleteAllScenes requires compositionId\");\n await deleteAllScenes(compositionId);\n return { compositionId, success: true, message: \"All scenes deleted\" };\n }\n\n case \"readComposition\": {\n const compositionId = inputs.compositionId as string;\n if (!compositionId) throw new Error(\"readComposition requires compositionId\");\n const composition = await getComposition(compositionId);\n if (!composition) throw new Error(`Composition not found: ${compositionId}`);\n return {\n compositionId,\n title: composition.title,\n description: composition.description,\n duration: composition.duration,\n fps: composition.fps,\n width: composition.width,\n height: composition.height,\n sceneCount: (composition.scenes ?? []).length,\n scenes: composition.scenes,\n success: true,\n };\n }\n\n case \"segmentScript\": {\n const script = inputs.script as string;\n if (!script) throw new Error(\"segmentScript requires script text\");\n const sceneDuration = (inputs.sceneDuration as number | undefined) ?? 5;\n\n // Simple split: divide script into segments by sentences, targeting sceneDuration\n const sentences = script.match(/[^.!?]+[.!?]+/g) ?? [script];\n const wordsPerSecond = 2.5;\n const segments: { text: string; start: number; end: number; duration: number }[] = [];\n let currentTime = 0;\n\n let currentSegment = \"\";\n for (const sentence of sentences) {\n const trimmed = sentence.trim();\n if (!trimmed) continue;\n\n currentSegment += (currentSegment ? \" \" : \"\") + trimmed;\n const wordCount = currentSegment.split(/\\s+/).length;\n const estimatedDuration = wordCount / wordsPerSecond;\n\n if (estimatedDuration >= sceneDuration) {\n const segDuration = Math.max(sceneDuration, estimatedDuration);\n segments.push({\n text: currentSegment,\n start: currentTime,\n end: currentTime + segDuration,\n duration: segDuration,\n });\n currentTime += segDuration;\n currentSegment = \"\";\n }\n }\n\n // Flush remaining\n if (currentSegment.trim()) {\n const wordCount = currentSegment.split(/\\s+/).length;\n const segDuration = Math.max(sceneDuration, wordCount / wordsPerSecond);\n segments.push({\n text: currentSegment.trim(),\n start: currentTime,\n end: currentTime + segDuration,\n duration: segDuration,\n });\n }\n\n return { segments, count: segments.length, success: true };\n }\n\n case \"assessComposition\": {\n const compositionId = inputs.compositionId as string;\n if (!compositionId) throw new Error(\"assessComposition requires compositionId\");\n const composition = await getComposition(compositionId);\n if (!composition) throw new Error(`Composition not found: ${compositionId}`);\n\n const scenes = (composition.scenes ?? []) as {\n id: string;\n type: string;\n start: number;\n end: number;\n duration: number;\n }[];\n\n const totalDuration = scenes.length > 0\n ? Math.max(...scenes.map((s) => s.end))\n : 0;\n\n return {\n compositionId,\n sceneCount: scenes.length,\n totalDuration,\n hasCodeScenes: scenes.some((s) => s.type === \"code_scene\"),\n hasAudioScenes: scenes.some((s) => s.type === \"audio_scene\"),\n hasVideoScenes: scenes.some((s) => s.type === \"video_scene\"),\n hasImageScenes: scenes.some((s) => s.type === \"image_scene\"),\n scenes: scenes.map((s) => ({\n id: s.id,\n type: s.type,\n start: s.start,\n end: s.end,\n duration: s.duration,\n })),\n success: true,\n };\n }\n\n default: {\n return {\n success: true,\n message: `Step '${stepId}' executed (passthrough)`,\n ...inputs,\n };\n }\n }\n}\n\n/**\n * Extract a URL from Replicate output.\n * Replicate SDK v1.x returns FileOutput objects (ReadableStream with .url() and .toString())\n * instead of plain strings. This handles all known output shapes:\n * - string URL\n * - FileOutput (has .url() method and .toString())\n * - Array of strings or FileOutput objects\n * - Object with .url property\n */\nfunction extractFileUrl(output: unknown): string | undefined {\n if (!output) return undefined;\n\n // Direct string\n if (typeof output === \"string\") return output;\n\n // FileOutput or object with .toString() that returns a URL\n if (typeof output === \"object\") {\n // Check for .url() method (FileOutput)\n if (\n \"url\" in output &&\n typeof (output as { url: unknown }).url === \"function\"\n ) {\n const url = (output as { url: () => URL }).url();\n return url.toString();\n }\n\n // Array — take first element\n if (Array.isArray(output) && output.length > 0) {\n return extractFileUrl(output[0]);\n }\n\n // Object with .url string property\n if (\n \"url\" in output &&\n typeof (output as { url: unknown }).url === \"string\"\n ) {\n return (output as { url: string }).url;\n }\n\n // FileOutput's toString returns the URL string\n const str = (output as { toString(): string }).toString();\n if (str.startsWith(\"http\")) return str;\n }\n\n return undefined;\n}\n\nfunction formatMs(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n const seconds = ms / 1000;\n if (seconds < 60) return `${seconds.toFixed(1)}s`;\n const minutes = Math.floor(seconds / 60);\n const secs = Math.floor(seconds % 60);\n return `${minutes}:${secs.toString().padStart(2, \"0\")}`;\n}\n\n/**\n * Execute template locally against local Convex backend.\n */\nasync function runLocal(\n templateId: string,\n options: RunOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n\n const available = await isLocalAvailable();\n if (!available) {\n outputError(\"Local Convex backend not running.\", options);\n process.exit(1);\n }\n\n // Fetch template\n const template = await getTemplate(templateId);\n if (!template) {\n outputError(`Template not found: ${templateId}`, options);\n process.exit(1);\n }\n\n const steps = (template.steps as StepDef[]).sort((a, b) => a.order - b.order);\n\n if (steps.length === 0) {\n outputError(\"Template has no steps to execute.\", options);\n process.exit(1);\n }\n\n // Get API keys (both optional — errors deferred to step execution if needed)\n const replicateToken = await getIntegrationApiKey(\"replicate\");\n const aiGatewayToken = await getIntegrationApiKey(\"ai-gateway\");\n const apiTokens = { replicate: replicateToken, aiGateway: aiGatewayToken };\n\n // Parse input\n let templateInputs: Record<string, unknown> = {};\n if (options.input) {\n try {\n templateInputs = JSON.parse(options.input) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --input\", options);\n process.exit(1);\n }\n }\n\n // Create or use existing execution record\n let executionId = options.executionId;\n executionId ??= await createExecution(templateId, templateInputs);\n\n // Update to running\n await updateExecution(executionId, { status: \"running\" });\n\n if (!options.json) {\n console.log(\n `${chalk.bold(template.name)} - ${steps.length} step${steps.length === 1 ? \"\" : \"s\"}`,\n );\n console.log(chalk.dim(`Execution: ${executionId}`));\n console.log();\n }\n\n const startTime = Date.now();\n const stepOutputs = new Map<number, Record<string, unknown>>();\n const results: {\n stepIndex: number;\n stepId: string;\n success: boolean;\n output?: unknown;\n error?: string;\n duration: number;\n }[] = [];\n\n let allSuccess = true;\n\n for (const [i, step] of steps.entries()) {\n const stepStart = Date.now();\n const stepLabel = `Step ${i + 1}/${steps.length}: ${step.stepId}`;\n\n const spinner = showSpinner ? ora(stepLabel).start() : null;\n\n let logId: string | undefined;\n\n try {\n const resolvedInputs = resolveStepInputs(\n step,\n stepOutputs,\n templateInputs,\n );\n\n // Log step start with resolved inputs (so references are expanded)\n logId = await createExecutionLog(executionId, {\n nodeId: `step-${i}`,\n nodeName: step.stepId,\n nodeType: \"action\",\n status: \"running\",\n input: resolvedInputs,\n startedAt: stepStart,\n });\n\n const output = await executeStepLocally(\n step.stepId,\n resolvedInputs,\n apiTokens,\n );\n\n const duration = Date.now() - stepStart;\n stepOutputs.set(i, output);\n\n spinner?.succeed(`${stepLabel} ${chalk.dim(`(${formatMs(duration)})`)}`);\n\n // Update log\n await updateExecutionLog(logId, {\n status: \"success\",\n output,\n completedAt: Date.now(),\n duration: formatMs(duration),\n });\n\n results.push({\n stepIndex: i,\n stepId: step.stepId,\n success: true,\n output,\n duration,\n });\n } catch (err) {\n const duration = Date.now() - stepStart;\n const errorMsg = err instanceof Error ? err.message : String(err);\n\n spinner?.fail(`${stepLabel} ${chalk.red(errorMsg)}`);\n\n // Update or create log\n if (logId) {\n await updateExecutionLog(logId, {\n status: \"error\",\n error: errorMsg,\n completedAt: Date.now(),\n duration: formatMs(duration),\n });\n } else {\n await createExecutionLog(executionId, {\n nodeId: `step-${i}`,\n nodeName: step.stepId,\n nodeType: \"action\",\n status: \"error\",\n input: step.config,\n error: errorMsg,\n startedAt: stepStart,\n completedAt: Date.now(),\n duration: formatMs(duration),\n });\n }\n\n results.push({\n stepIndex: i,\n stepId: step.stepId,\n success: false,\n error: errorMsg,\n duration,\n });\n\n allSuccess = false;\n break;\n }\n }\n\n const totalDuration = Date.now() - startTime;\n\n // Update execution\n await updateExecution(executionId, {\n status: allSuccess ? \"success\" : \"error\",\n output: allSuccess ? results[results.length - 1]?.output : undefined,\n error: allSuccess ? undefined : results.find((r) => !r.success)?.error,\n completedAt: Date.now(),\n duration: formatMs(totalDuration),\n });\n\n if (options.json) {\n outputSuccess(\n {\n executionId,\n success: allSuccess,\n stepResults: results,\n totalDuration,\n },\n options,\n );\n } else {\n console.log();\n if (allSuccess) {\n console.log(\n formatSuccess(\n `All ${steps.length} steps completed in ${formatMs(totalDuration)}`,\n ),\n );\n } else {\n console.log(\n chalk.red(`Execution failed after ${formatMs(totalDuration)}`),\n );\n }\n }\n}\n\nexport async function runCommand(\n id: string | undefined,\n options: RunOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n await runLocal(templateId, options);\n}\n","import type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError } from \"../../lib/output.js\";\n\nexport interface StatusOptions extends OutputOptions {\n watch?: boolean;\n interval?: number;\n}\n\nexport function statusCommand(\n executionId: string,\n options: StatusOptions,\n): void {\n // TODO: Add execution status query to local-convex.ts\n outputError(\n \"Execution status tracking is not yet available for the local backend. Check the desktop app for execution details.\",\n options,\n );\n process.exit(1);\n}\n","import crypto from \"node:crypto\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\nimport {\n getTemplate,\n isLocalAvailable,\n updateTemplate,\n} from \"../../../lib/local-convex.js\";\nimport {\n formatSuccess,\n outputError,\n outputSuccess,\n} from \"../../../lib/output.js\";\n\nexport interface StepAddOptions extends OutputOptions {\n config?: string;\n at?: number;\n after?: string;\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\nexport async function stepAddCommand(\n stepType: string,\n options: StepAddOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n // Parse config\n let config: Record<string, unknown> = {};\n if (options.config) {\n try {\n config = JSON.parse(options.config) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --config parameter\", options);\n process.exit(1);\n }\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Adding step...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n // Fetch current template\n const template = await getTemplate(templateId);\n\n if (!template) {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = (template.steps as Step[]).map((s) => ({ ...s }));\n\n // Generate unique ID for the new step\n const newId = crypto.randomUUID().slice(0, 8);\n\n // Determine insertion position\n let insertAt: number;\n if (options.at !== undefined) {\n insertAt = Math.max(0, Math.min(options.at, steps.length));\n } else if (options.after) {\n const afterIndex = steps.findIndex((s) => s.id === options.after);\n if (afterIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step with id \"${options.after}\" not found`, options);\n process.exit(1);\n }\n insertAt = afterIndex + 1;\n } else {\n insertAt = steps.length;\n }\n\n // Create the new step\n const newStep: Step = {\n id: newId,\n stepId: stepType,\n config,\n order: insertAt,\n };\n\n // Insert and re-number\n steps.splice(insertAt, 0, newStep);\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i];\n if (s) s.order = i;\n }\n\n // Update template\n await updateTemplate(templateId, { steps });\n\n spinner?.stop();\n spinner?.clear();\n\n if (options.json) {\n outputSuccess(\n { id: newId, stepId: stepType, order: insertAt, templateId },\n options,\n );\n } else {\n console.log(formatSuccess(`Step added: ${stepType}`));\n console.log(chalk.dim(` Step ID: ${newId}`));\n console.log(chalk.dim(` Position: ${insertAt}`));\n }\n}\n","import type { OutputOptions } from \"../../../lib/output.js\";\nimport { outputError } from \"../../../lib/output.js\";\n\nexport type StepInfoOptions = OutputOptions;\n\nexport function stepInfoCommand(\n _stepType: string,\n options: StepInfoOptions,\n): void {\n outputError(\n \"Step type info is not yet available for the local backend. Check the desktop app for step type details.\",\n options,\n );\n process.exit(1);\n}\n","import type { OutputOptions } from \"../../../lib/output.js\";\nimport { outputError } from \"../../../lib/output.js\";\n\nexport interface StepListOptions extends OutputOptions {\n category?: string;\n}\n\nexport function stepListCommand(options: StepListOptions): void {\n outputError(\n \"Step type listing is not yet available for the local backend. Check the desktop app for available step types.\",\n options,\n );\n process.exit(1);\n}\n","import ora from \"ora\";\n\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\nimport {\n getTemplate,\n isLocalAvailable,\n updateTemplate,\n} from \"../../../lib/local-convex.js\";\nimport {\n formatSuccess,\n outputError,\n outputSuccess,\n} from \"../../../lib/output.js\";\n\nexport interface StepRemoveOptions extends OutputOptions {\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\nexport async function stepRemoveCommand(\n stepInstanceId: string,\n options: StepRemoveOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Removing step...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n // Fetch current template\n const template = await getTemplate(templateId);\n\n if (!template) {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = template.steps as Step[];\n const removeIndex = steps.findIndex((s) => s.id === stepInstanceId);\n\n if (removeIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(\n `Step with id \"${stepInstanceId}\" not found in template`,\n options,\n );\n process.exit(1);\n }\n\n const removed = steps[removeIndex];\n if (!removed) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step at index ${removeIndex} not found`, options);\n process.exit(1);\n }\n\n // Remove and re-number\n const newSteps = steps.filter((_, i) => i !== removeIndex);\n for (let i = 0; i < newSteps.length; i++) {\n const s = newSteps[i];\n if (s) s.order = i;\n }\n\n // Update template\n await updateTemplate(templateId, { steps: newSteps });\n\n spinner?.stop();\n spinner?.clear();\n\n if (options.json) {\n outputSuccess(\n { removed: stepInstanceId, stepId: removed.stepId, templateId },\n options,\n );\n } else {\n console.log(\n formatSuccess(`Removed step: ${removed.stepId} (${stepInstanceId})`),\n );\n }\n}\n","import ora from \"ora\";\n\nimport type { OutputOptions } from \"../../../lib/output.js\";\nimport { getActiveTemplate } from \"../../../lib/context.js\";\nimport {\n getTemplate,\n isLocalAvailable,\n updateTemplate,\n} from \"../../../lib/local-convex.js\";\nimport {\n formatSuccess,\n outputError,\n outputSuccess,\n} from \"../../../lib/output.js\";\n\nexport interface StepUpdateOptions extends OutputOptions {\n config?: string;\n template?: string;\n}\n\ninterface Step {\n id?: string;\n stepId: string;\n config: Record<string, unknown>;\n order: number;\n nestedSteps?: Step[];\n}\n\nexport async function stepUpdateCommand(\n stepInstanceId: string,\n options: StepUpdateOptions,\n): Promise<void> {\n const templateId = options.template ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID. Use --template <id> or set active template with 'template use <id>'.\",\n options,\n );\n process.exit(1);\n }\n\n if (!options.config) {\n outputError(\"--config is required\", options);\n process.exit(1);\n }\n\n // Parse config to merge\n let configPatch: Record<string, unknown>;\n try {\n configPatch = JSON.parse(options.config) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --config parameter\", options);\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Updating step...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n // Fetch current template\n const template = await getTemplate(templateId);\n\n if (!template) {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Template not found\", options);\n process.exit(1);\n }\n\n const steps: Step[] = (template.steps as Step[]).map((s) => ({ ...s }));\n const stepIndex = steps.findIndex((s) => s.id === stepInstanceId);\n\n if (stepIndex === -1) {\n spinner?.stop();\n spinner?.clear();\n outputError(\n `Step with id \"${stepInstanceId}\" not found in template`,\n options,\n );\n process.exit(1);\n }\n\n const targetStep = steps[stepIndex];\n if (!targetStep) {\n spinner?.stop();\n spinner?.clear();\n outputError(`Step at index ${stepIndex} not found`, options);\n process.exit(1);\n }\n\n // Merge config\n targetStep.config = {\n ...targetStep.config,\n ...configPatch,\n };\n\n // Update template\n await updateTemplate(templateId, { steps });\n\n spinner?.stop();\n spinner?.clear();\n\n if (options.json) {\n outputSuccess(\n {\n id: stepInstanceId,\n stepId: targetStep.stepId,\n config: targetStep.config,\n templateId,\n },\n options,\n );\n } else {\n console.log(\n formatSuccess(`Updated step: ${targetStep.stepId} (${stepInstanceId})`),\n );\n }\n}\n","import ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { getActiveTemplate } from \"../../lib/context.js\";\nimport {\n isLocalAvailable,\n updateTemplate as localUpdateTemplate,\n} from \"../../lib/local-convex.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport interface UpdateOptions extends OutputOptions {\n name?: string;\n description?: string;\n steps?: string;\n}\n\nexport async function updateCommand(\n id: string | undefined,\n options: UpdateOptions,\n): Promise<void> {\n const templateId = id ?? getActiveTemplate();\n if (!templateId) {\n outputError(\n \"No template ID provided and no active template set. Use 'template use <id>' to set one.\",\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Updating template...\").start() : null;\n\n const updates: Record<string, unknown> = {};\n if (options.name !== undefined) updates.name = options.name;\n if (options.description !== undefined) updates.description = options.description;\n if (options.steps !== undefined) {\n try {\n updates.steps = JSON.parse(options.steps) as unknown[];\n } catch {\n spinner?.stop();\n spinner?.clear();\n outputError(\"Invalid JSON in --steps parameter\", options);\n process.exit(1);\n }\n }\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n await localUpdateTemplate(templateId, updates);\n\n spinner?.stop();\n spinner?.clear();\n\n if (options.json) {\n outputSuccess({ id: templateId, updated: true }, options);\n } else {\n console.log(formatSuccess(\"Template updated\"));\n }\n}\n","import chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { setActiveTemplate } from \"../../lib/context.js\";\nimport {\n getTemplate as localGetTemplate,\n isLocalAvailable,\n} from \"../../lib/local-convex.js\";\nimport { formatSuccess, outputError, outputSuccess } from \"../../lib/output.js\";\n\nexport type UseOptions = OutputOptions;\n\nexport async function useCommand(\n id: string,\n options: UseOptions,\n): Promise<void> {\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(\"Verifying template...\").start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n const result = await localGetTemplate(id);\n\n spinner?.stop();\n spinner?.clear();\n\n if (!result) {\n outputError(\"Template not found\", options);\n process.exit(1);\n }\n\n setActiveTemplate(id);\n\n if (options.json) {\n outputSuccess({ id, name: result.name, active: true }, options);\n } else {\n console.log(formatSuccess(`Active template set to \"${result.name}\"`));\n console.log(chalk.dim(` ID: ${id}`));\n }\n}\n","import { execSync } from \"node:child_process\";\nimport crypto from \"node:crypto\";\nimport {\n existsSync,\n rmSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { access, mkdir, mkdtemp, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport ora from \"ora\";\n\nimport {\n DEFAULT_IMAGE_MODEL,\n DEFAULT_SPEECH_MODEL,\n DEFAULT_VIDEO_MODEL,\n detectProvider,\n generateImage as generateImageInference,\n} from \"@program-video/inference\";\nimport { generateSpeechStep, generateVideoStep } from \"@program-video/steps\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport type { VideoAnalysis } from \"../research/types.js\";\nimport {\n addScene,\n createComposition,\n createStepExecution,\n deleteAllScenes,\n deleteScene,\n getComposition,\n getIntegrationApiKey,\n getResearch,\n isLocalAvailable,\n listCompositions,\n saveRemoteMediaToStorage,\n updateComposition,\n updateScene,\n updateStepExecution,\n} from \"../../lib/local-convex.js\";\nimport { outputError, outputSuccess } from \"../../lib/output.js\";\nimport { runShell } from \"../../lib/shell.js\";\nimport { createLocalStepDb } from \"../../lib/step-db.js\";\nimport { initWorkflowRuntime } from \"../../lib/workflow.js\";\nimport {\n extractAudio as extractAudioTrack,\n getVideoDuration,\n} from \"../research/pipeline.js\";\nimport { ensureVideo } from \"../research/sample.js\";\nimport type { WhisperResult } from \"../audio/captions.js\";\nimport {\n buildCaptionEntries,\n generateCaptionCode,\n} from \"../audio/captions.js\";\n\nexport interface ExecuteOptions extends OutputOptions {\n project?: string;\n params?: string;\n paramsFile?: string;\n}\n\nconst AUDIO_CACHE_DIR = \"/tmp/program-video-cache/audio\";\n\n// ============================================================================\n// Tool dispatcher\n// ============================================================================\n\ntype ToolHandler = (\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n) => Promise<unknown>;\n\ninterface LocalTranscriptWord {\n word: string;\n start: number;\n end: number;\n}\n\ninterface LocalTranscriptSegment {\n start: number;\n end: number;\n text: string;\n words?: LocalTranscriptWord[];\n}\n\ninterface LocalTranscriptResult {\n text: string;\n words: LocalTranscriptWord[];\n segments: LocalTranscriptSegment[];\n}\n\nconst tools: Record<string, ToolHandler> = {\n // Composition tools (require --project)\n assessComposition: handleAssessComposition,\n readComposition: handleReadComposition,\n setMetadata: handleSetMetadata,\n addScene: handleAddScene,\n deleteScene: handleDeleteScene,\n deleteAllScenes: handleDeleteAllScenes,\n updateScene: handleUpdateScene,\n\n // Composition creation (no --project needed)\n createComposition: handleCreateComposition,\n\n // Generation tools (require --project for scene creation)\n generateSpeech: handleGenerateSpeech,\n extractAudio: handleExtractAudio,\n generateVideo: handleGenerateVideo,\n generateImage: handleGenerateImage,\n transcribeAudio: handleTranscribeAudio,\n\n // Utility tools\n listCompositions: handleListCompositions,\n trimSilence: handleTrimSilence,\n buildCaptions: handleBuildCaptions,\n generateSubtitles: handleGenerateSubtitles,\n\n // Model listing\n listSpeechModels: handleListSpeechModels,\n listVideoModels: handleListVideoModels,\n listImageModels: handleListImageModels,\n\n // Reference tools\n referenceLayout: handleReferenceLayout,\n};\n\nconst TOOLS_REQUIRING_PROJECT = new Set([\n \"assessComposition\",\n \"readComposition\",\n \"setMetadata\",\n \"addScene\",\n \"deleteScene\",\n \"deleteAllScenes\",\n \"updateScene\",\n \"generateSpeech\",\n \"extractAudio\",\n \"generateVideo\",\n \"trimSilence\",\n \"buildCaptions\",\n \"generateSubtitles\",\n]);\n\nexport async function executeCommand(\n toolName: string,\n options: ExecuteOptions,\n): Promise<void> {\n const handler = tools[toolName];\n if (!handler) {\n outputError(\n `Unknown tool: \"${toolName}\". Run 'program tool list' to see available tools.`,\n options,\n );\n process.exit(1);\n }\n\n // Parse params — from --params JSON, --params-file path, or stdin (--params -)\n let params: Record<string, unknown> = {};\n if (options.paramsFile) {\n try {\n const { readFileSync } = await import(\"node:fs\");\n const raw = readFileSync(options.paramsFile, \"utf-8\");\n params = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n outputError(\n `Failed to read --params-file: ${(err as Error).message}`,\n options,\n );\n process.exit(1);\n }\n } else if (options.params === \"-\") {\n // Read from stdin\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n params = JSON.parse(raw) as Record<string, unknown>;\n } catch (err) {\n outputError(\n `Failed to read params from stdin: ${(err as Error).message}`,\n options,\n );\n process.exit(1);\n }\n } else if (options.params) {\n try {\n params = JSON.parse(options.params) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --params\", options);\n process.exit(1);\n }\n }\n\n const compositionId = options.project;\n if (TOOLS_REQUIRING_PROJECT.has(toolName) && !compositionId) {\n outputError(\n `--project <compositionId> is required for tool \"${toolName}\"`,\n options,\n );\n process.exit(1);\n }\n\n const showSpinner = !options.json && process.stdout.isTTY;\n const spinner = showSpinner ? ora(`Executing ${toolName}...`).start() : null;\n\n if (!(await isLocalAvailable())) {\n spinner?.stop();\n outputError(\n \"Local backend not available at http://127.0.0.1:3210\",\n options,\n );\n process.exit(1);\n }\n\n // Initialize workflow runtime (idempotent)\n initWorkflowRuntime();\n\n try {\n const result = await handler(params, compositionId, spinner);\n spinner?.stop();\n outputSuccess(result, options);\n } catch (err) {\n spinner?.stop();\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n\n// ============================================================================\n// Composition tools\n// ============================================================================\n\nasync function handleCreateComposition(\n params: Record<string, unknown>,\n): Promise<unknown> {\n const title = params.title as string;\n if (!title) throw new Error(\"title is required\");\n\n const id = await createComposition(title, {\n width: (params.width as number | undefined) ?? 1080,\n height: (params.height as number | undefined) ?? 1920,\n fps: (params.fps as number | undefined) ?? 30,\n description: params.description as string | undefined,\n });\n\n return {\n success: true,\n compositionId: id,\n message: `Created composition \"${title}\" (${id})`,\n };\n}\n\nasync function handleAssessComposition(\n _params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n const comp = await getComposition(compositionId);\n if (!comp) throw new Error(\"Composition not found\");\n\n const scenes = (comp.scenes ?? []) as Record<string, unknown>[];\n\n const sceneSummaries = scenes.map((scene) => {\n const metadata = (scene.metadata ?? {}) as Record<string, unknown>;\n const config = (scene.config ?? {}) as Record<string, unknown>;\n const status =\n typeof metadata.status === \"string\" ? metadata.status : \"draft\";\n\n const summary: Record<string, unknown> = {\n id: scene.id,\n type: scene.type,\n start: scene.start,\n duration: scene.duration,\n layer: typeof metadata.layer === \"number\" ? metadata.layer : 0,\n status,\n title: typeof metadata.title === \"string\" ? metadata.title : \"Untitled\",\n description:\n typeof metadata.description === \"string\" ? metadata.description : \"\",\n };\n\n if (scene.type === \"code_scene\") {\n const files = metadata.files as Record<string, string> | undefined;\n summary.hasCode = !!(\n files?.[\"index.tsx\"] &&\n files[\"index.tsx\"] !== \"// Code will be generated during execution\"\n );\n } else if (scene.type === \"video_scene\") {\n summary.hasVideo = !!config.url;\n } else if (scene.type === \"audio_scene\") {\n summary.hasAudio = !!config.audioUrl;\n }\n\n return summary;\n });\n\n const byStatus: Record<string, number> = {};\n const byType: Record<string, number> = {};\n for (const s of sceneSummaries) {\n const st = s.status as string;\n const tp = s.type as string;\n byStatus[st] = (byStatus[st] ?? 0) + 1;\n byType[tp] = (byType[tp] ?? 0) + 1;\n }\n\n return {\n success: true,\n composition: {\n id: comp._id,\n title: comp.title ?? null,\n description: comp.description ?? null,\n duration: comp.duration ?? null,\n fps: comp.fps ?? null,\n width: comp.width ?? null,\n height: comp.height ?? null,\n },\n scenes: sceneSummaries,\n summary: { total: scenes.length, byStatus, byType },\n };\n}\n\nasync function handleReadComposition(\n _params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n const comp = await getComposition(compositionId);\n if (!comp) throw new Error(\"Composition not found\");\n return { success: true, composition: comp };\n}\n\nasync function handleSetMetadata(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n const updates: Record<string, unknown> = {};\n if (params.title !== undefined) updates.title = params.title;\n if (params.description !== undefined)\n updates.description = params.description;\n if (params.script !== undefined) updates.script = params.script;\n if (params.duration !== undefined) updates.duration = params.duration;\n if (params.fps !== undefined) updates.fps = Math.trunc(params.fps as number);\n if (params.width !== undefined)\n updates.width = Math.trunc(params.width as number);\n if (params.height !== undefined)\n updates.height = Math.trunc(params.height as number);\n\n if (!compositionId) throw new Error(\"compositionId is required\");\n await updateComposition(compositionId, updates);\n return { success: true, message: \"Composition metadata updated\" };\n}\n\nasync function handleAddScene(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n const sceneId = crypto.randomUUID();\n const sceneType = (params.type as string | undefined) ?? \"code_scene\";\n const sceneTitle = (params.title ?? params.name) as string;\n if (!sceneTitle) throw new Error(\"title (or name) is required\");\n\n let duration = params.duration as number | undefined;\n\n // Auto-infer duration from media URL for video/audio scenes\n if (\n (!duration || duration <= 0) &&\n params.url &&\n (sceneType === \"video_scene\" || sceneType === \"audio_scene\")\n ) {\n try {\n const probedDuration = await getVideoDuration(params.url as string);\n if (probedDuration > 0) duration = probedDuration;\n } catch {\n // ffprobe not available or URL not probeable\n }\n }\n\n if (!duration || duration <= 0)\n throw new Error(\"duration is required and must be positive\");\n\n const sceneStart = (params.start as number | undefined) ?? 0;\n const end = sceneStart + duration;\n const sceneLayer = (params.layer as number | undefined) ?? 0;\n\n let scene: Record<string, unknown>;\n\n if (sceneType === \"code_scene\") {\n let code = params.code as string;\n if (!code) throw new Error(\"code is required when type is code_scene\");\n\n if (!code.includes(\"export default\") && !code.includes(\"export {\")) {\n const m =\n /(?:const|let|var|function)\\s+([A-Z][A-Za-z0-9_$]*)\\s*[=:(]/.exec(code);\n if (m?.[1]) code = `${code}\\n\\nexport default ${m[1]};`;\n }\n\n scene = {\n id: sceneId,\n type: \"code_scene\",\n start: sceneStart,\n end,\n duration,\n order: sceneLayer,\n componentId: sceneId,\n props: {},\n metadata: {\n title: sceneTitle,\n layer: sceneLayer,\n snapshot: true,\n code,\n files: { \"index.tsx\": code },\n entryPoint: \"index.tsx\",\n },\n };\n } else if (sceneType === \"video_scene\" || sceneType === \"image_scene\") {\n // URL is optional — scenes created for node-graph generation won't have one yet.\n scene = {\n id: sceneId,\n type: sceneType,\n start: sceneStart,\n end,\n duration,\n order: sceneLayer,\n config: {\n ...(params.url ? { url: params.url } : {}),\n ...(params.fileId ? { fileId: params.fileId } : {}),\n },\n metadata: { title: sceneTitle, layer: sceneLayer },\n };\n } else {\n // audio_scene\n scene = {\n id: sceneId,\n type: \"audio_scene\",\n start: sceneStart,\n end,\n duration,\n order: sceneLayer,\n config: {\n ...(params.url ? { audioUrl: params.url } : {}),\n ...(params.fileId ? { fileId: params.fileId } : {}),\n },\n metadata: { title: sceneTitle, layer: sceneLayer },\n };\n }\n\n if (!compositionId) throw new Error(\"compositionId is required\");\n await addScene(compositionId, scene);\n\n return {\n success: true,\n sceneId,\n type: sceneType,\n title: sceneTitle,\n message: `Added scene \"${sceneTitle}\" (${duration}s) starting at ${sceneStart}s`,\n };\n}\n\nasync function handleDeleteScene(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n if (!params.sceneId) throw new Error(\"sceneId is required\");\n const sceneId = params.sceneId as string;\n await deleteScene(compositionId, sceneId);\n return { success: true, message: `Scene ${sceneId} deleted` };\n}\n\nasync function handleDeleteAllScenes(\n _params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n await deleteAllScenes(compositionId);\n return { success: true, message: \"All scenes deleted\" };\n}\n\nasync function handleUpdateScene(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n if (!params.sceneId) throw new Error(\"sceneId is required\");\n const sceneId = params.sceneId as string;\n\n const comp = await getComposition(compositionId);\n if (!comp) throw new Error(\"Composition not found\");\n\n const scenes = (comp.scenes ?? []) as Record<string, unknown>[];\n const scene = scenes.find((s) => s.id === sceneId);\n if (!scene) throw new Error(`Scene ${sceneId} not found`);\n\n const updates: Record<string, unknown> = {};\n\n // Timing updates (any scene type) — end is always derived from start + duration\n if (params.start !== undefined) updates.start = params.start;\n if (params.duration !== undefined) updates.duration = params.duration;\n if (params.start !== undefined || params.duration !== undefined) {\n const start =\n (updates.start as number | undefined) ??\n (scene.start as number | undefined) ??\n 0;\n const duration =\n (updates.duration as number | undefined) ??\n (scene.duration as number | undefined) ??\n 0;\n updates.end = start + duration;\n }\n\n // Code scene updates\n if (params.code && scene.type === \"code_scene\") {\n let code = params.code as string;\n if (!code.includes(\"export default\") && !code.includes(\"export {\")) {\n const m =\n /(?:const|let|var|function)\\s+([A-Z][A-Za-z0-9_$]*)\\s*[=:(]/.exec(code);\n if (m?.[1]) code = `${code}\\n\\nexport default ${m[1]};`;\n }\n\n const metadata = (scene.metadata ?? {}) as Record<string, unknown>;\n updates.metadata = {\n ...metadata,\n title: (params.title as string | undefined) ?? metadata.title,\n code,\n files: { \"index.tsx\": code },\n entryPoint: \"index.tsx\",\n snapshot: true,\n };\n }\n\n // Config updates (audio/video/image scenes)\n if (params.url || params.config) {\n const existingConfig = (scene.config ?? {}) as Record<string, unknown>;\n if (params.url) {\n const urlKey = scene.type === \"audio_scene\" ? \"audioUrl\" : \"url\";\n updates.config = { ...existingConfig, [urlKey]: params.url };\n\n // Auto-infer duration from media when URL is set and no explicit duration provided\n if (\n params.duration === undefined &&\n (scene.type === \"video_scene\" || scene.type === \"audio_scene\")\n ) {\n try {\n const probedDuration = await getVideoDuration(params.url as string);\n if (probedDuration > 0) {\n updates.duration = probedDuration;\n const start =\n (updates.start as number | undefined) ??\n (scene.start as number | undefined) ??\n 0;\n updates.end = start + probedDuration;\n }\n } catch {\n // ffprobe not available or URL not probeable, skip\n }\n }\n }\n if (params.config) {\n updates.config = {\n ...existingConfig,\n ...(params.config as Record<string, unknown>),\n };\n }\n }\n\n // Title update for non-code scenes\n if (params.title && scene.type !== \"code_scene\") {\n const metadata = (scene.metadata ?? {}) as Record<string, unknown>;\n updates.metadata = { ...metadata, title: params.title };\n }\n\n if (Object.keys(updates).length === 0) {\n throw new Error(\n \"No updates provided. Pass code, start, duration, url, config, or title.\",\n );\n }\n\n await updateScene(compositionId, sceneId, updates);\n\n return {\n success: true,\n sceneId,\n message: `Updated scene ${sceneId}`,\n };\n}\n\n// ============================================================================\n// Generation tools\n// ============================================================================\n\nasync function handleGenerateSpeech(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n const text = (params.text ?? params.prompt) as string;\n if (!text) throw new Error(\"text is required\");\n\n if (!compositionId) throw new Error(\"compositionId is required\");\n const model = (params.model as string | undefined) ?? DEFAULT_SPEECH_MODEL;\n const provider = (params.provider as string | undefined) ?? \"replicate\";\n\n if (spinner) spinner.text = `Generating speech with ${model}...`;\n\n // Create step execution record\n const execId = await createStepExecution({\n step: \"generateSpeech\",\n model,\n provider,\n compositionId,\n sceneId: params.sceneId as string | undefined,\n nodeId: params.nodeId as string | undefined,\n input: { text, model },\n });\n const db = createLocalStepDb();\n const startTime = Date.now();\n let providerApiKey: string | undefined;\n\n try {\n providerApiKey = (await getIntegrationApiKey(\"replicate\")) ?? undefined;\n } catch {\n // Resolution is also handled by the step runtime.\n }\n\n try {\n const result = await generateSpeechStep(db, {\n text,\n compositionId,\n model,\n providerApiKey,\n voiceClone: await resolveAudioPrompt(\n (params.voiceClone ?? params.audioUrl) as string | undefined,\n ),\n sceneId: params.sceneId as string | undefined,\n start: params.start as number | undefined,\n duration: params.duration as number | undefined,\n title: params.title as string | undefined,\n layer: params.layer as number | undefined,\n });\n\n await updateStepExecution(execId, {\n status: \"success\",\n output: result as unknown as Record<string, unknown>,\n durationMs: Date.now() - startTime,\n });\n\n return {\n ...result,\n message: `Generated ${result.duration.toFixed(1)}s of speech`,\n };\n } catch (err) {\n await updateStepExecution(execId, {\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n durationMs: Date.now() - startTime,\n });\n throw err;\n }\n}\n\nfunction inferMediaContentType(input: string): string {\n const ext = (input.split(\"?\")[0] ?? input).split(\".\").pop()?.toLowerCase() ?? \"\";\n const mimeMap: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n bmp: \"image/bmp\",\n svg: \"image/svg+xml\",\n wav: \"audio/wav\",\n mp3: \"audio/mpeg\",\n m4a: \"audio/mp4\",\n aac: \"audio/aac\",\n ogg: \"audio/ogg\",\n mp4: \"video/mp4\",\n webm: \"video/webm\",\n mov: \"video/quicktime\",\n };\n return mimeMap[ext] ?? \"application/octet-stream\";\n}\n\nfunction localAssetUrlToFilePath(url: string): string {\n const parsed = new URL(url);\n return decodeURIComponent(parsed.pathname);\n}\n\nfunction isLoopbackUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.hostname === \"127.0.0.1\" || parsed.hostname === \"localhost\";\n } catch {\n return false;\n }\n}\n\nfunction bytesToDataUri(bytes: Uint8Array, contentType: string): string {\n return `data:${contentType};base64,${Buffer.from(bytes).toString(\"base64\")}`;\n}\n\nasync function resolveAudioPrompt(\n source: string | undefined,\n): Promise<string | undefined> {\n if (!source) return undefined;\n\n if (existsSync(source)) {\n return bytesToDataUri(\n await readFile(source),\n inferMediaContentType(source),\n );\n }\n\n if (source.startsWith(\"localasset://\")) {\n const filePath = localAssetUrlToFilePath(source);\n return bytesToDataUri(\n await readFile(filePath),\n inferMediaContentType(filePath),\n );\n }\n\n if (isLoopbackUrl(source)) {\n const response = await fetch(source);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch local audio reference: ${response.status} ${response.statusText}`,\n );\n }\n const contentType =\n response.headers.get(\"content-type\") ?? inferMediaContentType(source);\n return bytesToDataUri(\n new Uint8Array(await response.arrayBuffer()),\n contentType.split(\";\")[0] ?? contentType,\n );\n }\n\n return source;\n}\n\nasync function materializeVideoPath(source: string): Promise<{\n filePath: string;\n cleanup: () => void;\n}> {\n if (existsSync(source)) {\n return { filePath: source, cleanup: () => { /* noop */ } };\n }\n\n if (source.startsWith(\"localasset://\")) {\n return { filePath: localAssetUrlToFilePath(source), cleanup: () => { /* noop */ } };\n }\n\n const tempDir = await mkdtemp(path.join(tmpdir(), \"program-extract-audio-\"));\n const ext = path.extname(source.split(\"?\")[0] ?? \"\") || \".mp4\";\n const filePath = path.join(tempDir, `input${ext}`);\n\n const response = await fetch(source);\n if (!response.ok) {\n rmSync(tempDir, { recursive: true, force: true });\n throw new Error(\n `Failed to fetch video source: ${response.status} ${response.statusText}`,\n );\n }\n\n writeFileSync(filePath, Buffer.from(await response.arrayBuffer()));\n\n return {\n filePath,\n cleanup: () => {\n rmSync(tempDir, { recursive: true, force: true });\n },\n };\n}\n\nasync function handleExtractAudio(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n const videoUrl = params.videoUrl as string | undefined;\n if (!videoUrl) throw new Error(\"videoUrl is required\");\n if (!compositionId) throw new Error(\"compositionId is required\");\n\n if (spinner) spinner.text = \"Extracting audio from reference video...\";\n\n const execId = await createStepExecution({\n step: \"extractAudio\",\n model: \"ffmpeg\",\n provider: \"local\",\n compositionId,\n sceneId: params.sceneId as string | undefined,\n nodeId: params.nodeId as string | undefined,\n input: { videoUrl },\n });\n\n const db = createLocalStepDb();\n const startTime = Date.now();\n let cleanup = () => { /* noop */ };\n let workDir: string | null = null;\n\n try {\n const source = await materializeVideoPath(videoUrl);\n cleanup = source.cleanup;\n workDir = await mkdtemp(path.join(tmpdir(), \"program-audio-track-\"));\n const audioPath = await extractAudioTrack(source.filePath, workDir);\n const bytes = await readFile(audioPath);\n const stored = await db.storeFile(bytes, \"audio/wav\");\n const probedDuration = await getVideoDuration(audioPath);\n const duration =\n probedDuration > 0\n ? probedDuration\n : (params.duration as number | undefined) ?? 0;\n\n const result = {\n success: true,\n audioUrl: stored.url,\n storageId: stored.storageId,\n duration,\n };\n\n await updateStepExecution(execId, {\n status: \"success\",\n output: result as Record<string, unknown>,\n durationMs: Date.now() - startTime,\n });\n\n return result;\n } catch (err) {\n await updateStepExecution(execId, {\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n durationMs: Date.now() - startTime,\n });\n throw err;\n } finally {\n if (workDir) {\n rmSync(workDir, { recursive: true, force: true });\n }\n cleanup();\n }\n}\n\n/**\n * If imageUrl points to a local file (flagged by imageUrlIsLocalFile),\n * read it and convert to a base64 data URI for the inference API.\n */\nfunction resolveImageUrl(params: Record<string, unknown>): string | undefined {\n const imageUrl = params.imageUrl as string | undefined;\n if (!imageUrl) return undefined;\n\n if (params.imageUrlIsLocalFile) {\n try {\n const bytes = readFileSync(imageUrl);\n const ext = path.extname(imageUrl).slice(1).toLowerCase();\n const mimeMap: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n bmp: \"image/bmp\",\n };\n const mime = mimeMap[ext] ?? \"image/png\";\n return `data:${mime};base64,${bytes.toString(\"base64\")}`;\n } catch (err) {\n throw new Error(\n `Failed to read local image file: ${(err as Error).message}`,\n );\n }\n }\n\n return imageUrl;\n}\n\nasync function handleGenerateVideo(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n const prompt = params.prompt as string;\n if (!prompt) throw new Error(\"prompt is required\");\n\n if (!compositionId) throw new Error(\"compositionId is required\");\n const model = (params.model as string | undefined) ?? DEFAULT_VIDEO_MODEL;\n const provider =\n (params.provider as string | undefined) ?? detectProvider(model);\n\n if (spinner) spinner.text = `Generating video with ${model} (${provider})...`;\n\n // Create step execution record\n const execId = await createStepExecution({\n step: \"generateVideo\",\n model,\n provider,\n compositionId,\n sceneId: params.sceneId as string | undefined,\n nodeId: params.nodeId as string | undefined,\n input: { prompt, model, provider },\n });\n const db = createLocalStepDb();\n\n // Resolve API key for the detected provider\n let providerApiKey: string | undefined;\n try {\n const keyProvider = provider === \"replicate\" ? \"replicate\" : provider;\n providerApiKey = (await getIntegrationApiKey(keyProvider)) ?? undefined;\n } catch {\n // Key resolution handled by step\n }\n\n // Model-specific input fields (already snake_case, built by the desktop executor)\n const modelInput = (params.modelInput ?? {}) as Record<string, unknown>;\n\n try {\n const result = await generateVideoStep(db, {\n prompt,\n model,\n compositionId,\n provider: provider as \"replicate\" | \"fal\" | \"ai-gateway\",\n providerApiKey,\n sceneId: params.sceneId as string | undefined,\n start: params.start as number | undefined,\n layer: params.layer as number | undefined,\n title: params.title as string | undefined,\n imageUrl: resolveImageUrl(params),\n duration: params.duration as number | undefined,\n aspectRatio: (params.aspectRatio ?? modelInput.aspect_ratio) as\n | string\n | undefined,\n resolution: (params.resolution ?? modelInput.resolution) as\n | string\n | undefined,\n });\n\n await updateStepExecution(execId, {\n status: \"success\",\n output: result as unknown as Record<string, unknown>,\n costUsd: result.costUsd,\n durationMs: result.durationMs,\n });\n\n return {\n ...result,\n message: `Generated ${result.duration.toFixed(1)}s video with ${result.model} (${result.provider})`,\n };\n } catch (err) {\n await updateStepExecution(execId, {\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n}\n\nasync function handleGenerateImage(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n const prompt = params.prompt as string;\n if (!prompt) throw new Error(\"prompt is required\");\n\n const model = (params.model as string | undefined) ?? DEFAULT_IMAGE_MODEL;\n const provider =\n (params.provider as string | undefined) ?? detectProvider(model);\n\n if (spinner) spinner.text = `Generating image with ${model} (${provider})...`;\n\n const execId = await createStepExecution({\n step: \"generateImage\",\n model,\n provider,\n compositionId,\n sceneId: params.sceneId as string | undefined,\n nodeId: params.nodeId as string | undefined,\n input: { prompt, model, provider },\n });\n\n let providerApiKey: string | undefined;\n try {\n const keyProvider = provider === \"replicate\" ? \"replicate\" : provider;\n providerApiKey = (await getIntegrationApiKey(keyProvider)) ?? undefined;\n } catch {\n // Key resolution handled by step\n }\n\n // Model-specific input fields (already snake_case, built by the executor)\n const modelInput = (params.modelInput ?? {}) as Record<string, unknown>;\n\n try {\n // Map imageUrl to the correct model input key\n const imageInputKey = model.includes(\"nano-banana\")\n ? \"image_input\"\n : \"image\";\n\n const result = await generateImageInference({\n model,\n input: {\n prompt,\n ...(params.imageUrl\n ? { [imageInputKey]: resolveImageUrl(params) }\n : {}),\n // Spread all model-specific params (aspect_ratio, num_outputs, etc.)\n ...modelInput,\n },\n apiToken: providerApiKey,\n });\n\n const remoteUrl = result.output.url;\n\n // Save to local Convex storage immediately — provider URLs expire\n let imageUrl = remoteUrl;\n if (remoteUrl) {\n try {\n imageUrl = await saveRemoteMediaToStorage(remoteUrl);\n } catch (saveErr) {\n console.error(\n \"[generateImage] Failed to save to local storage:\",\n saveErr,\n );\n // Fall back to remote URL — it may still work temporarily\n }\n }\n\n await updateStepExecution(execId, {\n status: \"success\",\n output: { imageUrl } as Record<string, unknown>,\n });\n\n return {\n imageUrl,\n prompt,\n model,\n provider,\n message: `Generated image with ${model} (${provider})`,\n };\n } catch (err) {\n await updateStepExecution(execId, {\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n}\n\nfunction transcribeLocalAudioFile(\n filePath: string,\n opts?: { model?: string; output?: string },\n): LocalTranscriptResult {\n if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);\n\n try {\n execSync('python3 -c \"import whisper\"', { stdio: \"ignore\" });\n } catch {\n throw new Error(\n \"openai-whisper not installed. Install with: pip install openai-whisper\",\n );\n }\n\n const model = opts?.model ?? \"base\";\n\n const pythonScript = `\nimport whisper, json, sys\nmodel = whisper.load_model(\"${model}\")\nresult = model.transcribe(sys.argv[1], word_timestamps=True)\ndef clean(obj):\n if isinstance(obj, dict):\n return {k: clean(v) for k, v in obj.items()}\n if isinstance(obj, list):\n return [clean(v) for v in obj]\n if hasattr(obj, 'item'):\n return obj.item()\n return obj\nprint(json.dumps(clean(result), ensure_ascii=False))\n`.trim();\n\n const output = execSync(\n `python3 -c '${pythonScript.replace(/'/g, \"'\\\\''\")}' \"${filePath}\"`,\n { encoding: \"utf-8\", timeout: 120000, maxBuffer: 50 * 1024 * 1024 },\n );\n\n const raw = JSON.parse(output) as {\n text: string;\n segments: {\n start: number;\n end: number;\n text: string;\n words?: {\n word: string;\n start: number;\n end: number;\n probability: number;\n }[];\n }[];\n };\n\n const words = raw.segments.flatMap((seg) =>\n (seg.words ?? []).map((w) => ({\n word: w.word.trim(),\n start: Math.round(w.start * 100) / 100,\n end: Math.round(w.end * 100) / 100,\n })),\n );\n\n const result: LocalTranscriptResult = {\n text: raw.text.trim(),\n words,\n segments: raw.segments.map((s) => ({\n start: s.start,\n end: s.end,\n text: s.text.trim(),\n ...(s.words\n ? {\n words: s.words.map((w) => ({\n word: w.word.trim(),\n start: Math.round(w.start * 100) / 100,\n end: Math.round(w.end * 100) / 100,\n })),\n }\n : {}),\n })),\n };\n\n if (opts?.output) {\n writeFileSync(opts.output, JSON.stringify(result, null, 2));\n }\n\n return result;\n}\n\nfunction handleTranscribeAudio(\n params: Record<string, unknown>,\n): Promise<unknown> {\n // Support both audioUrl (web agent schema) and filePath (local)\n const filePath = (params.filePath ?? params.audioUrl) as string;\n if (!filePath) throw new Error(\"filePath (or audioUrl) is required\");\n\n const result = transcribeLocalAudioFile(filePath, {\n model: params.model as string | undefined,\n output: params.output as string | undefined,\n });\n\n return Promise.resolve({ success: true, transcript: result });\n}\n\n// ============================================================================\n// Utility tools\n// ============================================================================\n\nasync function handleListCompositions(\n params: Record<string, unknown>,\n): Promise<unknown> {\n const limit = params.limit as number | undefined;\n const compositions = await listCompositions(limit);\n return {\n success: true,\n compositions: compositions.map((c) => ({\n id: c._id,\n title: c.title ?? null,\n description: c.description ?? null,\n duration: c.duration ?? null,\n sceneCount: Array.isArray(c.scenes) ? c.scenes.length : 0,\n updatedAt: c.updatedAt,\n })),\n };\n}\n\nasync function handleTrimSilence(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n // Delegate to the trim-silence module\n const { trimSilenceCommand } = await import(\"../audio/trim-silence.js\");\n // This is a special case — the trim-silence command is complex enough\n // that we reuse it directly. It handles its own output.\n // For tool exec, we call it with json: true to get structured output.\n const fakeOptions = {\n json: true,\n scene: params.sceneId as string | undefined,\n silenceDuration: params.silenceDuration as string | undefined,\n threshold: params.threshold as string | undefined,\n dryRun: params.dryRun as boolean | undefined,\n };\n\n // Capture console output\n const origLog = console.log;\n let captured = \"\";\n console.log = (msg: string) => {\n captured += msg;\n };\n try {\n await trimSilenceCommand(compositionId, fakeOptions);\n } catch {\n // trimSilenceCommand calls process.exit on error — we'll handle gracefully\n } finally {\n console.log = origLog;\n }\n\n // Parse captured JSON output\n try {\n return JSON.parse(captured);\n } catch {\n return { success: true, message: \"Silence trimmed\" };\n }\n}\n\nasync function handleBuildCaptions(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n): Promise<unknown> {\n const { captionsCommand } = await import(\"../audio/captions.js\");\n const fakeOptions = {\n json: true,\n transcript: params.transcript as string[] | undefined,\n accentWords: params.accentWords as string | undefined,\n style: params.style as string | undefined,\n scene: params.sceneId as string | undefined,\n fontSize: params.fontSize as string | undefined,\n accentColor: params.accentColor as string | undefined,\n };\n\n const origLog = console.log;\n let captured = \"\";\n console.log = (msg: string) => {\n captured += msg;\n };\n try {\n await captionsCommand(compositionId, fakeOptions);\n } catch {\n // captionsCommand calls process.exit on error\n } finally {\n console.log = origLog;\n }\n\n try {\n return JSON.parse(captured);\n } catch {\n return { success: true, message: \"Captions built\" };\n }\n}\n\nasync function handleGenerateSubtitles(\n params: Record<string, unknown>,\n compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n if (!compositionId) throw new Error(\"compositionId is required\");\n\n const composition = await getComposition(compositionId);\n if (!composition) throw new Error(\"Composition not found\");\n\n const scenes = (composition.scenes ?? []) as Record<string, unknown>[];\n const targetSceneId = params.sceneId as string | undefined;\n const targetScenes = scenes.filter((scene) => {\n if (\n scene.type !== \"audio_scene\" &&\n scene.type !== \"video_scene\"\n ) {\n return false;\n }\n if (targetSceneId && scene.id !== targetSceneId) return false;\n\n const config = (scene.config ?? {}) as Record<string, unknown>;\n return scene.type === \"audio_scene\"\n ? typeof config.audioUrl === \"string\" && config.audioUrl.length > 0\n : typeof config.url === \"string\" && config.url.length > 0;\n });\n\n if (targetScenes.length === 0) {\n throw new Error(\n targetSceneId\n ? `No transcribable audio/video scene found for ${targetSceneId}`\n : \"No audio/video scenes with media found in composition\",\n );\n }\n\n await mkdir(AUDIO_CACHE_DIR, { recursive: true });\n\n const transcriptionModel = (params.model as string | undefined) ?? \"base\";\n const transcriptPaths: string[] = [];\n const transcribedSceneIds: string[] = [];\n const transcriptsByScene = new Map<string, WhisperResult>();\n\n for (const scene of targetScenes) {\n const config = (scene.config ?? {}) as Record<string, unknown>;\n const mediaUrl =\n scene.type === \"audio_scene\"\n ? (config.audioUrl as string | undefined)\n : (config.url as string | undefined);\n\n if (!mediaUrl) continue;\n\n if (spinner) {\n spinner.text = `Transcribing ${scene.type === \"audio_scene\" ? \"audio\" : \"video\"} scene ${String(scene.id)} locally...`;\n }\n\n const source = await materializeVideoPath(mediaUrl);\n const workDir = await mkdtemp(path.join(tmpdir(), \"program-subtitles-\"));\n try {\n const wavPath = await extractAudioTrack(source.filePath, workDir);\n const transcriptPath = path.join(\n AUDIO_CACHE_DIR,\n `${String(scene.id)}-transcript.json`,\n );\n const transcript = transcribeLocalAudioFile(wavPath, {\n model: transcriptionModel,\n output: transcriptPath,\n });\n transcriptPaths.push(transcriptPath);\n transcribedSceneIds.push(scene.id as string);\n transcriptsByScene.set(scene.id as string, transcript);\n } finally {\n rmSync(workDir, { recursive: true, force: true });\n source.cleanup();\n }\n }\n\n if (transcriptPaths.length === 0) {\n throw new Error(\"No transcripts were generated\");\n }\n\n const captionSceneIds: string[] = [];\n const explicitLayer =\n typeof params.layer === \"number\" ? params.layer : undefined;\n const accentWords = new Set(\n ((params.accentWords as string | undefined) ?? \"ai,program,openclaw,claude,codex\")\n .split(\",\")\n .map((word) => word.trim().toLowerCase())\n .filter(Boolean),\n );\n const style = (params.style as string | undefined) ?? \"tiktok\";\n const fontSize = parseInt((params.fontSize as string | undefined) ?? \"64\", 10);\n const accentColor = (params.accentColor as string | undefined) ?? \"#ff3900\";\n const initialMaxLayer = Math.max(\n 0,\n ...scenes.map((scene) => {\n const order = Number(scene.order ?? 0);\n const metadata = (scene.metadata ?? {}) as Record<string, unknown>;\n const layer = Number(metadata.layer ?? 0);\n return Number.isFinite(order) ? Math.max(order, layer) : layer;\n }),\n );\n\n let nextCaptionLayer = explicitLayer ?? initialMaxLayer + 1;\n\n for (const sourceScene of targetScenes) {\n const transcript = transcriptsByScene.get(sourceScene.id as string);\n if (!transcript) {\n continue;\n }\n\n if (spinner) {\n spinner.text = `Building subtitle overlay for scene ${String(sourceScene.id)}...`;\n }\n\n const sourceMetadata = (sourceScene.metadata ?? {}) as Record<\n string,\n unknown\n >;\n const sourceTitle =\n (sourceMetadata.title as string | undefined) ??\n (sourceScene.id as string);\n const captionTitle =\n targetScenes.length === 1 && typeof params.title === \"string\"\n ? params.title\n : `${sourceTitle} Captions`;\n\n const existingCaptionScene = scenes.find((scene) => {\n if (scene.type !== \"code_scene\") return false;\n const metadata = (scene.metadata ?? {}) as Record<string, unknown>;\n return metadata.sourceSceneId === sourceScene.id;\n });\n\n let captionSceneId =\n existingCaptionScene?.id as string | undefined;\n\n const localEntries = buildCaptionEntries(\n [\n {\n id: sourceScene.id as string,\n type: sourceScene.type as string,\n start: 0,\n end: Number(sourceScene.duration ?? 0),\n duration: Number(sourceScene.duration ?? 0),\n order: Number(sourceScene.order ?? 0),\n },\n ],\n new Map([[sourceScene.id as string, transcript]]),\n accentWords,\n );\n\n const code = generateCaptionCode(localEntries, {\n style,\n fontSize,\n accentColor,\n totalDuration: Number(sourceScene.duration ?? 0),\n });\n\n if (!captionSceneId) {\n captionSceneId = crypto.randomUUID();\n const captionLayer = nextCaptionLayer;\n nextCaptionLayer += 1;\n\n await addScene(compositionId, {\n id: captionSceneId,\n type: \"code_scene\",\n start: Number(sourceScene.start ?? 0),\n end: Number(sourceScene.end ?? 0),\n duration: Number(sourceScene.duration ?? 0),\n order: captionLayer,\n componentId: captionSceneId,\n props: {},\n metadata: {\n title: captionTitle,\n layer: captionLayer,\n snapshot: true,\n role: \"captions\",\n sourceSceneId: sourceScene.id,\n showControls: false,\n visible: true,\n code,\n files: { \"index.tsx\": code },\n entryPoint: \"index.tsx\",\n },\n });\n } else {\n const captionScene = scenes.find((scene) => scene.id === captionSceneId);\n const metadata = (captionScene?.metadata ?? {}) as Record<string, unknown>;\n const currentLayer =\n explicitLayer ??\n (Number(captionScene?.order ?? metadata.layer ?? nextCaptionLayer) ||\n nextCaptionLayer);\n\n if (!existingCaptionScene && explicitLayer === undefined) {\n nextCaptionLayer += 1;\n }\n\n await updateScene(compositionId, captionSceneId, {\n start: Number(sourceScene.start ?? 0),\n end: Number(sourceScene.end ?? 0),\n duration: Number(sourceScene.duration ?? 0),\n order: currentLayer,\n metadata: {\n ...metadata,\n files: { \"index.tsx\": code },\n code,\n entryPoint:\n (metadata.entryPoint as string | undefined) ?? \"index.tsx\",\n role: \"captions\",\n title: captionTitle,\n layer: currentLayer,\n sourceSceneId: sourceScene.id,\n showControls:\n typeof metadata.showControls === \"boolean\"\n ? metadata.showControls\n : false,\n visible:\n typeof metadata.visible === \"boolean\" ? metadata.visible : true,\n },\n });\n }\n\n captionSceneIds.push(captionSceneId);\n }\n\n return {\n success: true,\n captionSceneId: captionSceneIds[0] ?? null,\n captionSceneIds,\n transcribedSceneIds,\n transcriptPaths,\n };\n}\n\n// ============================================================================\n// Model listing tools (hardcoded — models are static)\n// ============================================================================\n\nfunction handleListSpeechModels(): Promise<unknown> {\n return Promise.resolve({\n success: true,\n models: [\n {\n id: \"resemble-ai/chatterbox-turbo\",\n name: \"Chatterbox Turbo\",\n provider: \"resemble-ai\",\n description:\n \"Fast, high-quality TTS with 20+ voice presets and voice cloning\",\n },\n ],\n });\n}\n\nfunction handleListVideoModels(): Promise<unknown> {\n return Promise.resolve({\n success: true,\n models: [\n // Vercel AI Gateway — text-to-video\n {\n id: \"alibaba/wan-v2.6-t2v\",\n name: \"Wan 2.6 Text-to-Video\",\n provider: \"ai-gateway\",\n pricing: \"free\",\n description: \"Free text-to-video, good quality, 2-15s clips\",\n },\n {\n id: \"alibaba/wan-v2.5-t2v-preview\",\n name: \"Wan 2.5 Text-to-Video Preview\",\n provider: \"ai-gateway\",\n pricing: \"free\",\n description: \"Free text-to-video preview model\",\n },\n {\n id: \"klingai/kling-v3.0-t2v\",\n name: \"Kling 3.0 Text-to-Video\",\n provider: \"ai-gateway\",\n pricing: \"$0.17/sec\",\n description: \"High-quality text-to-video with multi-shot support\",\n },\n {\n id: \"google/veo-3.1-generate-001\",\n name: \"Veo 3.1\",\n provider: \"ai-gateway\",\n pricing: \"$0.20/sec\",\n description: \"Google video gen with audio, up to 1080p\",\n },\n {\n id: \"xai/grok-imagine-video\",\n name: \"Grok Imagine Video\",\n provider: \"ai-gateway\",\n pricing: \"$0.05/sec\",\n description: \"Fast video gen with editing, 1-15s, image-to-video\",\n },\n // Vercel AI Gateway — image-to-video\n {\n id: \"alibaba/wan-v2.6-i2v\",\n name: \"Wan 2.6 Image-to-Video\",\n provider: \"ai-gateway\",\n pricing: \"free\",\n description: \"Free image-to-video animation\",\n },\n {\n id: \"alibaba/wan-v2.6-r2v\",\n name: \"Wan 2.6 Reference-to-Video\",\n provider: \"ai-gateway\",\n pricing: \"free\",\n description: \"Free reference-to-video with character consistency\",\n },\n // Replicate\n {\n id: \"minimax/video-01-live\",\n name: \"Minimax Video 01 Live\",\n provider: \"replicate\",\n description: \"High-quality video generation from text prompts\",\n },\n {\n id: \"luma/ray\",\n name: \"Luma Ray\",\n provider: \"replicate\",\n description: \"Video generation with cinematic quality\",\n },\n ],\n });\n}\n\nfunction handleListImageModels(): Promise<unknown> {\n return Promise.resolve({\n success: true,\n models: [\n {\n id: \"black-forest-labs/flux-1.1-pro-ultra\",\n name: \"FLUX 1.1 Pro Ultra\",\n provider: \"black-forest-labs\",\n description: \"High-resolution image generation\",\n },\n {\n id: \"stability-ai/sdxl\",\n name: \"Stable Diffusion XL\",\n provider: \"stability-ai\",\n description: \"Fast, high-quality image generation\",\n },\n ],\n });\n}\n\n// ============================================================================\n// Reference tools\n// ============================================================================\n\nconst REFERENCE_CACHE_DIR = \"/tmp/program-video-cache\";\n\nasync function handleReferenceLayout(\n params: Record<string, unknown>,\n _compositionId: string | undefined,\n spinner: ReturnType<typeof ora> | null,\n): Promise<unknown> {\n const researchItemId = params.researchItemId as string;\n if (!researchItemId) throw new Error(\"researchItemId is required\");\n\n const maxFrames = Math.min(\n (params.maxFrames as number | undefined) ?? 12,\n 12,\n );\n\n // 1. Fetch research item\n if (spinner) spinner.text = \"Fetching research item...\";\n const item = await getResearch(researchItemId);\n if (!item) throw new Error(`Research item not found: ${researchItemId}`);\n\n const analysis = item.metadata?.analysis as VideoAnalysis | undefined;\n\n // 2. Ensure video is cached\n if (spinner) spinner.text = \"Ensuring video is cached...\";\n const videoPath = await ensureVideo(researchItemId, item.sourceUrl);\n const duration = await getVideoDuration(videoPath);\n\n // 3. Determine frame extraction timestamps\n let timestamps: number[];\n if (analysis?.scenes.length) {\n // Extract at scene boundaries — these are the most visually interesting moments\n const sceneTimes = new Set<number>();\n for (const scene of analysis.scenes) {\n sceneTimes.add(Math.max(0.5, scene.startTime));\n // Midpoint of each scene for additional coverage\n const mid = (scene.startTime + scene.endTime) / 2;\n sceneTimes.add(mid);\n }\n timestamps = [...sceneTimes].sort((a, b) => a - b).slice(0, maxFrames);\n } else {\n // Evenly spaced every 2s\n const interval = Math.max(2, duration / maxFrames);\n timestamps = [];\n for (\n let t = 0.5;\n t < duration && timestamps.length < maxFrames;\n t += interval\n ) {\n timestamps.push(Math.round(t * 100) / 100);\n }\n }\n\n if (timestamps.length === 0) {\n timestamps = [0.5];\n }\n\n // 4. Extract frames at timestamps\n const safeId = researchItemId.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n const outDir = path.join(REFERENCE_CACHE_DIR, `${safeId}_reference`);\n await mkdir(outDir, { recursive: true });\n\n const framePaths: string[] = [];\n for (let i = 0; i < timestamps.length; i++) {\n const ts = timestamps[i];\n const outPath = path.join(\n outDir,\n `frame_${String(i).padStart(2, \"0\")}.jpg`,\n );\n\n // Skip if already extracted\n const exists = await access(outPath)\n .then(() => true)\n .catch(() => false);\n if (!exists) {\n if (spinner)\n spinner.text = `Extracting frame ${i + 1}/${timestamps.length} (${ts}s)...`;\n await runShell(\n \"ffmpeg\",\n [\n \"-i\",\n videoPath,\n \"-ss\",\n String(ts),\n \"-frames:v\",\n \"1\",\n \"-vf\",\n \"scale=1024:-1:flags=lanczos\",\n \"-q:v\",\n \"2\",\n \"-y\",\n outPath,\n ],\n { timeout: 15_000 },\n );\n }\n\n // Verify frame was created\n const created = await access(outPath)\n .then(() => true)\n .catch(() => false);\n if (created) framePaths.push(outPath);\n }\n\n // 5. Build layoutHints from analysis\n const layoutHints: Record<string, unknown> = {};\n\n if (analysis) {\n layoutHints.format = analysis.style.format;\n layoutHints.pacing = analysis.style.pacing;\n\n // Collect unique text overlay patterns\n const textPlacements = new Set<string>();\n const transitions = new Set<string>();\n const visualStyles = new Set<string>();\n\n for (const scene of analysis.scenes) {\n for (const overlay of scene.textOverlays) {\n textPlacements.add(overlay);\n }\n if (scene.transition) transitions.add(scene.transition);\n if (scene.visualStyle) visualStyles.add(scene.visualStyle);\n }\n\n if (textPlacements.size > 0)\n layoutHints.textPlacements = [...textPlacements];\n if (transitions.size > 0) layoutHints.transitions = [...transitions];\n if (visualStyles.size > 0) layoutHints.visualStyles = [...visualStyles];\n\n // Extract color palettes and layering from detailed frame descriptions\n if (analysis.detailedVisualTranscript?.length) {\n const colors = new Set<string>();\n const layers = new Set<string>();\n\n for (const frame of analysis.detailedVisualTranscript) {\n for (const color of frame.colorPalette) colors.add(color);\n for (const bg of frame.scene.background) layers.add(bg);\n }\n\n if (colors.size > 0) layoutHints.colorPalette = [...colors].slice(0, 8);\n if (layers.size > 0) layoutHints.layering = [...layers];\n }\n }\n\n // 6. Build analysis summary (avoid sending the full verbose analysis)\n const analysisSummary = analysis\n ? {\n duration: analysis.duration,\n scenes: analysis.scenes.map((s) => ({\n startTime: s.startTime,\n endTime: s.endTime,\n description: s.description,\n textOverlays: s.textOverlays,\n visualStyle: s.visualStyle,\n })),\n style: analysis.style,\n }\n : null;\n\n return {\n success: true,\n researchItemId,\n sourceUrl: item.sourceUrl,\n title: item.title ?? null,\n framePaths,\n timestamps: timestamps.slice(0, framePaths.length),\n analysis: analysisSummary,\n layoutHints,\n instructions:\n \"Use the Read tool on framePaths to view reference frames. \" +\n \"These are for INSPIRATION — create original compositions informed by the visual patterns, not reproductions.\",\n };\n}\n","/**\n * Generate Video Step\n *\n * Mirrors apps/nextjs/src/workflows/agent/steps/generate/generate-video.ts\n * but uses StepDb instead of workflowDb, making it portable across\n * CLI, desktop, and (future) web.\n */\n\nimport { execSync } from \"node:child_process\";\nimport { readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { tmpdir } from \"node:os\";\n\nimport type { InferenceProvider } from \"@program-video/inference\";\nimport { detectProvider, generateVideo } from \"@program-video/inference\";\n\nimport type { ExecutionLog, StepDb } from \"../db\";\n\nexport interface GenerateVideoParams {\n prompt: string;\n model: string;\n compositionId: string;\n provider?: InferenceProvider;\n providerApiKey?: string;\n sceneId?: string;\n start?: number;\n layer?: number;\n title?: string;\n imageUrl?: string;\n duration?: number;\n aspectRatio?: string;\n resolution?: string;\n}\n\nexport interface GenerateVideoResult {\n success: boolean;\n sceneId: string;\n videoUrl: string;\n duration: number;\n model: string;\n provider: string;\n costUsd: number;\n durationMs: number;\n}\n\nfunction probeVideoDurationSeconds(videoPath: string): number | undefined {\n try {\n const out = execSync(\n `ffprobe -v error -show_entries format=duration -of csv=p=0 \"${videoPath}\"`,\n { encoding: \"utf8\", timeout: 5000 },\n ).trim();\n const parsed = parseFloat(out);\n return !isNaN(parsed) && parsed > 0 ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction writeTempVideoFile(bytes: Uint8Array): string {\n const tempPath = join(\n tmpdir(),\n `program-video-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.mp4`,\n );\n writeFileSync(tempPath, Buffer.from(bytes));\n return tempPath;\n}\n\nfunction deriveRequestedVideoDuration(params: GenerateVideoParams): number | undefined {\n return typeof params.duration === \"number\" && params.duration > 0\n ? params.duration\n : undefined;\n}\n\nexport async function generateVideoStep(\n db: StepDb,\n params: GenerateVideoParams,\n): Promise<GenerateVideoResult> {\n \"use step\";\n\n const startTime = Date.now();\n const provider = params.provider ?? detectProvider(params.model);\n\n // Resolve API key from integrations table if not provided\n let apiKey = params.providerApiKey;\n if (!apiKey && db.getIntegrationApiKey) {\n const keyProvider = provider === \"replicate\" ? \"replicate\" : provider;\n apiKey = await db.getIntegrationApiKey(keyProvider);\n }\n\n // Fetch composition for dimensions\n const comp = await db.getComposition(params.compositionId);\n const width = comp.width ?? 1080;\n const height = comp.height ?? 1920;\n\n // Call inference with provider routing.\n // We still probe the actual duration from the output file instead of\n // trusting provider metadata.\n const result = await generateVideo({\n model: params.model,\n input: {\n prompt: params.prompt,\n ...(params.imageUrl && { image_url: params.imageUrl }),\n ...(typeof params.duration === \"number\" &&\n params.duration > 0\n ? { duration: params.duration }\n : {}),\n ...(params.aspectRatio && { aspect_ratio: params.aspectRatio }),\n ...(params.resolution && { resolution: params.resolution }),\n width,\n height,\n },\n provider,\n providerApiKey: apiKey,\n });\n\n const costUsd = Number(result.usage?.cost) || 0;\n\n // Log usage IMMEDIATELY after inference succeeds, BEFORE upload.\n // This mirrors the Next.js step pattern — if upload fails, we still\n // have the cost recorded.\n const logEntry: ExecutionLog = {\n step: \"generateVideo\",\n model: params.model,\n provider,\n input: { prompt: params.prompt, model: params.model, width, height },\n output: {},\n costUsd,\n durationMs: Date.now() - startTime,\n status: \"success\",\n };\n\n // Upload video to storage\n const videoUrl = result.output.url;\n let storedUrl = videoUrl;\n let storageId: string | undefined;\n let probedDuration: number | undefined;\n\n // If the output is a local file path (from AI SDK), read and upload\n if (videoUrl.startsWith(\"/\")) {\n const videoData = readFileSync(videoUrl);\n probedDuration = probeVideoDurationSeconds(videoUrl);\n const stored = await db.storeFile(\n new Uint8Array(videoData),\n result.output.contentType || \"video/mp4\",\n );\n storedUrl = stored.url;\n storageId = stored.storageId;\n } else if (videoUrl.startsWith(\"http\")) {\n // Remote URL from Replicate — download and upload to our storage\n const response = await fetch(videoUrl);\n const arrayBuffer = await response.arrayBuffer();\n const videoBytes = new Uint8Array(arrayBuffer);\n const tempPath = writeTempVideoFile(videoBytes);\n try {\n probedDuration = probeVideoDurationSeconds(tempPath);\n } finally {\n rmSync(tempPath, { force: true });\n }\n const stored = await db.storeFile(\n videoBytes,\n result.output.contentType || \"video/mp4\",\n );\n storedUrl = stored.url;\n storageId = stored.storageId;\n }\n\n // Probe the actual video duration whenever possible rather than trusting\n // provider metadata. Replicate outputs often omit duration, which previously\n // caused us to fall back to 5s and clip longer videos on the timeline.\n const requestedDuration = deriveRequestedVideoDuration(params);\n const videoDuration =\n probedDuration ?? result.output.duration ?? requestedDuration ?? 5;\n const start = params.start ?? 0;\n let sceneId = params.sceneId;\n\n if (sceneId) {\n await db.updateScene(params.compositionId, sceneId, {\n config: {\n url: storedUrl,\n ...(storageId && { storageId }),\n audioUrl: storedUrl,\n },\n duration: videoDuration,\n end: start + videoDuration,\n });\n } else {\n sceneId = await db.addScene(params.compositionId, {\n type: \"video_scene\",\n title: params.title ?? \"Generated Video\",\n start,\n end: start + videoDuration,\n duration: videoDuration,\n order: params.layer ?? 0,\n config: {\n url: storedUrl,\n ...(storageId && { storageId }),\n },\n metadata: {\n prompt: params.prompt,\n model: params.model,\n provider,\n },\n });\n }\n\n // Update log with output and record\n logEntry.output = { sceneId, videoUrl: storedUrl, duration: videoDuration };\n logEntry.durationMs = Date.now() - startTime;\n await db.logExecution(logEntry);\n\n return {\n success: true,\n sceneId: sceneId!,\n videoUrl: storedUrl,\n duration: videoDuration,\n model: params.model,\n provider,\n costUsd,\n durationMs: Date.now() - startTime,\n };\n}\n","/**\n * Generate Speech Step\n *\n * Mirrors apps/nextjs/src/workflows/agent/steps/generate/generate-speech.ts\n * TTS via Replicate (chatterbox, etc.) with storage upload and scene creation.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { DEFAULT_SPEECH_MODEL } from \"@program-video/inference\";\nimport type { StepDb, ExecutionLog } from \"../db\";\n\nexport interface GenerateSpeechParams {\n text: string;\n model?: string;\n compositionId: string;\n providerApiKey?: string;\n voiceClone?: string;\n sceneId?: string;\n start?: number;\n duration?: number;\n layer?: number;\n title?: string;\n}\n\nexport interface GenerateSpeechResult {\n success: boolean;\n sceneId: string;\n audioUrl: string;\n duration: number;\n model: string;\n}\n\nexport async function generateSpeechStep(\n db: StepDb,\n params: GenerateSpeechParams,\n): Promise<GenerateSpeechResult> {\n \"use step\";\n\n const startTime = Date.now();\n const model = params.model ?? DEFAULT_SPEECH_MODEL;\n\n // Resolve API key\n let apiKey = params.providerApiKey;\n if (!apiKey && db.getIntegrationApiKey) {\n apiKey = await db.getIntegrationApiKey(\"replicate\");\n }\n\n // Import and call inference\n const { generateAudio } = await import(\"@program-video/inference\");\n const result = await generateAudio({\n model,\n input: {\n text: params.text,\n ...(params.voiceClone && { reference_audio: params.voiceClone }),\n },\n apiToken: apiKey,\n });\n\n const costUsd = Number(result.usage?.cost) || 0;\n\n // Log usage immediately after inference\n const logEntry: ExecutionLog = {\n step: \"generateSpeech\",\n model,\n provider: \"replicate\",\n input: { text: params.text, model },\n output: {},\n costUsd,\n durationMs: Date.now() - startTime,\n status: \"success\",\n };\n\n // Upload audio to storage\n const audioUrl = result.output.url;\n let storedUrl = audioUrl;\n let storageId: string | undefined;\n\n if (audioUrl.startsWith(\"http\")) {\n const response = await fetch(audioUrl);\n const arrayBuffer = await response.arrayBuffer();\n const stored = await db.storeFile(\n new Uint8Array(arrayBuffer),\n result.output.contentType || \"audio/wav\",\n );\n storedUrl = stored.url;\n storageId = stored.storageId;\n } else if (audioUrl.startsWith(\"/\")) {\n const data = readFileSync(audioUrl);\n const stored = await db.storeFile(\n new Uint8Array(data),\n result.output.contentType || \"audio/wav\",\n );\n storedUrl = stored.url;\n storageId = stored.storageId;\n }\n\n // Estimate duration: ~150 words per minute if not provided\n const audioDuration =\n result.output.duration ?? params.duration ?? (params.text.split(/\\s+/).length / 150) * 60;\n const start = params.start ?? 0;\n let sceneId = params.sceneId;\n\n if (sceneId) {\n await db.updateScene(params.compositionId, sceneId, {\n config: {\n audioUrl: storedUrl,\n ...(storageId && { storageId }),\n },\n duration: audioDuration,\n end: start + audioDuration,\n });\n } else {\n sceneId = await db.addScene(params.compositionId, {\n type: \"audio_scene\",\n title: params.title ?? \"Generated Speech\",\n start,\n end: start + audioDuration,\n duration: audioDuration,\n order: params.layer ?? -1,\n config: {\n audioUrl: storedUrl,\n ...(storageId && { storageId }),\n },\n metadata: {\n text: params.text,\n model,\n },\n });\n }\n\n logEntry.output = { sceneId, audioUrl: storedUrl, duration: audioDuration };\n logEntry.durationMs = Date.now() - startTime;\n await db.logExecution(logEntry);\n\n return {\n success: true,\n sceneId: sceneId!,\n audioUrl: storedUrl,\n duration: audioDuration,\n model,\n };\n}\n","/**\n * Local StepDb implementation backed by local-convex.ts\n *\n * Adapts the CLI's plain HTTP Convex client to the StepDb interface\n * used by shared workflow steps in @program-video/steps.\n *\n * Execution data is persisted to the local Convex database:\n * - Usage events → usageEvent table (cost/billing tracking per inference call)\n * - Step executions → stepExecution table (lifecycle tracking per step invocation)\n *\n * The stepExecution lifecycle (create/update) is managed by the tool handlers\n * in execute.ts. The StepDb.logExecution() method writes the usage event.\n */\n\nimport crypto from \"node:crypto\";\nimport type { StepDb, Composition, ExecutionLog } from \"@program-video/steps\";\nimport {\n getComposition as localGetComposition,\n addScene as localAddScene,\n updateScene as localUpdateScene,\n deleteScene as localDeleteScene,\n generateUploadUrl,\n uploadToStorage,\n getStorageUrl as localGetStorageUrl,\n getIntegrationApiKey as localGetApiKey,\n recordUsage,\n} from \"./local-convex.js\";\n\nexport function createLocalStepDb(): StepDb {\n return {\n async getComposition(id: string): Promise<Composition> {\n const comp = await localGetComposition(id);\n if (!comp) throw new Error(`Composition not found: ${id}`);\n return comp as unknown as Composition;\n },\n\n async addScene(compositionId, scene) {\n const sceneWithId = {\n id: crypto.randomUUID(),\n ...scene,\n };\n return localAddScene(\n compositionId,\n sceneWithId as Record<string, unknown>,\n );\n },\n\n async updateScene(compositionId, sceneId, updates) {\n await localUpdateScene(\n compositionId,\n sceneId,\n updates as Record<string, unknown>,\n );\n },\n\n async deleteScene(compositionId, sceneId) {\n await localDeleteScene(compositionId, sceneId);\n },\n\n async storeFile(data: Uint8Array, contentType: string) {\n const uploadUrl = await generateUploadUrl();\n const storageId = await uploadToStorage(uploadUrl, data, contentType);\n const url = await localGetStorageUrl(storageId);\n if (!url) throw new Error(`Failed to get storage URL for ${storageId}`);\n return { storageId, url };\n },\n\n async getStorageUrl(storageId: string) {\n return localGetStorageUrl(storageId);\n },\n\n async logExecution(entry: ExecutionLog) {\n // Console output for immediate visibility\n const tag = entry.status === \"success\" ? \"[ok]\" : \"[err]\";\n const cost =\n typeof entry.costUsd === \"number\"\n ? `$${entry.costUsd.toFixed(4)}`\n : `$${Number(entry.costUsd) || 0}`;\n console.error(\n `${tag} step=${entry.step} model=${entry.model} provider=${entry.provider} ` +\n `cost=${cost} duration=${entry.durationMs}ms`,\n );\n\n // Persist usage event to Convex usageEvent table\n try {\n await recordUsage({\n model: entry.model,\n provider: entry.provider,\n step: entry.step,\n costUsd: entry.costUsd,\n durationMs: entry.durationMs,\n input: entry.input,\n output: entry.output,\n status: entry.status,\n error: entry.error,\n });\n } catch (err) {\n console.error(\n `[warn] Failed to persist usage event: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n },\n\n async getIntegrationApiKey(provider: string) {\n const key = await localGetApiKey(provider);\n if (!key)\n throw new Error(\n `No API key found for provider \"${provider}\". Add it via the desktop app integrations.`,\n );\n return key;\n },\n };\n}\n","/**\n * Workflow Runtime Initialization\n *\n * Sets up the Vercel Workflow runtime for local step execution.\n *\n * Current state: Steps with \"use step\" directives work as plain async\n * functions — the directive is a no-op string literal without the SWC\n * transform. Observability comes from StepDb.logExecution() which logs\n * to console and (future) local Convex executionLogs table.\n *\n * To fully activate the workflow runtime:\n * 1. Add @workflow/builders to packages/steps\n * 2. Use StandaloneBuilder to compile step files with SWC transform\n * 3. Generate manifest.json mapping step functions to step IDs\n * 4. Import compiled steps instead of source steps\n * 5. Initialize world-local here before calling start()\n *\n * The \"use step\" directives are already in place — once the build step\n * is configured, the runtime will intercept step calls automatically.\n */\n\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { mkdirSync } from \"node:fs\";\n\nconst WORKFLOW_DATA_DIR = join(homedir(), \".program\", \"workflow-data\");\n\nlet _initialized = false;\n\n/**\n * Initialize the workflow runtime environment.\n * Currently sets up env vars and data directory.\n * Full runtime activation requires StandaloneBuilder build step.\n */\nexport function initWorkflowRuntime(): void {\n if (_initialized) return;\n _initialized = true;\n\n // Ensure data directory exists\n mkdirSync(WORKFLOW_DATA_DIR, { recursive: true });\n\n // Set env vars for workflow runtime discovery\n process.env.WORKFLOW_TARGET_WORLD = \"local\";\n process.env.WORKFLOW_LOCAL_DATA_DIR = WORKFLOW_DATA_DIR;\n}\n\n/**\n * Get the workflow data directory path.\n */\nexport function getWorkflowDataDir(): string {\n return WORKFLOW_DATA_DIR;\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { formatTable, outputSuccess } from \"../../lib/output.js\";\n\nexport type ToolListOptions = OutputOptions;\n\ninterface ToolInfo {\n name: string;\n description: string;\n category: string;\n inputs: string[];\n}\n\n/**\n * Available tools — matches the web agent tool registry.\n * Tools marked (local) are CLI-only extensions.\n */\nconst tools: ToolInfo[] = [\n // Composition\n {\n name: \"createComposition\",\n description: \"Create a new composition project. Returns the composition ID.\",\n category: \"composition\",\n inputs: [\"title\", \"description\", \"width\", \"height\", \"fps\"],\n },\n {\n name: \"addScene\",\n description:\n \"Add a scene to the composition. Types: code_scene, video_scene, image_scene, audio_scene.\",\n category: \"composition\",\n inputs: [\"type\", \"title\", \"name\", \"code\", \"url\", \"fileId\", \"duration\", \"start\", \"layer\"],\n },\n {\n name: \"deleteScene\",\n description: \"Delete a specific scene from the composition by its ID\",\n category: \"composition\",\n inputs: [\"sceneId\"],\n },\n {\n name: \"deleteAllScenes\",\n description: \"Delete ALL scenes from the composition to start fresh\",\n category: \"composition\",\n inputs: [],\n },\n {\n name: \"setMetadata\",\n description:\n \"Update composition metadata like title, description, duration, and dimensions\",\n category: \"composition\",\n inputs: [\"title\", \"description\", \"script\", \"duration\", \"fps\", \"width\", \"height\"],\n },\n {\n name: \"updateScene\",\n description:\n \"Update a scene's code, timing, or config. Automatically computes end = start + duration.\",\n category: \"composition\",\n inputs: [\"sceneId\", \"code\", \"title\", \"start\", \"duration\", \"url\", \"config\"],\n },\n // Query\n {\n name: \"assessComposition\",\n description:\n \"Get a lightweight overview of the composition showing all scenes with metadata and status\",\n category: \"query\",\n inputs: [],\n },\n {\n name: \"readComposition\",\n description:\n \"Read the current composition to see its metadata and all scenes\",\n category: \"query\",\n inputs: [],\n },\n // Generation\n {\n name: \"generateSpeech\",\n description:\n \"Generate speech audio from text via TTS and add as audio scene. Uses Replicate chatterbox-turbo.\",\n category: \"generation\",\n inputs: [\"text\", \"voice\", \"voiceClone\", \"sceneId\", \"start\", \"duration\"],\n },\n {\n name: \"extractAudio\",\n description:\n \"Extract a clean mono WAV voice reference from a video clip and return a stored audio URL.\",\n category: \"utility\",\n inputs: [\"videoUrl\", \"sceneId\", \"duration\"],\n },\n {\n name: \"generateVideo\",\n description:\n \"Generate video from text or image via Vercel AI Gateway. Default: alibaba/wan-v2.6-t2v (free).\",\n category: \"generation\",\n inputs: [\"prompt\", \"model\", \"duration\", \"aspectRatio\", \"resolution\", \"imageUrl\", \"sceneId\", \"start\", \"layer\", \"title\"],\n },\n {\n name: \"transcribeAudio\",\n description:\n \"Transcribe audio to text with word-level timestamps using local whisper\",\n category: \"generation\",\n inputs: [\"filePath\", \"model\", \"output\"],\n },\n // Utility\n {\n name: \"listCompositions\",\n description: \"List all compositions in the local database\",\n category: \"utility\",\n inputs: [\"limit\"],\n },\n {\n name: \"trimSilence\",\n description: \"Trim silence from audio scenes in a composition\",\n category: \"utility\",\n inputs: [\"sceneId\", \"silenceDuration\", \"threshold\", \"dryRun\"],\n },\n {\n name: \"buildCaptions\",\n description:\n \"Build caption overlay code from transcripts for composition audio scenes\",\n category: \"utility\",\n inputs: [\"transcript\", \"accentWords\", \"style\", \"sceneId\", \"fontSize\", \"accentColor\"],\n },\n {\n name: \"generateSubtitles\",\n description:\n \"Create or update a captions overlay scene by transcribing composition audio locally and building subtitles in one step.\",\n category: \"utility\",\n inputs: [\"sceneId\", \"style\", \"fontSize\", \"accentColor\", \"accentWords\", \"layer\", \"title\"],\n },\n // Reference\n {\n name: \"referenceLayout\",\n description:\n \"Extract visual reference frames and layout hints from a research item for composition inspiration\",\n category: \"reference\",\n inputs: [\"researchItemId\", \"maxFrames\"],\n },\n];\n\nexport function toolListCommand(options: ToolListOptions): void {\n if (options.json) {\n outputSuccess(\n tools.map((t) => ({\n name: t.name,\n description: t.description,\n category: t.category,\n inputs: t.inputs,\n })),\n options,\n );\n } else {\n console.log(\n `Found ${chalk.cyan(tools.length)} available tool${tools.length === 1 ? \"\" : \"s\"}:\\n`,\n );\n\n const rows = tools.map((t) => [\n t.name,\n t.category,\n t.description.length > 60\n ? t.description.substring(0, 57) + \"...\"\n : t.description,\n ]);\n\n console.log(formatTable([\"Tool\", \"Category\", \"Description\"], rows));\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { formatTable, outputError, outputSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport { getNodeGraph, shortId } from \"../../lib/node-graph.js\";\n\nexport interface NodeListOptions extends OutputOptions {\n scene: string;\n project: string;\n}\n\nexport async function nodeListCommand(options: NodeListOptions): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n if (options.json) {\n outputSuccess({ nodes: graph.nodes, edges: graph.edges }, options);\n return;\n }\n\n // Nodes table\n if (graph.nodes.length === 0) {\n console.log(\"\\nNo nodes in graph.\");\n return;\n }\n\n console.log(\n `\\n${chalk.cyan(String(graph.nodes.length))} node(s) in scene ${chalk.dim(options.scene)}:\\n`,\n );\n\n const nodeRows = graph.nodes.map((n) => {\n const configKeys = Object.keys(n.data.config);\n let configSummary = \"\";\n if (configKeys.length > 0) {\n configSummary = configKeys\n .map((k) => {\n const v = n.data.config[k];\n const s = typeof v === \"string\" ? v : JSON.stringify(v);\n return `${k}=${(s || \"\").toString().slice(0, 20)}`;\n })\n .join(\", \");\n if (configSummary.length > 50) {\n configSummary = configSummary.slice(0, 47) + \"...\";\n }\n } else {\n configSummary = chalk.dim(\"(none)\");\n }\n\n const statusColor =\n n.data.status === \"success\"\n ? chalk.green\n : n.data.status === \"error\"\n ? chalk.red\n : n.data.status === \"running\"\n ? chalk.yellow\n : chalk.dim;\n\n return [\n chalk.cyan(shortId(n.id)),\n n.type,\n n.data.label,\n statusColor(n.data.status),\n configSummary,\n ];\n });\n\n console.log(\n formatTable([\"ID\", \"Type\", \"Label\", \"Status\", \"Config\"], nodeRows, {\n indent: 2,\n }),\n );\n\n // Edges table\n if (graph.edges.length > 0) {\n console.log(\n `\\n${chalk.cyan(String(graph.edges.length))} edge(s):\\n`,\n );\n\n const edgeRows = graph.edges.map((e) => {\n const srcNode = graph.nodes.find((n) => n.id === e.source);\n const tgtNode = graph.nodes.find((n) => n.id === e.target);\n return [\n chalk.cyan(shortId(e.source)),\n srcNode?.data.label ?? \"?\",\n e.sourceHandle ?? chalk.dim(\"-\"),\n chalk.dim(\"->\"),\n chalk.cyan(shortId(e.target)),\n tgtNode?.data.label ?? \"?\",\n e.targetHandle ?? chalk.dim(\"-\"),\n ];\n });\n\n console.log(\n formatTable(\n [\"Source\", \"Name\", \"Handle\", \"\", \"Target\", \"Name\", \"Handle\"],\n edgeRows,\n { indent: 2 },\n ),\n );\n } else {\n console.log(chalk.dim(\"\\n No edges.\"));\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","/**\n * Node Graph — Types, helpers, and execution logic for scene node graphs.\n *\n * CLI-side counterpart to the desktop's scene-node-types.ts and\n * scene-node-executor.ts. No React or @xyflow/react dependency — uses\n * plain interfaces that are structurally compatible with the desktop types.\n */\n\nimport crypto from \"node:crypto\";\n\nimport type { LocalComposition } from \"./local-convex.js\";\nimport { getComposition, updateScene } from \"./local-convex.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport type SceneNodeType =\n | \"prompt\"\n | \"number-value\"\n | \"reference-image\"\n | \"reference-video\"\n | \"extract-audio\"\n | \"model-select\"\n | \"generate-image\"\n | \"generate-video\"\n | \"generate-speech\"\n | \"scene-output\";\n\nexport type SceneNodeStatus = \"idle\" | \"running\" | \"success\" | \"error\";\n\nexport interface SceneNodeData {\n label: string;\n nodeType: SceneNodeType;\n config: Record<string, unknown>;\n status: SceneNodeStatus;\n output?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface NodeGraphNode {\n id: string;\n type: SceneNodeType;\n position: { x: number; y: number };\n data: SceneNodeData;\n}\n\nexport interface NodeGraphEdge {\n id: string;\n source: string;\n target: string;\n sourceHandle?: string;\n targetHandle?: string;\n type?: string;\n animated?: boolean;\n}\n\nexport interface NodeGraph {\n nodes: NodeGraphNode[];\n edges: NodeGraphEdge[];\n lastExecution?: {\n status: SceneNodeStatus;\n startedAt?: number;\n completedAt?: number;\n error?: string;\n nodeOutputs?: Record<string, Record<string, unknown>>;\n };\n}\n\nexport function normalizeSceneOutputMediaEdges(graph: NodeGraph): NodeGraph {\n const sceneOutputIds = new Set(\n graph.nodes.filter((node) => node.type === \"scene-output\").map((node) => node.id),\n );\n\n const edges = graph.edges.map((edge) => {\n if (\n sceneOutputIds.has(edge.target) &&\n (edge.sourceHandle === \"imageUrl\" ||\n edge.sourceHandle === \"videoUrl\" ||\n edge.sourceHandle === \"audioUrl\") &&\n (edge.targetHandle === \"imageUrl\" ||\n edge.targetHandle === \"videoUrl\" ||\n edge.targetHandle === \"audioUrl\")\n ) {\n return {\n ...edge,\n targetHandle: \"media\",\n };\n }\n return edge;\n });\n\n return { ...graph, edges };\n}\n\n// ─── Handle Metadata ─────────────────────────────────────────────────────────\n\nexport interface HandleDef {\n id: string;\n label: string;\n type: \"string\" | \"url\" | \"number\" | \"object\";\n required?: boolean;\n hidden?: boolean;\n}\n\nexport interface SceneNodeMeta {\n type: SceneNodeType;\n label: string;\n description: string;\n inputs: HandleDef[];\n outputs: HandleDef[];\n deletable?: boolean;\n}\n\nexport const SCENE_NODE_TYPES: SceneNodeMeta[] = [\n {\n type: \"prompt\",\n label: \"Prompt\",\n description: \"Text prompt for generation\",\n inputs: [],\n outputs: [{ id: \"prompt\", label: \"Prompt\", type: \"string\" }],\n deletable: true,\n },\n {\n type: \"number-value\",\n label: \"Number\",\n description: \"Numeric value for configurable generation inputs\",\n inputs: [],\n outputs: [{ id: \"duration\", label: \"Value\", type: \"number\" }],\n deletable: true,\n },\n {\n type: \"reference-image\",\n label: \"Reference Image\",\n description: \"Starting image or character reference\",\n inputs: [{ id: \"prompt\", label: \"Prompt\", type: \"string\", hidden: true }],\n outputs: [{ id: \"imageUrl\", label: \"Image URL\", type: \"url\" }],\n deletable: true,\n },\n {\n type: \"reference-video\",\n label: \"Reference Video\",\n description: \"Video reference or reusable clip source\",\n inputs: [],\n outputs: [{ id: \"videoUrl\", label: \"Video URL\", type: \"url\" }],\n deletable: true,\n },\n {\n type: \"extract-audio\",\n label: \"Extract Audio\",\n description: \"Extract a voice reference track from a video clip\",\n inputs: [\n { id: \"videoUrl\", label: \"Video URL\", type: \"url\", required: true },\n ],\n outputs: [\n { id: \"audioUrl\", label: \"Audio URL\", type: \"url\" },\n { id: \"duration\", label: \"Duration\", type: \"number\", hidden: true },\n ],\n deletable: true,\n },\n {\n type: \"model-select\",\n label: \"Model\",\n description: \"Select the AI model and provider\",\n inputs: [],\n outputs: [\n { id: \"model\", label: \"Model ID\", type: \"string\" },\n { id: \"provider\", label: \"Provider\", type: \"string\" },\n ],\n deletable: true,\n },\n {\n type: \"generate-image\",\n label: \"Generate Image\",\n description: \"Generate an image from prompt and reference\",\n inputs: [\n { id: \"prompt\", label: \"Prompt\", type: \"string\", required: true },\n { id: \"imageUrl\", label: \"Reference Image\", type: \"url\" },\n { id: \"model\", label: \"Model\", type: \"string\", required: true },\n ],\n outputs: [{ id: \"imageUrl\", label: \"Image URL\", type: \"url\" }],\n deletable: true,\n },\n {\n type: \"generate-video\",\n label: \"Generate Video\",\n description: \"Generate a video from prompt and optional start image\",\n inputs: [\n { id: \"prompt\", label: \"Prompt\", type: \"string\", required: true },\n { id: \"imageUrl\", label: \"Start Image\", type: \"url\" },\n { id: \"model\", label: \"Model\", type: \"string\", required: true },\n { id: \"duration\", label: \"Duration\", type: \"number\" },\n ],\n outputs: [\n { id: \"videoUrl\", label: \"Video URL\", type: \"url\" },\n { id: \"duration\", label: \"Duration\", type: \"number\" },\n ],\n deletable: true,\n },\n {\n type: \"generate-speech\",\n label: \"Generate Speech\",\n description: \"Generate speech audio from text and an optional voice reference\",\n inputs: [\n { id: \"prompt\", label: \"Script\", type: \"string\", required: true },\n { id: \"audioUrl\", label: \"Voice Reference\", type: \"url\" },\n { id: \"model\", label: \"Model\", type: \"string\", required: true },\n ],\n outputs: [\n { id: \"audioUrl\", label: \"Audio URL\", type: \"url\" },\n { id: \"duration\", label: \"Duration\", type: \"number\", hidden: true },\n ],\n deletable: true,\n },\n {\n type: \"scene-output\",\n label: \"Scene Output\",\n description: \"Writes the generated result back to the scene\",\n inputs: [\n { id: \"media\", label: \"Media\", type: \"url\" },\n { id: \"videoUrl\", label: \"Video URL\", type: \"url\", hidden: true },\n { id: \"imageUrl\", label: \"Image URL\", type: \"url\", hidden: true },\n { id: \"audioUrl\", label: \"Audio URL\", type: \"url\", hidden: true },\n { id: \"duration\", label: \"Duration\", type: \"number\", hidden: true },\n ],\n outputs: [],\n deletable: false,\n },\n];\n\nexport const VALID_ADDABLE_TYPES: SceneNodeType[] = [\n \"prompt\",\n \"number-value\",\n \"reference-image\",\n \"reference-video\",\n \"extract-audio\",\n \"model-select\",\n \"generate-image\",\n \"generate-video\",\n \"generate-speech\",\n];\n\nexport function getSceneNodeMeta(\n type: SceneNodeType,\n): SceneNodeMeta | undefined {\n return SCENE_NODE_TYPES.find((n) => n.type === type);\n}\n\n// ─── ID Helpers ──────────────────────────────────────────────────────────────\n\n/** Generate a short random ID (21 chars, matching nanoid default length). */\nexport function generateId(): string {\n return crypto.randomUUID().replace(/-/g, \"\").slice(0, 21);\n}\n\n/** Shorten an ID for display (first 8 chars). */\nexport function shortId(id: string): string {\n return id.slice(0, 8);\n}\n\n/** Find a node by ID prefix (minimum 4 chars). */\nexport function findNodeByPrefix(\n nodes: NodeGraphNode[],\n prefix: string,\n): NodeGraphNode | undefined {\n if (prefix.length < 4) return undefined;\n const matches = nodes.filter((n) => n.id.startsWith(prefix));\n if (matches.length === 1) return matches[0];\n // Exact match takes priority\n return nodes.find((n) => n.id === prefix);\n}\n\n// ─── Graph Read / Write ──────────────────────────────────────────────────────\n\ninterface SceneWithMetadata {\n id: string;\n metadata?: {\n nodeGraph?: NodeGraph;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport async function getNodeGraph(\n compositionId: string,\n sceneId: string,\n): Promise<{ graph: NodeGraph; composition: LocalComposition }> {\n const comp = await getComposition(compositionId);\n if (!comp) throw new Error(`Composition not found: ${compositionId}`);\n\n const scenes = (comp.scenes ?? []) as SceneWithMetadata[];\n const scene = scenes.find((s) => s.id === sceneId);\n if (!scene) throw new Error(`Scene not found: ${sceneId}`);\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- nodeGraph is typed as `any` in metadata\n let graph = scene.metadata?.nodeGraph as NodeGraph | undefined;\n if (graph) {\n const normalized = normalizeSceneOutputMediaEdges(graph);\n if (normalized !== graph) {\n graph = normalized;\n await saveNodeGraph(compositionId, sceneId, graph);\n }\n }\n\n // Auto-initialize a default graph if none exists (matches desktop createDefaultGraph)\n if (!graph) {\n const sceneType = scene.type as string | undefined;\n if (\n sceneType === \"video_scene\" ||\n sceneType === \"image_scene\" ||\n sceneType === \"audio_scene\"\n ) {\n const genType: SceneNodeType =\n sceneType === \"video_scene\"\n ? \"generate-video\"\n : sceneType === \"image_scene\"\n ? \"generate-image\"\n : \"generate-speech\";\n const outputHandleId =\n sceneType === \"video_scene\"\n ? \"videoUrl\"\n : sceneType === \"image_scene\"\n ? \"imageUrl\"\n : \"audioUrl\";\n\n // Build aspectRatio from composition dimensions\n const dimConfig: Record<string, unknown> = {};\n if (comp.width && comp.height) {\n const gcd = (a: number, b: number): number =>\n b === 0 ? a : gcd(b, a % b);\n const d = gcd(comp.width, comp.height);\n dimConfig.aspectRatio = `${comp.width / d}:${comp.height / d}`;\n }\n\n const genNode = createNode(genType, dimConfig, {\n x: LAYOUT.startX,\n y: LAYOUT.startY + 60,\n });\n if (sceneType === \"audio_scene\") {\n genNode.data.config = {\n ...genNode.data.config,\n model: \"resemble-ai/chatterbox-turbo\",\n provider: \"replicate\",\n };\n }\n const outputNode = createNode(\n \"scene-output\",\n {},\n { x: LAYOUT.startX + LAYOUT.gapX, y: LAYOUT.startY + 60 },\n );\n\n const edges: NodeGraphEdge[] = [\n createEdge(\n genNode.id,\n outputNode.id,\n outputHandleId,\n \"media\",\n ),\n ];\n if (sceneType === \"video_scene\" || sceneType === \"audio_scene\") {\n edges.push(\n createEdge(genNode.id, outputNode.id, \"duration\", \"duration\"),\n );\n }\n\n graph = { nodes: [genNode, outputNode], edges };\n\n // Persist the initialized graph\n await saveNodeGraph(compositionId, sceneId, graph);\n } else {\n throw new Error(\n `Scene \"${sceneId}\" (type: ${sceneType ?? \"unknown\"}) does not support node graphs.`,\n );\n }\n }\n\n return { graph, composition: comp };\n}\n\nexport async function saveNodeGraph(\n compositionId: string,\n sceneId: string,\n graph: NodeGraph,\n): Promise<void> {\n const comp = await getComposition(compositionId);\n if (!comp) throw new Error(`Composition not found: ${compositionId}`);\n\n const scenes = (comp.scenes ?? []) as SceneWithMetadata[];\n const scene = scenes.find((s) => s.id === sceneId);\n if (!scene) throw new Error(`Scene not found: ${sceneId}`);\n\n const existingMetadata = scene.metadata ?? {};\n await updateScene(compositionId, sceneId, {\n metadata: { ...existingMetadata, nodeGraph: graph },\n });\n}\n\n// ─── Node / Edge Factories ───────────────────────────────────────────────────\n\nconst LAYOUT = {\n startX: 50,\n startY: 120,\n gapX: 280,\n rowGapY: 160,\n} as const;\n\nexport function createNode(\n type: SceneNodeType,\n config: Record<string, unknown> = {},\n position?: { x: number; y: number },\n): NodeGraphNode {\n const meta = getSceneNodeMeta(type);\n return {\n id: generateId(),\n type,\n position: position ?? { x: LAYOUT.startX, y: LAYOUT.startY },\n data: {\n label: meta?.label ?? type,\n nodeType: type,\n config,\n status: \"idle\",\n },\n };\n}\n\n/**\n * Auto-position a new node based on its type and existing nodes.\n *\n * Lays out nodes left-to-right by pipeline stage:\n * Col 0: Input nodes (prompt, reference-image, model-select)\n * Col 1: Generation nodes (generate-image, generate-video)\n * Col 2: Output node (scene-output)\n *\n * Multiple nodes in the same column are stacked vertically.\n */\nexport function autoPosition(\n type: SceneNodeType,\n existingNodes: NodeGraphNode[],\n): { x: number; y: number } {\n const col = getColumnForType(type);\n const x = LAYOUT.startX + col * LAYOUT.gapX;\n\n // Count existing nodes in the same column to stack vertically\n const sameColCount = existingNodes.filter(\n (n) => getColumnForType(n.type) === col,\n ).length;\n const y = LAYOUT.startY + sameColCount * LAYOUT.rowGapY;\n\n return { x, y };\n}\n\nfunction getColumnForType(type: SceneNodeType): number {\n switch (type) {\n case \"prompt\":\n case \"reference-image\":\n case \"reference-video\":\n case \"extract-audio\":\n case \"model-select\":\n return 0;\n case \"generate-image\":\n return 1;\n case \"generate-video\":\n case \"generate-speech\":\n return 2;\n case \"scene-output\":\n return 3;\n default:\n return 1;\n }\n}\n\n// ─── Node Sizing (must match desktop rendered sizes) ─────────────────────────\n\n/** Base widths by node type (px). */\nconst NODE_WIDTHS: Record<string, number> = {\n prompt: 192, // w-48\n \"reference-image\": 176, // w-44\n \"reference-video\": 176, // w-44\n \"extract-audio\": 176, // w-44\n \"model-select\": 176, // w-44\n \"generate-image\": 176, // w-44\n \"generate-video\": 176, // w-44\n \"generate-speech\": 176, // w-44\n \"scene-output\": 176, // w-44\n};\n\n/** Base heights — used when no aspect ratio is set. */\nconst NODE_HEIGHTS: Record<string, number> = {\n prompt: 140,\n \"reference-image\": 120,\n \"reference-video\": 120,\n \"extract-audio\": 140,\n \"model-select\": 100,\n \"generate-image\": 200,\n \"generate-video\": 200,\n \"generate-speech\": 180,\n \"scene-output\": 200,\n};\n\n/**\n * Compute actual rendered height for a node.\n *\n * Uses the `measured` dimensions from React Flow if available (most accurate),\n * otherwise estimates based on content and aspect ratio.\n */\nfunction getNodeHeight(node: NodeGraphNode): number {\n const base = NODE_HEIGHTS[node.type] ?? 160;\n\n // Prompt nodes can grow after text edits before React Flow has written back\n // a fresh measured height, so use the larger of measured vs estimated size.\n if (node.type === \"prompt\") {\n const prompt = (node.data.config.prompt as string | undefined) ?? \"\";\n const measured = (node as { measured?: { height?: number } }).measured;\n const measuredHeight =\n measured?.height && measured.height > 0 ? measured.height : 0;\n const nodeWidth = 208; // `w-52` in PromptNode\n const innerWidth = nodeWidth - 16; // textarea horizontal padding\n const charsPerLine = Math.max(14, Math.floor(innerWidth / 6.1));\n const wrappedLines = prompt\n .split(\"\\n\")\n .map((segment) =>\n Math.max(1, Math.ceil(segment.length / Math.max(1, charsPerLine))),\n )\n .reduce((sum, lines) => sum + lines, 0);\n const estimatedHeight = Math.round(Math.max(3, wrappedLines) * 18 + 72);\n return Math.max(base, measuredHeight, estimatedHeight);\n }\n\n // Prefer React Flow's measured height if the UI has rendered the node.\n const measured = (node as { measured?: { height?: number } }).measured;\n if (measured?.height && measured.height > 0) return measured.height;\n\n if (\n node.type === \"extract-audio\" ||\n node.type === \"generate-speech\"\n ) {\n const hasAudioOutput = typeof node.data.output?.audioUrl === \"string\";\n if (hasAudioOutput) {\n return Math.max(base, 220);\n }\n }\n\n // Generate/output nodes: scale height for portrait aspect ratios\n const aspectRatio = node.data.config.aspectRatio as string | undefined;\n if (!aspectRatio) return base;\n\n const parts = aspectRatio.split(\":\");\n if (parts.length !== 2) return base;\n const w = parseFloat(parts[0] ?? \"1\");\n const h = parseFloat(parts[1] ?? \"1\");\n if (w <= 0 || h <= 0) return base;\n\n const nodeWidth = NODE_WIDTHS[node.type] ?? 176;\n if (h > w) {\n return Math.round(nodeWidth * (h / w));\n }\n return base;\n}\n\n/**\n * Auto-layout all nodes using edge-aware column assignment.\n * Called explicitly by `program node autolayout` — never runs automatically.\n *\n * Instead of grouping by type, computes the longest-path depth from source\n * nodes (nodes with no incoming edges). This means generate-image and\n * generate-video end up in different columns when one feeds into the other:\n *\n * Prompt → Generate Image → Generate Video → Scene Output\n * col 0 col 1 col 2 col 3\n *\n * Nodes at the same depth share a column and are stacked vertically\n * with height-aware spacing (accounts for aspect ratio).\n */\nexport function autoLayoutNodes(\n nodes: NodeGraphNode[],\n edges: NodeGraphEdge[],\n): NodeGraphNode[] {\n if (nodes.length === 0) return nodes;\n\n const GAP_X = 260;\n const GAP_Y = 40;\n const START_X = 50;\n\n // Build adjacency: for each node, which nodes does it feed into?\n const outgoing = new Map<string, string[]>();\n const incoming = new Map<string, string[]>();\n for (const n of nodes) {\n outgoing.set(n.id, []);\n incoming.set(n.id, []);\n }\n for (const e of edges) {\n outgoing.get(e.source)?.push(e.target);\n incoming.get(e.source); // ensure exists\n incoming.get(e.target)?.push(e.source);\n }\n\n // Compute depth (column) via longest path from any source node.\n // This ensures A→B always puts B in a later column than A.\n const depth = new Map<string, number>();\n for (const n of nodes) depth.set(n.id, 0);\n\n // Topological BFS to compute longest path\n const inDeg = new Map<string, number>();\n for (const n of nodes) {\n inDeg.set(n.id, (incoming.get(n.id) ?? []).length);\n }\n const queue: string[] = [];\n for (const [id, deg] of inDeg) {\n if (deg === 0) queue.push(id);\n }\n while (queue.length > 0) {\n const id = queue.shift();\n if (!id) continue;\n const d = depth.get(id) ?? 0;\n for (const target of outgoing.get(id) ?? []) {\n const newDepth = d + 1;\n if (newDepth > (depth.get(target) ?? 0)) {\n depth.set(target, newDepth);\n }\n const newDeg = (inDeg.get(target) ?? 1) - 1;\n inDeg.set(target, newDeg);\n if (newDeg === 0) queue.push(target);\n }\n }\n\n // Heuristic: if generate-image and generate-video share the same depth,\n // push generate-video (and everything downstream of it) one column right.\n // In i2v pipelines, image gen conceptually precedes video gen even when\n // no direct edge connects them.\n const genImageNodes = nodes.filter((n) => n.type === \"generate-image\");\n const genVideoNodes = nodes.filter((n) => n.type === \"generate-video\");\n if (genImageNodes.length > 0 && genVideoNodes.length > 0) {\n const imgDepth = depth.get(genImageNodes[0]?.id ?? \"\") ?? 0;\n const vidDepth = depth.get(genVideoNodes[0]?.id ?? \"\") ?? 0;\n if (vidDepth <= imgDepth) {\n // Shift generate-video and all its downstream nodes\n const toShift = new Set<string>();\n const shiftQueue = genVideoNodes.map((n) => n.id);\n while (shiftQueue.length > 0) {\n const id = shiftQueue.shift();\n if (!id) continue;\n if (toShift.has(id)) continue;\n // Don't shift generate-image nodes\n const nd = nodes.find((n) => n.id === id);\n if (nd?.type === \"generate-image\") continue;\n toShift.add(id);\n for (const target of outgoing.get(id) ?? []) {\n shiftQueue.push(target);\n }\n }\n for (const id of toShift) {\n depth.set(id, (depth.get(id) ?? 0) + 1);\n }\n }\n }\n\n // Push input nodes (no incoming edges) to target_depth - 1 so they align\n // with sibling inputs to the same target node.\n const inputTypes = new Set([\n \"prompt\",\n \"reference-image\",\n \"reference-video\",\n \"extract-audio\",\n \"model-select\",\n ]);\n for (const node of nodes) {\n if (!inputTypes.has(node.type)) continue;\n const targets = outgoing.get(node.id) ?? [];\n if (targets.length === 0) continue;\n const targetDepths = targets.map((t) => depth.get(t) ?? 0);\n const maxTargetDepth = Math.max(...targetDepths);\n const desiredDepth = Math.max(0, maxTargetDepth - 1);\n if (desiredDepth > (depth.get(node.id) ?? 0)) {\n depth.set(node.id, desiredDepth);\n }\n }\n\n // Group by depth column\n const columns = new Map<number, NodeGraphNode[]>();\n for (const node of nodes) {\n const col = depth.get(node.id) ?? 0;\n if (!columns.has(col)) columns.set(col, []);\n columns.get(col)?.push(node);\n }\n\n // Sort within each column: prompts first, then ref-image, model, gen-image, gen-video, output\n const typeOrder: Record<string, number> = {\n prompt: 0,\n \"reference-image\": 1,\n \"reference-video\": 2,\n \"extract-audio\": 3,\n \"model-select\": 4,\n \"generate-image\": 5,\n \"generate-video\": 6,\n \"generate-speech\": 7,\n \"scene-output\": 8,\n };\n for (const [, colNodes] of columns) {\n colNodes.sort(\n (a, b) => (typeOrder[a.type] ?? 3) - (typeOrder[b.type] ?? 3),\n );\n }\n\n // Compute column heights\n const colHeights = new Map<number, number>();\n for (const [col, colNodes] of columns) {\n let totalH = 0;\n for (let i = 0; i < colNodes.length; i++) {\n const colNode = colNodes[i];\n if (colNode) totalH += getNodeHeight(colNode);\n if (i < colNodes.length - 1) totalH += GAP_Y;\n }\n colHeights.set(col, totalH);\n }\n\n const maxColHeight = Math.max(...colHeights.values());\n const centerY = maxColHeight / 2;\n\n // Assign positions — each column centered vertically\n const result: NodeGraphNode[] = [];\n for (const [col, colNodes] of [...columns.entries()].sort(\n ([a], [b]) => a - b,\n )) {\n const colHeight = colHeights.get(col) ?? 0;\n let y = centerY - colHeight / 2;\n\n for (const node of colNodes) {\n const h = getNodeHeight(node);\n result.push({\n ...node,\n position: {\n x: START_X + col * GAP_X,\n y: Math.round(y),\n },\n });\n y += h + GAP_Y;\n }\n }\n\n // Safety: include any missed nodes\n for (const node of nodes) {\n if (!result.find((n) => n.id === node.id)) {\n result.push(node);\n }\n }\n\n return result;\n}\n\nexport function createEdge(\n sourceId: string,\n targetId: string,\n sourceHandle?: string,\n targetHandle?: string,\n): NodeGraphEdge {\n return {\n id: generateId(),\n source: sourceId,\n target: targetId,\n sourceHandle,\n targetHandle,\n type: \"default\",\n animated: false,\n };\n}\n\n// ─── Topological Sort ────────────────────────────────────────────────────────\n\n/**\n * Kahn's algorithm — returns node IDs in execution order.\n * Only includes executable nodes (generate-image, generate-video, scene-output).\n */\nexport function topologicalSort(\n nodes: NodeGraphNode[],\n edges: NodeGraphEdge[],\n): string[] {\n const executableTypes = new Set([\n \"generate-image\",\n \"generate-video\",\n \"extract-audio\",\n \"generate-speech\",\n \"scene-output\",\n ]);\n const execNodes = nodes.filter((n) => executableTypes.has(n.type));\n\n const inDegree = new Map<string, number>();\n const adjacency = new Map<string, string[]>();\n\n for (const n of execNodes) {\n inDegree.set(n.id, 0);\n adjacency.set(n.id, []);\n }\n\n for (const edge of edges) {\n if (inDegree.has(edge.source) && inDegree.has(edge.target)) {\n adjacency.get(edge.source)?.push(edge.target);\n inDegree.set(edge.target, (inDegree.get(edge.target) ?? 0) + 1);\n }\n // Source is a static node (prompt, model, ref-image) — doesn't add in-degree\n }\n\n const queue: string[] = [];\n for (const [id, deg] of inDegree) {\n if (deg === 0) queue.push(id);\n }\n\n const sorted: string[] = [];\n while (queue.length > 0) {\n const id = queue.shift();\n if (!id) break;\n sorted.push(id);\n for (const neighbor of adjacency.get(id) ?? []) {\n const newDeg = (inDegree.get(neighbor) ?? 1) - 1;\n inDegree.set(neighbor, newDeg);\n if (newDeg === 0) queue.push(neighbor);\n }\n }\n\n return sorted;\n}\n\n// ─── Input Resolution ────────────────────────────────────────────────────────\n\n/**\n * Resolve inputs for a node by walking upstream edges.\n * Falls back to the node's own config if no upstream edge provides a value.\n */\nexport function resolveInputsForNode(\n nodeId: string,\n nodes: NodeGraphNode[],\n edges: NodeGraphEdge[],\n): Record<string, unknown> {\n const inputs: Record<string, unknown> = {};\n\n for (const edge of edges.filter((e) => e.target === nodeId)) {\n const source = nodes.find((n) => n.id === edge.source);\n if (!source) continue;\n\n const handleId = edge.targetHandle ?? edge.sourceHandle;\n if (!handleId) continue;\n\n switch (source.type) {\n case \"prompt\":\n if (handleId === \"prompt\")\n inputs.prompt = source.data.config.prompt ?? \"\";\n break;\n case \"number-value\":\n if (handleId === \"duration\") {\n inputs.duration = source.data.config.value;\n }\n break;\n case \"reference-image\":\n if (handleId === \"imageUrl\")\n inputs.imageUrl = source.data.config.imageUrl ?? \"\";\n break;\n case \"reference-video\":\n if (handleId === \"videoUrl\")\n inputs.videoUrl = source.data.config.videoUrl ?? \"\";\n break;\n case \"extract-audio\":\n case \"generate-speech\":\n if (source.data.output) {\n if (handleId === \"audioUrl\" || edge.sourceHandle === \"audioUrl\") {\n inputs.audioUrl = source.data.output.audioUrl;\n }\n if (handleId === \"duration\" || edge.sourceHandle === \"duration\") {\n inputs.duration = source.data.output.duration;\n }\n }\n break;\n case \"model-select\":\n if (handleId === \"model\" || edge.targetHandle === \"model\") {\n inputs.model = source.data.config.model ?? \"\";\n }\n if (handleId === \"provider\") {\n inputs.provider = source.data.config.provider ?? \"\";\n }\n break;\n case \"generate-image\":\n case \"generate-video\":\n if (source.data.output) {\n if (\n handleId === \"imageUrl\" ||\n (handleId === \"media\" && edge.sourceHandle === \"imageUrl\") ||\n edge.sourceHandle === \"imageUrl\"\n ) {\n inputs.imageUrl = source.data.output.imageUrl;\n }\n if (\n handleId === \"videoUrl\" ||\n (handleId === \"media\" && edge.sourceHandle === \"videoUrl\") ||\n edge.sourceHandle === \"videoUrl\"\n ) {\n inputs.videoUrl = source.data.output.videoUrl;\n }\n if (\n handleId === \"duration\" ||\n edge.sourceHandle === \"duration\" ||\n (handleId === \"media\" &&\n edge.sourceHandle === \"videoUrl\" &&\n typeof source.data.output.duration === \"number\")\n ) {\n inputs.duration = source.data.output.duration;\n }\n }\n break;\n }\n }\n\n // Fall back to node's own config for missing inputs\n const node = nodes.find((n) => n.id === nodeId);\n if (\n node &&\n (node.type === \"generate-video\" ||\n node.type === \"generate-image\" ||\n node.type === \"generate-speech\" ||\n node.type === \"extract-audio\")\n ) {\n if (!inputs.prompt && node.data.config.prompt)\n inputs.prompt = node.data.config.prompt;\n if (!inputs.model && node.data.config.model)\n inputs.model = node.data.config.model;\n if (!inputs.provider && node.data.config.provider)\n inputs.provider = node.data.config.provider;\n if (!inputs.imageUrl && node.data.config.imageUrl)\n inputs.imageUrl = node.data.config.imageUrl;\n if (!inputs.videoUrl && node.data.config.videoUrl)\n inputs.videoUrl = node.data.config.videoUrl;\n if (!inputs.audioUrl && node.data.config.audioUrl)\n inputs.audioUrl = node.data.config.audioUrl;\n if (\n (node.type === \"generate-video\" ||\n node.type === \"generate-speech\" ||\n node.type === \"extract-audio\") &&\n typeof inputs.duration !== \"number\" &&\n typeof node.data.config.duration === \"number\"\n ) {\n inputs.duration = node.data.config.duration;\n }\n }\n\n return inputs;\n}\n\n// ─── Validation ──────────────────────────────────────────────────────────────\n\nexport interface ValidationResult {\n valid: boolean;\n warnings: string[];\n}\n\nfunction findConnectedToOutput(\n nodes: NodeGraphNode[],\n edges: NodeGraphEdge[],\n): Set<string> {\n const outputNode = nodes.find((node) => node.type === \"scene-output\");\n const connected = new Set<string>();\n if (!outputNode) return connected;\n\n const queue = [outputNode.id];\n while (queue.length > 0) {\n const id = queue.shift();\n if (!id || connected.has(id)) continue;\n connected.add(id);\n for (const edge of edges) {\n if (edge.target === id) queue.push(edge.source);\n }\n }\n\n return connected;\n}\n\nexport function validateGraph(\n nodes: NodeGraphNode[],\n edges: NodeGraphEdge[],\n): ValidationResult {\n const warnings: string[] = [];\n\n const connected = findConnectedToOutput(nodes, edges);\n const generateNodes = nodes.filter(\n (n) =>\n connected.has(n.id) &&\n (n.type === \"generate-video\" ||\n n.type === \"generate-image\" ||\n n.type === \"generate-speech\" ||\n n.type === \"extract-audio\"),\n );\n if (generateNodes.length === 0) {\n warnings.push(\"No generation node in graph\");\n return { valid: false, warnings };\n }\n\n for (const genNode of generateNodes) {\n const label = genNode.data.label || \"Generate\";\n if (genNode.type === \"extract-audio\") {\n const hasVideoEdge = edges.some(\n (e) => e.target === genNode.id && e.targetHandle === \"videoUrl\",\n );\n const videoVal = genNode.data.config.videoUrl as string | undefined;\n const hasVideoConfig = !!videoVal?.trim();\n if (!hasVideoEdge && !hasVideoConfig) {\n warnings.push(`${label} needs a video`);\n }\n continue;\n }\n\n const hasPromptEdge = edges.some(\n (e) => e.target === genNode.id && e.targetHandle === \"prompt\",\n );\n const promptVal = genNode.data.config.prompt as string | undefined;\n const hasPromptConfig = !!promptVal?.trim();\n if (!hasPromptEdge && !hasPromptConfig) {\n warnings.push(\n genNode.type === \"generate-speech\"\n ? `${label} needs a script`\n : `${label} needs a prompt`,\n );\n }\n\n const hasModelEdge = edges.some(\n (e) => e.target === genNode.id && e.targetHandle === \"model\",\n );\n const hasModelConfig = !!(genNode.data.config.model as string);\n if (!hasModelEdge && !hasModelConfig) {\n warnings.push(`${label} needs a model`);\n }\n }\n\n for (const pn of nodes.filter((n) => n.type === \"prompt\")) {\n const pnPrompt = pn.data.config.prompt as string | undefined;\n if (!pnPrompt?.trim()) {\n warnings.push(\"Prompt node is empty\");\n }\n }\n\n for (const mn of nodes.filter((n) => n.type === \"model-select\")) {\n if (!(mn.data.config.model as string)) {\n warnings.push(\"Model node has no selection\");\n }\n }\n\n const outputNode = nodes.find((n) => n.type === \"scene-output\");\n if (outputNode) {\n if (!edges.some((e) => e.target === outputNode.id)) {\n warnings.push(\"Scene output is not connected\");\n }\n }\n\n return { valid: warnings.length === 0, warnings };\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError, outputSuccess, formatSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n createNode,\n autoPosition,\n shortId,\n VALID_ADDABLE_TYPES,\n} from \"../../lib/node-graph.js\";\nimport type { SceneNodeType } from \"../../lib/node-graph.js\";\n\nexport interface NodeAddOptions extends OutputOptions {\n scene: string;\n project: string;\n config?: string;\n}\n\nexport async function nodeAddCommand(\n type: string,\n options: NodeAddOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!VALID_ADDABLE_TYPES.includes(type as SceneNodeType)) {\n outputError(\n `Invalid node type \"${type}\". Valid types: ${VALID_ADDABLE_TYPES.join(\", \")}`,\n options,\n );\n process.exit(1);\n }\n\n if (type === \"scene-output\") {\n outputError(\n \"Cannot add scene-output node — each graph has exactly one.\",\n options,\n );\n process.exit(1);\n }\n\n let config: Record<string, unknown> = {};\n if (options.config) {\n try {\n config = JSON.parse(options.config) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --config\", options);\n process.exit(1);\n }\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph, composition } = await getNodeGraph(options.project, options.scene);\n\n // Auto-inject aspectRatio from composition dimensions into generate nodes\n // unless the caller has already specified it in --config JSON.\n if (type === \"generate-image\" || type === \"generate-video\") {\n if (config.aspectRatio === undefined && composition.width && composition.height) {\n const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n const d = gcd(composition.width, composition.height);\n config.aspectRatio = `${composition.width / d}:${composition.height / d}`;\n }\n }\n\n const position = autoPosition(type as SceneNodeType, graph.nodes);\n const node = createNode(type as SceneNodeType, config, position);\n graph.nodes.push(node);\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n { nodeId: node.id, type: node.type, label: node.data.label, position },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Added ${chalk.cyan(type)} node ${chalk.dim(shortId(node.id))} (${node.data.label})`,\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError, outputSuccess, formatSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n findNodeByPrefix,\n shortId,\n} from \"../../lib/node-graph.js\";\n\nexport interface NodeRemoveOptions extends OutputOptions {\n scene: string;\n project: string;\n}\n\nexport async function nodeRemoveCommand(\n nodeId: string,\n options: NodeRemoveOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n const node = findNodeByPrefix(graph.nodes, nodeId);\n if (!node) {\n outputError(\n `Node not found matching \"${nodeId}\". Run 'program node list' to see node IDs.`,\n options,\n );\n process.exit(1);\n }\n\n if (node.type === \"scene-output\") {\n outputError(\"Cannot remove the scene-output node.\", options);\n process.exit(1);\n }\n\n const fullId = node.id;\n const label = node.data.label;\n\n // Remove the node\n graph.nodes = graph.nodes.filter((n) => n.id !== fullId);\n\n // Remove all connected edges\n const removedEdges = graph.edges.filter(\n (e) => e.source === fullId || e.target === fullId,\n );\n graph.edges = graph.edges.filter(\n (e) => e.source !== fullId && e.target !== fullId,\n );\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n {\n removedNodeId: fullId,\n label,\n removedEdges: removedEdges.length,\n },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Removed ${chalk.cyan(node.type)} node ${chalk.dim(shortId(fullId))} (${label})` +\n (removedEdges.length > 0\n ? ` and ${removedEdges.length} connected edge(s)`\n : \"\"),\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError, outputSuccess, formatSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n findNodeByPrefix,\n createEdge,\n getSceneNodeMeta,\n shortId,\n} from \"../../lib/node-graph.js\";\n\nexport interface NodeConnectOptions extends OutputOptions {\n scene: string;\n project: string;\n sourceHandle: string;\n targetHandle: string;\n}\n\nexport async function nodeConnectCommand(\n sourceId: string,\n targetId: string,\n options: NodeConnectOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!options.sourceHandle || !options.targetHandle) {\n outputError(\"--source-handle and --target-handle are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n // Resolve nodes by prefix\n const sourceNode = findNodeByPrefix(graph.nodes, sourceId);\n if (!sourceNode) {\n outputError(\n `Source node not found matching \"${sourceId}\".`,\n options,\n );\n process.exit(1);\n }\n\n const targetNode = findNodeByPrefix(graph.nodes, targetId);\n if (!targetNode) {\n outputError(\n `Target node not found matching \"${targetId}\".`,\n options,\n );\n process.exit(1);\n }\n\n // Validate handle names exist on the respective nodes\n const sourceMeta = getSceneNodeMeta(sourceNode.type);\n const targetMeta = getSceneNodeMeta(targetNode.type);\n\n if (sourceMeta) {\n const validOutputs = sourceMeta.outputs.map((o) => o.id);\n if (!validOutputs.includes(options.sourceHandle)) {\n outputError(\n `\"${options.sourceHandle}\" is not a valid output handle on ${sourceNode.type}. Valid: ${validOutputs.join(\", \")}`,\n options,\n );\n process.exit(1);\n }\n }\n\n if (targetMeta) {\n const validInputs = targetMeta.inputs.map((i) => i.id);\n if (!validInputs.includes(options.targetHandle)) {\n outputError(\n `\"${options.targetHandle}\" is not a valid input handle on ${targetNode.type}. Valid: ${validInputs.join(\", \")}`,\n options,\n );\n process.exit(1);\n }\n }\n\n // Check for duplicate edges\n const duplicate = graph.edges.find(\n (e) =>\n e.source === sourceNode.id &&\n e.target === targetNode.id &&\n e.sourceHandle === options.sourceHandle &&\n e.targetHandle === options.targetHandle,\n );\n if (duplicate) {\n outputError(\"This exact connection already exists.\", options);\n process.exit(1);\n }\n\n const edge = createEdge(\n sourceNode.id,\n targetNode.id,\n options.sourceHandle,\n options.targetHandle,\n );\n graph.edges.push(edge);\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n {\n edgeId: edge.id,\n source: sourceNode.id,\n target: targetNode.id,\n sourceHandle: options.sourceHandle,\n targetHandle: options.targetHandle,\n },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Connected ${chalk.cyan(sourceNode.data.label)} (${chalk.dim(shortId(sourceNode.id))}) ` +\n `${chalk.dim(options.sourceHandle)} -> ` +\n `${chalk.dim(options.targetHandle)} ` +\n `${chalk.cyan(targetNode.data.label)} (${chalk.dim(shortId(targetNode.id))})`,\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError, outputSuccess, formatSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n findNodeByPrefix,\n shortId,\n} from \"../../lib/node-graph.js\";\n\nexport interface NodeDisconnectOptions extends OutputOptions {\n scene: string;\n project: string;\n sourceHandle?: string;\n targetHandle?: string;\n all?: boolean;\n}\n\n/**\n * Disconnect edges between two nodes, or remove all edges from a single node.\n *\n * Usage:\n * program node disconnect <sourceId> <targetId> --scene X --project Y\n * program node disconnect <sourceId> <targetId> --source-handle prompt --target-handle prompt\n * program node disconnect <nodeId> --all --scene X --project Y (removes all edges touching nodeId)\n */\nexport async function nodeDisconnectCommand(\n sourceId: string,\n targetId: string | undefined,\n options: NodeDisconnectOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n const sourceNode = findNodeByPrefix(graph.nodes, sourceId);\n if (!sourceNode) {\n outputError(`Node not found matching \"${sourceId}\". Run 'program node list' to see node IDs.`, options);\n process.exit(1);\n }\n\n // --all mode: remove every edge touching this node\n if (options.all) {\n const removed = graph.edges.filter(\n (e) => e.source === sourceNode.id || e.target === sourceNode.id,\n );\n if (removed.length === 0) {\n outputError(`No edges found on node ${shortId(sourceNode.id)}.`, options);\n process.exit(1);\n }\n graph.edges = graph.edges.filter(\n (e) => e.source !== sourceNode.id && e.target !== sourceNode.id,\n );\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess({ removedEdges: removed.length, nodeId: sourceNode.id }, options);\n } else {\n console.log(\n formatSuccess(\n `Removed ${removed.length} edge(s) from ${chalk.cyan(sourceNode.data.label)} (${chalk.dim(shortId(sourceNode.id))})`,\n ),\n );\n }\n return;\n }\n\n // Two-node mode: remove edges between source and target\n if (!targetId) {\n outputError(\"Provide a target node ID, or use --all to remove all edges from a node.\", options);\n process.exit(1);\n }\n\n const targetNode = findNodeByPrefix(graph.nodes, targetId);\n if (!targetNode) {\n outputError(`Node not found matching \"${targetId}\". Run 'program node list' to see node IDs.`, options);\n process.exit(1);\n }\n\n const edgesToRemove = graph.edges.filter((e) => {\n const matchesDirection =\n (e.source === sourceNode.id && e.target === targetNode.id) ||\n (e.source === targetNode.id && e.target === sourceNode.id);\n if (!matchesDirection) return false;\n if (options.sourceHandle && e.sourceHandle !== options.sourceHandle) return false;\n if (options.targetHandle && e.targetHandle !== options.targetHandle) return false;\n return true;\n });\n\n if (edgesToRemove.length === 0) {\n outputError(\n `No edges found between ${shortId(sourceNode.id)} and ${shortId(targetNode.id)}.`,\n options,\n );\n process.exit(1);\n }\n\n const removeIds = new Set(edgesToRemove.map((e) => e.id));\n graph.edges = graph.edges.filter((e) => !removeIds.has(e.id));\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n {\n removedEdges: edgesToRemove.length,\n source: sourceNode.id,\n target: targetNode.id,\n },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Removed ${edgesToRemove.length} edge(s) between ` +\n `${chalk.cyan(sourceNode.data.label)} (${chalk.dim(shortId(sourceNode.id))}) and ` +\n `${chalk.cyan(targetNode.data.label)} (${chalk.dim(shortId(targetNode.id))})`,\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n outputError,\n outputSuccess,\n formatSuccess,\n formatKeyValue,\n} from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n findNodeByPrefix,\n shortId,\n} from \"../../lib/node-graph.js\";\n\nexport interface NodeConfigOptions extends OutputOptions {\n scene: string;\n project: string;\n set?: string;\n}\n\nexport async function nodeConfigCommand(\n nodeId: string,\n options: NodeConfigOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n const node = findNodeByPrefix(graph.nodes, nodeId);\n if (!node) {\n outputError(\n `Node not found matching \"${nodeId}\". Run 'program node list' to see node IDs.`,\n options,\n );\n process.exit(1);\n }\n\n // Read-only mode: show current config\n if (!options.set) {\n if (options.json) {\n outputSuccess(\n {\n nodeId: node.id,\n type: node.type,\n label: node.data.label,\n config: node.data.config,\n },\n options,\n );\n } else {\n console.log(\n `\\nConfig for ${chalk.cyan(node.data.label)} (${chalk.dim(shortId(node.id))}, ${node.type}):\\n`,\n );\n\n const entries = Object.entries(node.data.config);\n if (entries.length === 0) {\n console.log(chalk.dim(\" (no config set)\"));\n } else {\n console.log(\n formatKeyValue(\n entries.map(([key, value]) => ({\n key,\n value:\n typeof value === \"string\"\n ? value.length > 80\n ? value.slice(0, 77) + \"...\"\n : value\n : JSON.stringify(value),\n })),\n { indent: 2 },\n ),\n );\n }\n }\n return;\n }\n\n // Write mode: merge config\n let updates: Record<string, unknown>;\n try {\n updates = JSON.parse(options.set) as Record<string, unknown>;\n } catch {\n outputError(\"Invalid JSON in --set\", options);\n process.exit(1);\n return; // unreachable but satisfies TS\n }\n\n node.data.config = { ...node.data.config, ...updates };\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n {\n nodeId: node.id,\n type: node.type,\n label: node.data.label,\n config: node.data.config,\n },\n options,\n );\n } else {\n const keys = Object.keys(updates).join(\", \");\n console.log(\n formatSuccess(\n `Updated config on ${chalk.cyan(node.data.label)} (${chalk.dim(shortId(node.id))}): ${keys}`,\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import { execFileSync } from \"node:child_process\";\nimport chalk from \"chalk\";\nimport ora from \"ora\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport {\n outputError,\n outputSuccess,\n formatTable,\n formatSuccess,\n formatWarning,\n} from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport {\n getNodeGraph,\n saveNodeGraph,\n topologicalSort,\n resolveInputsForNode,\n validateGraph,\n shortId,\n} from \"../../lib/node-graph.js\";\n\nexport interface NodeExecuteOptions extends OutputOptions {\n scene: string;\n project: string;\n dryRun?: boolean;\n}\n\nexport async function nodeExecuteCommand(\n options: NodeExecuteOptions,\n): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n // Validate\n const validation = validateGraph(graph.nodes, graph.edges);\n if (!validation.valid) {\n if (options.json) {\n outputError(\n `Graph validation failed: ${validation.warnings.join(\"; \")}`,\n options,\n );\n } else {\n console.error(chalk.red(\"\\nGraph validation failed:\\n\"));\n for (const w of validation.warnings) {\n console.error(` ${formatWarning(w)}`);\n }\n }\n process.exit(1);\n }\n\n // Topo sort\n const order = topologicalSort(graph.nodes, graph.edges);\n\n if (order.length === 0) {\n outputError(\"No executable nodes in graph.\", options);\n process.exit(1);\n }\n\n // Build execution plan\n const plan = order.map((nodeId) => {\n const node = graph.nodes.find((n) => n.id === nodeId);\n if (!node) throw new Error(`Node ${nodeId} not found in graph`);\n const inputs = resolveInputsForNode(nodeId, graph.nodes, graph.edges);\n return { nodeId, node, inputs };\n });\n\n // Dry run: show plan and exit\n if (options.dryRun) {\n if (options.json) {\n outputSuccess(\n {\n dryRun: true,\n executionOrder: plan.map((p) => ({\n nodeId: p.nodeId,\n type: p.node.type,\n label: p.node.data.label,\n inputs: p.inputs,\n })),\n validation,\n },\n options,\n );\n return;\n }\n\n console.log(chalk.bold(\"\\nExecution Plan (dry run):\\n\"));\n\n const planRows = plan.map((p, i) => {\n const inputSummary = Object.entries(p.inputs)\n .map(([k, v]) => {\n const s = typeof v === \"string\" ? v : JSON.stringify(v);\n const display = (s || \"\").toString();\n return `${k}=${display.length > 30 ? display.slice(0, 27) + \"...\" : display}`;\n })\n .join(\", \");\n\n return [\n String(i + 1),\n chalk.cyan(shortId(p.nodeId)),\n p.node.type,\n p.node.data.label,\n inputSummary || chalk.dim(\"(none)\"),\n ];\n });\n\n console.log(\n formatTable([\"#\", \"ID\", \"Type\", \"Label\", \"Inputs\"], planRows, {\n indent: 2,\n }),\n );\n\n if (validation.warnings.length > 0) {\n console.log(chalk.yellow(\"\\nWarnings:\"));\n for (const w of validation.warnings) {\n console.log(` ${formatWarning(w)}`);\n }\n }\n return;\n }\n\n // ─── Live execution ──────────────────────────────────────────────\n const showSpinner = !options.json && process.stdout.isTTY;\n const results: {\n nodeId: string;\n type: string;\n label: string;\n status: \"success\" | \"error\" | \"skipped\";\n output?: Record<string, unknown>;\n error?: string;\n durationMs?: number;\n }[] = [];\n\n // Reset node statuses\n for (const n of graph.nodes) {\n n.data.status = \"idle\";\n n.data.output = undefined;\n }\n\n let failed = false;\n\n for (const step of plan) {\n const { nodeId, node, inputs } = step;\n\n if (failed) {\n results.push({\n nodeId,\n type: node.type,\n label: node.data.label,\n status: \"skipped\",\n });\n continue;\n }\n\n // Scene-output collects inputs, no CLI call\n if (node.type === \"scene-output\") {\n node.data.status = \"success\";\n node.data.output = inputs;\n results.push({\n nodeId,\n type: node.type,\n label: node.data.label,\n status: \"success\",\n output: inputs,\n });\n continue;\n }\n\n // Generate nodes — call program tool exec\n const toolName =\n node.type === \"generate-video\"\n ? \"generateVideo\"\n : node.type === \"generate-image\"\n ? \"generateImage\"\n : node.type === \"generate-speech\"\n ? \"generateSpeech\"\n : \"extractAudio\";\n\n const params: Record<string, unknown> = {\n sceneId: options.scene,\n };\n if (node.type === \"generate-speech\") {\n params.text = inputs.prompt ?? \"\";\n params.model = inputs.model ?? \"\";\n if (inputs.audioUrl) params.voiceClone = inputs.audioUrl;\n if (inputs.provider) params.provider = inputs.provider;\n if (typeof inputs.duration === \"number\") params.duration = inputs.duration;\n } else if (node.type === \"extract-audio\") {\n params.videoUrl = inputs.videoUrl ?? \"\";\n if (typeof inputs.duration === \"number\") params.duration = inputs.duration;\n } else {\n params.prompt = inputs.prompt ?? \"\";\n params.model = inputs.model ?? \"\";\n if (inputs.imageUrl) params.imageUrl = inputs.imageUrl;\n if (inputs.provider) params.provider = inputs.provider;\n if (typeof inputs.duration === \"number\") params.duration = inputs.duration;\n }\n\n const spinner = showSpinner\n ? ora(`Executing ${node.data.label} (${shortId(nodeId)})...`).start()\n : null;\n node.data.status = \"running\";\n\n const startTime = Date.now();\n\n try {\n const cliEntry = process.argv[1];\n if (!cliEntry) {\n throw new Error(\"CLI entrypoint not found\");\n }\n\n const output = execFileSync(\n process.execPath,\n [\n cliEntry,\n \"tool\",\n \"exec\",\n toolName,\n \"--project\",\n options.project,\n \"--params\",\n JSON.stringify(params),\n \"--json\",\n ],\n {\n encoding: \"utf-8\",\n timeout: 300_000, // 5 min per node\n maxBuffer: 10 * 1024 * 1024,\n },\n );\n\n const durationMs = Date.now() - startTime;\n\n let result: Record<string, unknown> = {};\n try {\n result = JSON.parse(output) as Record<string, unknown>;\n if (result.data) result = result.data as Record<string, unknown>;\n } catch {\n // parse fail — treat as success with empty output\n }\n\n node.data.status = \"success\";\n node.data.output = result;\n\n spinner?.succeed(\n `${node.data.label} (${shortId(nodeId)}) completed in ${(durationMs / 1000).toFixed(1)}s`,\n );\n\n results.push({\n nodeId,\n type: node.type,\n label: node.data.label,\n status: \"success\",\n output: result,\n durationMs,\n });\n } catch (err) {\n const durationMs = Date.now() - startTime;\n const error = err instanceof Error ? err.message : String(err);\n node.data.status = \"error\";\n node.data.output = { error };\n failed = true;\n\n spinner?.fail(`${node.data.label} (${shortId(nodeId)}) failed`);\n\n results.push({\n nodeId,\n type: node.type,\n label: node.data.label,\n status: \"error\",\n error,\n durationMs,\n });\n }\n }\n\n // Save graph with updated statuses/outputs\n graph.lastExecution = {\n status: failed ? \"error\" : \"success\",\n startedAt: Date.now() - results.reduce((sum, r) => sum + (r.durationMs ?? 0), 0),\n completedAt: Date.now(),\n nodeOutputs: Object.fromEntries(\n results\n .filter((r): r is typeof r & { output: Record<string, unknown> } => r.output !== undefined)\n .map((r) => [r.nodeId, r.output]),\n ),\n };\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n {\n status: failed ? \"error\" : \"success\",\n results,\n },\n options,\n );\n } else {\n console.log(\"\");\n if (failed) {\n console.log(chalk.red(\"Execution failed. See errors above.\"));\n } else {\n console.log(\n formatSuccess(\n `All ${results.length} node(s) executed successfully.`,\n ),\n );\n }\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n","import chalk from \"chalk\";\n\nimport type { OutputOptions } from \"../../lib/output.js\";\nimport { outputError, outputSuccess, formatSuccess } from \"../../lib/output.js\";\nimport { isLocalAvailable } from \"../../lib/local-convex.js\";\nimport { getNodeGraph, saveNodeGraph, autoLayoutNodes } from \"../../lib/node-graph.js\";\n\nexport interface NodeLayoutOptions extends OutputOptions {\n scene: string;\n project: string;\n}\n\nexport async function nodeLayoutCommand(options: NodeLayoutOptions): Promise<void> {\n if (!options.scene || !options.project) {\n outputError(\"--scene and --project are required\", options);\n process.exit(1);\n }\n\n if (!(await isLocalAvailable())) {\n outputError(\"Local backend not available at http://127.0.0.1:3210\", options);\n process.exit(1);\n }\n\n try {\n const { graph } = await getNodeGraph(options.project, options.scene);\n\n const layoutedNodes = autoLayoutNodes(graph.nodes, graph.edges);\n graph.nodes = layoutedNodes;\n\n await saveNodeGraph(options.project, options.scene, graph);\n\n if (options.json) {\n outputSuccess(\n { nodes: layoutedNodes.length, message: \"Layout applied\" },\n options,\n );\n } else {\n console.log(\n formatSuccess(\n `Applied auto-layout to ${chalk.cyan(String(layoutedNodes.length))} nodes`,\n ),\n );\n }\n } catch (err) {\n outputError((err as Error).message, options);\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,eAAe;;;ACOxB,IAAM,iBAAiB;AAAA,EACrB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AAAA,EACb,UAAU;AAAA,IACR,MAAM;AAAA,MACJ,aAAa;AAAA,MACb,aAAa;AAAA,QACX,OAAO;AAAA,UACL,aAAa;AAAA,UACb,SAAS;AAAA,YACP,UAAU;AAAA,UACZ;AAAA,UACA,SAAS;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,UACN,aAAa;AAAA,UACb,SAAS;AAAA,YACP,UAAU;AAAA,UACZ;AAAA,UACA,SAAS;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,UACN,aAAa;AAAA,UACb,SAAS;AAAA,YACP,UAAU;AAAA,UACZ;AAAA,UACA,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP,aAAa;AAAA,MACb,aAAa;AAAA,QACX,QAAQ;AAAA,UACN,aAAa;AAAA,UACb,SAAS;AAAA,YACP,mBAAmB;AAAA,YACnB,wBAAwB;AAAA,YACxB,UAAU;AAAA,UACZ;AAAA,UACA,SAAS;AAAA,QACX;AAAA,QACA,MAAM;AAAA,UACJ,aAAa;AAAA,UACb,SAAS;AAAA,YACP,eAAe;AAAA,YACf,UAAU;AAAA,UACZ;AAAA,UACA,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,aAAa;AAAA,MACb,aAAa;AAAA,QACX,MAAM;AAAA,UACJ,aAAa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pE,OAAO,wBAAwB,oCAAoC,EACnE,OAAO,SAAS,yDAAyD,EACzE,OAAO,UAAU,gBAAgB,EACjC,OAAO,OAAO,UAAkB,UAA8B,YAAmC;AAChG,QAAM,sBAAsB,UAAU,UAAU,OAAO;AACzD,CAAC;AAEH,KACG,QAAQ,iBAAiB,EACzB,YAAY,uCAAuC,EACnD,eAAe,gBAAgB,UAAU,EACzC,eAAe,kBAAkB,gBAAgB,EACjD,OAAO,gBAAgB,gCAAgC,EACvD,OAAO,UAAU,gBAAgB,EACjC,OAAO,OAAO,QAAgB,YAA+B;AAC5D,QAAM,kBAAkB,QAAQ,OAAO;AACzC,CAAC;AAEH,KACG,QAAQ,SAAS,EACjB,YAAY,4EAA4E,EACxF,eAAe,gBAAgB,UAAU,EACzC,eAAe,kBAAkB,gBAAgB,EACjD,OAAO,aAAa,qCAAqC,EACzD,OAAO,UAAU,gBAAgB,EACjC,OAAO,OAAO,YAAgC;AAC7C,QAAM,mBAAmB,OAAO;AAClC,CAAC;AAEH,KACG,QAAQ,YAAY,EACpB,YAAY,4DAA4D,EACxE,eAAe,gBAAgB,UAAU,EACzC,eAAe,kBAAkB,gBAAgB,EACjD,OAAO,UAAU,gBAAgB,EACjC,OAAO,OAAO,YAA+B;AAC5C,QAAM,kBAAkB,OAAO;AACjC,CAAC;AAKH,QACG,QAAQ,MAAM,EACd,YAAY,8CAA8C,EAC1D,OAAO,YAAY,oCAAoC,EACvD,OAAO,UAAU,gBAAgB,EACjC,OAAO,CAAC,YAAyB;AAChC,cAAY,OAAO;AACrB,CAAC;AAGH,QAAQ,MAAM;","names":["access","join","chalk","checkSetup","readFile","readFile","chalk","join","step","access","chalk","tools","chalk","chalk","model","chalk","tool","chalk","chalk","chalk","chalk","chalk","OLLAMA_URL","isOllamaRunning","ollamaGenerate","model","chalk","execFile","access","mkdir","readdir","rm","join","promisify","chalk","ora","execFileAsync","promisify","execFile","chalk","duration","ora","mkdir","join","rm","readdir","access","chalk","ora","status","chalk","ora","chalk","ora","step","ora","chalk","chalk","ora","ora","chalk","chalk","ora","ora","template","chalk","chalk","ora","listCommand","ora","chalk","chalk","ora","step","model","template","chalk","ora","chalk","ora","ora","template","chalk","ora","ora","template","ora","ora","template","ora","ora","chalk","ora","ora","chalk","execSync","crypto","existsSync","rmSync","readFileSync","writeFileSync","tmpdir","access","mkdir","readFile","path","ora","join","tmpdir","join","tmpdir","readFileSync","model","readFileSync","crypto","crypto","join","homedir","mkdirSync","readFileSync","ora","crypto","model","existsSync","readFile","path","tmpdir","rmSync","writeFileSync","execSync","mkdir","access","chalk","tools","chalk","chalk","crypto","node","crypto","measured","nodeWidth","chalk","chalk","node","chalk","chalk","node","chalk","chalk","chalk","chalk","chalk","chalk","node","chalk","chalk","ora","chalk","node","step","ora","chalk","chalk","require","listCommand"]}