langtrain 0.1.19 → 0.1.21

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/cli.mjs CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import {e,h as h$1,j,c,a,g,i}from'./chunk-Q46V6ODQ.mjs';import {Command}from'commander';import {select,isCancel,confirm,text,cancel,password}from'@clack/prompts';import {red,blue,dim,bold,cyan,gray,yellow,green,black,bgCyan}from'kleur/colors';import L from'gradient-string';import M from'fs';import B from'path';import we from'os';function te(n){console.clear(),console.log(L(["#00DC82","#36E4DA","#0047E1"])(`
2
+ import {a,b,h,q as q$1,r,o,k,m,f as f$1,d,j,c,l}from'./chunk-TDQXC2RA.mjs';import Ge from'cli-table3';import {text,isCancel,select,confirm,cancel,password}from'@clack/prompts';import {green,gray,red,yellow,bgMagenta,black,magenta,blue,white,dim,bold,cyan}from'kleur/colors';import K from'gradient-string';import G from'fs';import se from'path';import Pe from'os';import {Command}from'commander';function q(a){return new Ge({head:a.map(r=>F.magenta(F.bold(r))),chars:{top:"\u2500","top-mid":"\u252C","top-left":"\u250C","top-right":"\u2510",bottom:"\u2500","bottom-mid":"\u2534","bottom-left":"\u2514","bottom-right":"\u2518",left:"\u2502","left-mid":"\u251C",mid:"\u2500","mid-mid":"\u253C",right:"\u2502","right-mid":"\u2524",middle:"\u2502"},style:{"padding-left":1,"padding-right":1,head:[],border:["gray"]}})}var me=a(()=>{$();});function we(a){console.clear(),console.log(K(["#A855F7","#EC4899","#3B82F6"])(`
3
3
  \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
4
4
  \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551
5
5
  \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
6
6
  \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551
7
7
  \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551
8
8
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D
9
- `)),console.log(`${bgCyan(black(` Langtrain SDK v${n} `))}
10
- `);}function m(n){console.log(cyan(`\u25C6 ${n}`));}function A(n){console.log(gray(`\u2514 ${n}`));}function p(){return {start:n=>process.stdout.write(`${cyan("\u25CF")} ${n}\r`),stop:n=>{console.log(n?`${green("\u2714")} ${n}`:"");},message:n=>process.stdout.write(`${cyan("\u25CF")} ${n}\r`)}}function D(n){console.log(green(`\u2714 ${n}`));}function ne(n){console.log(yellow(`\u26A0 Warning: ${n}`));}function ae(n){console.log(blue(`\u2139 ${n}`));}var k={bgCyan:bgCyan,black:black,red:red,green:green,yellow:yellow,gray:gray,cyan:cyan,bold:bold,dim:dim,blue:blue};var Y=B.join(we.homedir(),".langtrain"),z=B.join(Y,"config.json");function h(){if(!M.existsSync(z))return {};try{return JSON.parse(M.readFileSync(z,"utf-8"))}catch{return {}}}function oe(n){M.existsSync(Y)||M.mkdirSync(Y,{recursive:true}),M.writeFileSync(z,JSON.stringify(n,null,2));}async function E(){for(;;){console.log(gray(`
9
+ `)),console.log(`${bgMagenta(black(` Langtrain SDK v${a} `))}
10
+ `);}function w(a){console.log(magenta(`\u25C6 ${a}`));}function _(a){console.log(gray(`\u2514 ${a}`));}function u(){return {start:a=>process.stdout.write(`${magenta("\u25CF")} ${a}\r`),stop:a=>{console.log(a?`${green("\u2714")} ${a}`:"");},message:a=>process.stdout.write(`${magenta("\u25CF")} ${a}\r`)}}function R(a){console.log(green(`\u2714 ${a}`));}function be(a){console.log(yellow(`\u26A0 Warning: ${a}`));}function ve(a){console.log(blue(`\u2139 ${a}`));}var F,$=a(()=>{me();F={bgMagenta:bgMagenta,black:black,red:red,green:green,yellow:yellow,gray:gray,cyan:cyan,bold:bold,dim:dim,blue:blue,magenta:magenta,white:white};});function f(){if(!G.existsSync(ae))return {};try{return JSON.parse(G.readFileSync(ae,"utf-8"))}catch{return {}}}function $e(a){G.existsSync(ne)||G.mkdirSync(ne,{recursive:true}),G.writeFileSync(ae,JSON.stringify(a,null,2));}var ne,ae,I=a(()=>{ne=se.join(Pe.homedir(),".langtrain"),ae=se.join(ne,"config.json");});async function Ke(a,r){let t=await text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(l){if(!l||l.length===0)return "API Key is required"}});if(isCancel(t)){cancel("Operation cancelled");return}let e=await text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(isCancel(e))return;let n=await text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(isCancel(n))return;let i="gpt-4o",o=u();o.start("Fetching agent models...");try{let l=await r.list("agent");o.stop(`Found ${l.length} models`),l.length>0&&(i=await select({message:"Select Agent Model:",options:l.map(c=>({value:c.id,label:c.id}))}));}catch{o.stop(yellow("Could not fetch models, using default."));}if(isCancel(i))return;let s=u();s.start("Creating agent...");try{let l=await a.list(),c="";if(l.length>0)c=l[0].workspace_id;else {s.stop(yellow("Workspace ID needed (no existing agents found)."));let k=await text({message:"Enter Workspace ID (UUID):",validate(S){if(!S||S.length===0)return "Required"}});if(isCancel(k))return;c=k,s.start("Creating agent...");}let v=await a.create({workspace_id:c,name:t,description:e,config:{system_prompt:n,model:i}});s.stop(green(`Agent "${v.name}" created successfully! ID: ${v.id}`));}catch(l){throw s.stop(red("Failed to create agent.")),l}}async function Ue(a){let r=u();r.start("Fetching agents...");let t=await a.list();if(r.stop(`Found ${t.length} agents`),t.length===0){w(yellow("No agents to delete."));return}let e=await select({message:"Select an agent to DELETE:",options:t.map(o=>({value:o.id,label:o.name,hint:o.description||"No description"}))});if(isCancel(e))return;if(await select({message:"Are you sure you want to delete this agent?",options:[{value:"yes",label:"Yes, delete it",hint:"Cannot be undone"},{value:"no",label:"No, keep it"}]})!=="yes"){w(gray("Deletion cancelled."));return}let i=u();i.start("Deleting agent...");try{await a.delete(e),i.stop(green("Agent deleted successfully."));}catch(o){throw i.stop(red("Failed to delete agent.")),o}}async function _e(a){let r=u();r.start("Fetching agents...");let t=await a.list();if(r.stop(`Found ${t.length} agents`),t.length===0){w(yellow("No agents found in your workspace."));return}let e=q(["ID","Name","Model","Created"]);t.forEach(i=>{e.push([i.id.substring(0,8)+"...",i.name,i.config?.model||"default",new Date(i.created_at).toLocaleDateString()]);}),console.log(e.toString()),console.log("");let n=await select({message:"Select an agent to run:",options:t.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});isCancel(n)||await oe(a,n,t.find(i=>i.id===n)?.name||"Agent");}async function oe(a,r,t,e){w(bgMagenta(black(` Chatting with ${t} `))),console.log(gray('Type "exit" to quit conversation.'));let n;if(e){let i=u();i.start("Agent is analyzing...");try{let o=await a.execute(r,{prompt:e},[],n);i.stop(),o.output?.response?console.log(K.pastel(`Agent: ${o.output.response}`)):console.log(K.pastel(`Agent: ${JSON.stringify(o.output)}`)),n=o.conversation_id;}catch(o){i.stop(red("Error running agent.")),console.error(o);}}for(;;){let i=await text({message:"You:",placeholder:"Type a message..."});if(isCancel(i)||i==="exit")break;let o=u();o.start("Agent is thinking...");try{let s=await a.execute(r,{prompt:i},[],n);o.stop(),s.output?.response?console.log(K.pastel(`Agent: ${s.output.response}`)):console.log(K.pastel(`Agent: ${JSON.stringify(s.output)}`)),n=s.conversation_id;}catch(s){o.stop(red("Error running agent.")),console.error(s);}}}var ie=a(()=>{$();});var je={};b(je,{handleDataAnalyze:()=>Re,handleDataList:()=>Qe,handleDataRefine:()=>H,handleDataUpload:()=>Y});async function Y(a){let t=f().workspace_id,e=await text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(o){if(!o)return "Required";if(!G.existsSync(o))return "File not found"}});if(isCancel(e))return;let n=await select({message:"File Purpose:",options:[{value:"fine-tune",label:"Fine-tuning (JSONL)"},{value:"vision-tune",label:"Vision Tuning (Image/Zip)"},{value:"agent-knowledge",label:"Agent Knowledge"}]});if(isCancel(n))return;let i=u();i.start("Uploading file...");try{let o=await a.upload(e,t,n);i.stop(green("File uploaded successfully!")),console.log(gray(`ID: ${o.id}`)),console.log(gray(`Name: ${o.filename}`)),console.log(gray(`Bytes: ${o.bytes}`));}catch(o){i.stop(red(`Upload failed: ${o.message}`));}}async function Qe(a){let t=f().workspace_id;if(!t&&(t=await text({message:"Enter Workspace ID (optional):",initialValue:""}),isCancel(t)))return;let e=u();e.start("Fetching files...");try{let n=await a.list(t);if(e.stop(`Found ${n.length} files`),n.length===0){console.log(yellow("No files found."));return}let i=await select({message:"Select file to analyze (or cancel to exit):",options:n.map(o=>({value:o.id,label:`${o.filename} (${Ne(o.bytes)})`}))});if(isCancel(i))return;await Re(a,i);}catch(n){e.stop(red(`Failed to list files: ${n.message}`));}}async function Re(a,r){let t=f(),e=u();e.start("Connecting to Data Analyst...");try{let n=new h({apiKey:t.apiKey||"",baseUrl:t.baseUrl}),o=(await n.list()).find(s=>s.name&&s.name==="Langtrain Data Analyst");if(!o){e.stop(yellow("Data Analyst agent (System) not found. Please contact admin to provision it."));return}e.stop(green("Connected to Data Analyst.")),console.log(gray(`
11
+ Analyzing dataset ${r}...
12
+ `)),await oe(n,o.id,o.name,`Please analyze the dataset with ID: ${r}`);}catch(n){e.stop(red(`Failed to connect: ${n.message}`));}}async function H(a,r){let t=f(),e=new q$1({apiKey:t.apiKey||"",baseUrl:t.baseUrl});if(!r){let s=u();s.start("Fetching files...");try{let l=t.workspace_id||"",c=await a.list(l);if(s.stop(`Found ${c.length} files`),c.length===0){console.log(yellow("No files found. Upload one first."));return}let v=await select({message:"Select file to refine:",options:c.map(k=>({value:k.id,label:`${k.filename} (${Ne(k.bytes)})`}))});if(isCancel(v))return;r=v;}catch(l){s.stop(red(`Failed to fetch files: ${l.message}`));return}}let n=u();n.start("Fetching guardrails...");let i="";try{let s=await e.list();if(n.stop(`Found ${s.length} guardrails`),s.length===0){console.log(yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let l=await select({message:"Select a Guardrail to apply:",options:s.map(c=>({value:c.id,label:c.name,hint:c.description}))});if(isCancel(l))return;i=l;}catch(s){n.stop(red(`Failed to fetch guardrails: ${s.message}`));return}let o=u();o.start("Applying guardrail (filtering dataset)...");try{let s=await e.apply(r,i);o.stop(green("Dataset refined successfully!")),console.log(gray("Stats:")),console.log(`Original Rows: ${s.original_rows}`),console.log(`Filtered Rows: ${s.filtered_rows}`),console.log(red(`Removed: ${s.removed_rows} rows`)),console.log(green(`New Dataset ID: ${s.new_dataset_id}`));}catch(s){o.stop(red(`Failed to refine dataset: ${s.message}`));}}function Ne(a,r=2){if(!+a)return "0 Bytes";let t=1024,e=r<0?0:r,n=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(a)/Math.log(t));return `${parseFloat((a/Math.pow(t,i)).toFixed(e))} ${n[i]}`}var le=a(()=>{$();I();r();ie();});$();$();$();I();r();async function J(){for(;;){console.log(gray(`
11
13
  Get your API Key at: https://langtrain.xyz/settings/keys
12
- `));let n=await password({message:"Enter your Langtrain API Key:",validate(a){if(!a||a.length===0)return "API Key is required"}});isCancel(n)&&(cancel("Operation cancelled"),process.exit(0));let o=p();o.start("Verifying API Key...");try{let e=await new i({apiKey:n}).getStatus();o.stop(green(`Authenticated as ${e.plan==="pro"?"PRO":e.plan.toUpperCase()}`));let t=h();oe({...t,apiKey:n});return}catch{o.stop(red("Invalid API Key. Please try again."));}}}async function T(n){let o=new i({apiKey:n}),a=p();a.start("Verifying subscription plan...");try{let e=await o.getStatus(),t=e.plan==="pro"?bgCyan(" PRO "):e.plan.toUpperCase();return a.stop(green(`Authenticated as ${t}`)),e.is_active===!1&&console.log(yellow("Warning: Your subscription is not active. Some features may be limited.")),e}catch(e){return a.stop(red("Failed to verify subscription.")),e.response&&e.response.status===401&&console.log(red("Invalid API Key. Please run login again.")),null}}function se(n,o,a){o?.plan==="pro"||o?.plan==="enterprise";switch(n){case "main":let t=[{value:"nav-agents",label:"Agents",hint:"Manage & Chat with AI Agents"},{value:"nav-text",label:"Langtune (Text)",hint:"Fine-tuning & Generation"},{value:"nav-vision",label:"Langvision (Vision)",hint:"Vision Analysis & Tuning"},{value:"init",label:"Initialize Project",hint:"Scaffold new Langtrain app"},{value:"deploy",label:"Deploy",hint:"Push config to Cloud"},{value:"dev",label:"Start Dev Server",hint:"Watch mode"},{value:"doctor",label:"Doctor",hint:"Check environment health"},{value:"nav-settings",label:"Settings",hint:"Subscription & Auth"}];return a||t.unshift({value:"login",label:"Login to Langtrain",hint:"Required for most features"}),t.push({value:"exit",label:"Exit"}),t;case "agents":return [{value:"agent-list",label:"List & Run Agents",hint:"Chat with active agents"},{value:"agent-create",label:"Create New Agent",hint:"Deploy a new agent"},{value:"agent-delete",label:"Delete Agent",hint:"Remove an agent"},{value:"back",label:"\u2190 Back to Main Menu"}];case "text":return [{value:"tune-finetune",label:"Fine-tune Text Model",hint:"Create custom LLM"},{value:"tune-list",label:"List Jobs",hint:"Check training status"},{value:"tune-generate",label:"Generate Text",hint:"Test your models"},{value:"data-upload",label:"Upload Dataset",hint:"Upload JSONL for training"},{value:"back",label:"\u2190 Back to Main Menu"}];case "vision":return [{value:"vision-finetune",label:"Fine-tune Vision Model",hint:"Create custom VLM"},{value:"vision-generate",label:"Generate Vision Response",hint:"Test vision models"},{value:"back",label:"\u2190 Back to Main Menu"}];case "settings":return [{value:"status",label:a?`Subscription Status (${o?.plan||"Free"})`:"Check Status (Login required)"},{value:"login",label:a?"Update API Key":"Login"},{value:"back",label:"\u2190 Back to Main Menu"}];default:return []}}async function re(){let n=h();if(!n.apiKey){m(red('Not logged in. Run "login" first.'));return}let o=new i({apiKey:n.apiKey}),a=p();a.start("Fetching subscription status...");try{let e=await o.getStatus();a.stop(green("Subscription Status:")),console.log(gray("Plan: ")+(e.plan==="pro"?bgCyan(" PRO "):e.plan.toUpperCase())),console.log(gray("Active: ")+(e.is_active?green("Yes"):red("No"))),e.expires_at&&console.log(gray("Expires: ")+new Date(e.expires_at).toLocaleDateString()),console.log(gray(`
13
- Limits:`)),console.log(` Models: ${e.limits.max_models===-1?"Unlimited":e.limits.max_models}`),console.log(` Training Jobs: ${e.limits.max_training_jobs}`);}catch(e){a.stop(red("Failed to fetch status.")),console.error(e.message);}}async function le(n,o){let a="",e=p();e.start("Fetching available text models...");try{let s=await o.list("text");e.stop(`Found ${s.length} text models`),s.length>0&&(a=await select({message:"Select base model:",options:s.map(c=>({value:c.id,label:c.id,hint:c.owned_by}))}));}catch{e.stop(yellow("Failed to fetch models. Using manual input.")),a=await text({message:"Enter base model (e.g., gpt-3.5-turbo):",placeholder:"gpt-3.5-turbo",validate(c){if(!c||c.length===0)return "Value is required!"}});}isCancel(a)&&(cancel("Operation cancelled."),process.exit(0));let t=await text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(s){if(!s||s.length===0)return "Value is required!"}});isCancel(t)&&cancel("Operation cancelled.");let r=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(r)&&cancel("Operation cancelled.");let i$1=await select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(isCancel(i$1)&&cancel("Operation cancelled."),i$1==="yes"){let s=p();s.start("Connecting to Cloud...");try{let c=h();if(!c.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new i({apiKey:c.apiKey}).getStatus()).features.includes("cloud_finetuning")){s.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let _=await confirm({message:"Upgrade to Pro for cloud tracking?"});_&&!isCancel(_)&&console.log(bgCyan(black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let K=new g({apiKey:c.apiKey}),O=new h$1({apiKey:c.apiKey});s.message("Uploading dataset...");let V=await K.upload(t);s.message("Creating Job...");let J=await O.createJob({name:`cli-sft-${Date.now()}`,base_model:a,dataset_id:V.id,task:"text",hyperparameters:{n_epochs:parseInt(r)}});s.stop(green(`Job tracked: ${J.id}`));}catch(c){s.stop(red(`Tracking failed: ${c.message}`));let x=await confirm({message:"Continue with local training anyway?"});if(!x||isCancel(x))return}}let u=p();u.start("Starting local fine-tuning...");try{let s={model:a,trainFile:t,preset:"default",epochs:parseInt(r),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await n.finetune(s),u.stop(green("Fine-tuning job started successfully!"));}catch(s){throw u.stop(red("Failed to start job.")),s}}async function ce(n){let o=await text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});isCancel(o)&&cancel("Operation cancelled");let a=await text({message:"Enter prompt:",placeholder:"Hello world"});isCancel(a)&&cancel("Operation cancelled");let e=p();e.start("Connecting to Langtrain Inference API...");try{let t=await n.generate(o,{prompt:a});e.stop("Generation complete"),m("Response:"),console.log(L.pastel(t));}catch(t){throw e.stop(red("Generation failed.")),t}}async function ge(n){let o=p();o.start("Fetching fine-tuning jobs...");let e=h().workspace_id;if(!(!e&&(o.stop(yellow("Workspace ID required to list jobs.")),e=await text({message:"Enter Workspace ID:"}),isCancel(e))))try{let t=await n.listJobs(e);if(o.stop(`Found ${t.data.length} jobs`),t.data.length===0){console.log(yellow("No jobs found."));return}let r=await select({message:"Select a job to view details:",options:t.data.map(i=>({value:i.id,label:`${i.name||i.id} (${i.status})`,hint:`Created: ${new Date(i.created_at).toLocaleDateString()}`}))});if(isCancel(r))return;await pe(n,r);}catch(t){o.stop(red(`Failed to list jobs: ${t.message}`));}}async function pe(n,o){let a=o;if(!a&&(a=await text({message:"Enter Job ID:"}),isCancel(a)))return;let e=p();e.start(`Fetching status for ${a}...`);try{let t=await n.getJob(a);if(e.stop(`Job Status: ${t.status.toUpperCase()}`),console.log(gray("------------------------------------------------")),console.log(`${bgCyan(black(" Job Details "))}`),console.log(`ID: ${t.id}`),console.log(`Name: ${t.name}`),console.log(`Status: ${t.status==="succeeded"?green(t.status):t.status}`),console.log(`Model: ${t.base_model}`),console.log(`Progress: ${t.progress||0}%`),t.error_message&&console.log(red(`Error: ${t.error_message}`)),console.log(gray("------------------------------------------------")),t.status==="running"||t.status==="queued"){let r=await select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});r==="refresh"&&await pe(n,a),r==="cancel"&&await $e(n,a);}}catch(t){e.stop(red(`Failed to get job status: ${t.message}`));}}async function $e(n,o){let a=await confirm({message:"Are you sure you want to cancel this job?"});if(!a||isCancel(a))return;let e=p();e.start("Canceling job...");try{await n.cancelJob(o),e.stop(green("Job canceled successfully."));}catch(t){e.stop(red(`Failed to cancel job: ${t.message}`));}}async function ue(n,o){let a="",e=p();e.start("Fetching available vision models...");try{let s=await o.list("vision");e.stop(`Found ${s.length} vision models`),s.length>0?a=await select({message:"Select base vision model:",options:s.map(c=>({value:c.id,label:c.id,hint:c.owned_by}))}):a=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{e.stop(yellow("Failed to fetch models. Using manual input.")),a=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}isCancel(a)&&(cancel("Operation cancelled"),process.exit(0));let t=await text({message:"Enter dataset path:",placeholder:"./dataset"});isCancel(t)&&cancel("Operation cancelled");let r=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(r)&&cancel("Operation cancelled");let i$1=await select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(isCancel(i$1)&&cancel("Operation cancelled"),i$1==="yes"){let s=p();s.start("Connecting to Cloud...");try{let c=h();if(!c.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new i({apiKey:c.apiKey}).getStatus()).features.includes("cloud_finetuning")){s.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let _=await confirm({message:"Upgrade to Pro for cloud tracking?"});_&&!isCancel(_)&&console.log(bgCyan(black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let K=new g({apiKey:c.apiKey}),O=new h$1({apiKey:c.apiKey});s.message("Uploading dataset...");let V=await K.upload(t,void 0,"fine-tune-vision");s.message("Creating Job...");let J=await O.createJob({name:`cli-vision-${Date.now()}`,base_model:a,dataset_id:V.id,task:"vision",training_method:"lora",hyperparameters:{n_epochs:parseInt(r)}});s.stop(green(`Job tracked: ${J.id}`));}catch(c){s.stop(red(`Tracking failed: ${c.message}`));let x=await confirm({message:"Continue with local training anyway?"});if(!x||isCancel(x))return}}let u=p();u.start("Analyzing dataset structure..."),await new Promise(s=>setTimeout(s,800)),u.message("Starting vision fine-tuning on Langtrain Cloud...");try{let s={model:a,dataset:t,epochs:parseInt(r),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await n.finetune(s),u.stop(green("Vision fine-tuning started successfully!"));}catch(s){throw u.stop(red("Failed to start vision job.")),s}}async function de(n){let o=await text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});isCancel(o)&&cancel("Operation cancelled");let a=await text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});isCancel(a)&&cancel("Operation cancelled");let e=p();e.start("Uploading image and context..."),await new Promise(t=>setTimeout(t,600)),e.message("Generating vision response...");try{let t=await n.generate(o,{prompt:a});e.stop("Generation complete"),m("Response:"),console.log(L.pastel(t));}catch(t){throw e.stop(red("Generation failed.")),t}}async function fe(n,o){let a=await text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(s){if(!s||s.length===0)return "API Key is required"}});if(isCancel(a)){cancel("Operation cancelled");return}let e=await text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(isCancel(e))return;let t=await text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(isCancel(t))return;let r="gpt-4o",i=p();i.start("Fetching agent models...");try{let s=await o.list("agent");i.stop(`Found ${s.length} models`),s.length>0&&(r=await select({message:"Select Agent Model:",options:s.map(c=>({value:c.id,label:c.id}))}));}catch{i.stop(yellow("Could not fetch models, using default."));}if(isCancel(r))return;let u=p();u.start("Creating agent...");try{let s=await n.list(),c="";if(s.length>0)c=s[0].workspace_id;else {u.stop(yellow("Workspace ID needed (no existing agents found)."));let R=await text({message:"Enter Workspace ID (UUID):",validate(K){if(!K||K.length===0)return "Required"}});if(isCancel(R))return;c=R,u.start("Creating agent...");}let x=await n.create({workspace_id:c,name:a,description:e,config:{system_prompt:t,model:r}});u.stop(green(`Agent "${x.name}" created successfully! ID: ${x.id}`));}catch(s){throw u.stop(red("Failed to create agent.")),s}}async function me(n){let o=p();o.start("Fetching agents...");let a=await n.list();if(o.stop(`Found ${a.length} agents`),a.length===0){m(yellow("No agents to delete."));return}let e=await select({message:"Select an agent to DELETE:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});if(isCancel(e))return;if(await select({message:"Are you sure you want to delete this agent?",options:[{value:"yes",label:"Yes, delete it",hint:"Cannot be undone"},{value:"no",label:"No, keep it"}]})!=="yes"){m(gray("Deletion cancelled."));return}let r=p();r.start("Deleting agent...");try{await n.delete(e),r.stop(green("Agent deleted successfully."));}catch(i){throw r.stop(red("Failed to delete agent.")),i}}async function he(n){let o=p();o.start("Fetching agents...");let a=await n.list();if(o.stop(`Found ${a.length} agents`),a.length===0){m(yellow("No agents found in your workspace."));return}let e=await select({message:"Select an agent to run:",options:a.map(t=>({value:t.id,label:t.name,hint:t.description||"No description"}))});isCancel(e)||await Ie(n,e,a.find(t=>t.id===e)?.name||"Agent");}async function Ie(n,o,a){m(bgCyan(black(` Chatting with ${a} `))),console.log(gray('Type "exit" to quit conversation.'));let e;for(;;){let t=await text({message:"You:",placeholder:"Type a message..."});if(isCancel(t)||t==="exit")break;let r=p();r.start("Agent is thinking...");try{let i=await n.execute(o,{prompt:t},[],e);r.stop(),i.output?.response?console.log(L.pastel(`Agent: ${i.output.response}`)):console.log(L.pastel(`Agent: ${JSON.stringify(i.output)}`)),e=i.conversation_id;}catch(i){r.stop(red("Error running agent.")),console.error(i);}}}async function H(){m("Initializing new Langtrain project...");let n=process.cwd();if(M.existsSync(B.join(n,"langtrain.config.json"))){ae("langtrain.config.json already exists in this directory.");let i=await confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(isCancel(i)||!i){A("Initialization cancelled.");return}}let o=await text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:B.basename(n),validate(i){if(!i||i.length===0)return "Project name is required!"}});if(isCancel(o)){cancel("Operation cancelled.");return}let a=h(),e=a.apiKey;if(e)D("Found existing Langtrain credentials.");else {let i=await confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(isCancel(i)){cancel("Operation cancelled.");return}if(i)await E(),a=h(),e=a.apiKey;else if(e=await text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),isCancel(e)){cancel("Operation cancelled.");return}}p().start("Creating configuration...");let r={name:o,apiKey:e||void 0,environment:"development",agents:[{name:"support-bot",description:"A helpful customer support assistant",config:{model:"llama-3-8b",system_prompt:"You are a helpful customer support assistant.",temperature:.7}}]};M.writeFileSync(B.join(n,"langtrain.config.json"),JSON.stringify(r,null,2)),D("Project initialized successfully!"),console.log(k.dim(`
14
- Next steps:`)),console.log(` 1. Run ${k.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${k.cyan("lt dev")} to start the local development loop.`),A("Happy coding!");}async function be(){m("Running Langtrain Doctor...");let n=p(),o=0;n.start("Checking Node.js environment...");let a=process.version,e=we.platform(),t=we.arch();parseInt(a.replace("v","").split(".")[0])<18?(n.stop(k.red(`Node.js version ${a} is outdated. Please upgrade to v18+.`)),o++):n.stop(`Node.js ${a} (${e} ${t})`),n.start("Checking configuration...");let r=h();if(!r.apiKey)n.stop(k.yellow("API Key is missing. Run `langtrain login` or set LANGTRAIN_API_KEY.")),o++;else {n.stop("Configuration found."),n.start("Checking API connectivity...");try{let i=await T(r.apiKey);n.stop(`Connected to Langtrain Cloud (Plan: ${k.green(i?.plan||"unknown")})`);}catch(i){n.stop(k.red(`Failed to connect to Langtrain Cloud: ${i.message}`)),o++;}}console.log(""),o===0?D("Your Langtrain environment is healthy! Ready to build."):ne(`Found ${o} issue(s). Please resolve them for the best experience.`),A("Doctor check complete.");}async function ve(n){let a=h().workspace_id,e=await text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(i){if(!i)return "Required";if(!M.existsSync(i))return "File not found"}});if(isCancel(e))return;let t=await select({message:"File Purpose:",options:[{value:"fine-tune",label:"Fine-tuning (JSONL)"},{value:"vision-tune",label:"Vision Tuning (Image/Zip)"},{value:"agent-knowledge",label:"Agent Knowledge"}]});if(isCancel(t))return;let r=p();r.start("Uploading file...");try{let i=await n.upload(e,a,t);r.stop(green("File uploaded successfully!")),console.log(gray(`ID: ${i.id}`)),console.log(gray(`Name: ${i.filename}`)),console.log(gray(`Bytes: ${i.bytes}`));}catch(i){r.stop(red(`Upload failed: ${i.message}`));}}async function P(n){m("Deploying configuration to Langtrain Cloud...");let o=h(),a=o.agents||[];if(a.length===0){m(yellow("No agents found in langtrain.config.json"));return}for(let e of a){let t=p();t.start(`Deploying agent: ${e.name}...`);try{let r=await n.list(),i=r.find(u=>u.name===e.name);if(i)t.stop(yellow(`Agent ${e.name} already exists (ID: ${i.id}). Skipping update (not supported yet).`));else {let u={workspace_id:o.workspace_id||r[0]?.workspace_id||"",name:e.name,description:e.description,config:e.config};if(!u.workspace_id){t.stop(red(`Failed: Workspace ID missing in config for ${e.name}`));continue}await n.create(u),t.stop(green(`Agent ${e.name} deployed successfully!`));}}catch(r){t.stop(red(`Failed to deploy ${e.name}: ${r.message}`));}}D("Deployment complete.");}async function Z(n){m("Starting Langtrain Development Server...");let o=B.join(process.cwd(),"langtrain.config.json");if(!M.existsSync(o)){m(red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(gray(`Watching ${o} for changes...`));let a=false;await P(n),M.watch(o,async e=>{if(e==="change"&&!a){a=true,console.log(yellow("Configuration changed. Redeploying...")),await new Promise(t=>setTimeout(t,500));try{await P(n);}catch(t){console.error(red(`Deploy failed: ${t.message}`));}finally{a=false,console.log(gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}var Q={version:"0.1.19",description:"Unified JavaScript SDK for Langtrain Ecosystem"};async function Ke(){let n=new Command,o=Q.version;n.name("langtrain").description(Q.description).version(o),n.command("init").description("Initialize a new Langtrain project").action(H),n.command("deploy").description("Deploy configuration to Langtrain Cloud").action(async()=>{let a=h(),e$1=a.apiKey||"",t=new e({apiKey:e$1,baseUrl:a.baseUrl});await P(t);}),n.command("dev").description("Start local development server (Watch Mode)").action(async()=>{let a=h(),e$1=a.apiKey||"",t=new e({apiKey:e$1,baseUrl:a.baseUrl});await Z(t);}),n.action(async()=>{te(o),process.argv.includes("--first-run")&&(process.stdin.isTTY?(m("Welcome to Langtrain! Let's get you set up."),await E()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let e$1=h(),t=e$1.apiKey||"",r=null;if(t)try{r=await T(t);}catch{}let i={vision:new a({apiKey:t}),tune:new c({apiKey:t}),agent:new e({apiKey:t,baseUrl:e$1.baseUrl}),model:new j({apiKey:t,baseUrl:e$1.baseUrl}),train:new h$1({apiKey:t,baseUrl:e$1.baseUrl})},u="main";for(;;){let s=await select({message:je(u),options:se(u,r,!!t)});if(isCancel(s))if(u==="main")A("Goodbye!"),process.exit(0);else {u="main";continue}let c$1=s;if(c$1==="exit"&&(A("Goodbye!"),process.exit(0)),c$1==="back"){u="main";continue}if(c$1.startsWith("nav-")){u=c$1.replace("nav-","");continue}try{switch(c$1){case "login":await E(),e$1=h(),t=e$1.apiKey||"",i={vision:new a({apiKey:t}),tune:new c({apiKey:t}),agent:new e({apiKey:t,baseUrl:e$1.baseUrl}),model:new j({apiKey:t,baseUrl:e$1.baseUrl}),train:new h$1({apiKey:t,baseUrl:e$1.baseUrl})};try{r=await T(t);}catch{}break;case "status":await re();break;case "init":await H();break;case "deploy":await P(i.agent);break;case "dev":await Z(i.agent);break;case "doctor":await be();break;case "tune-finetune":await le(i.tune,i.model);break;case "tune-list":await ge(i.train);break;case "tune-generate":await ce(i.tune);break;case "vision-finetune":await ue(i.vision,i.model);break;case "vision-generate":await de(i.vision);break;case "agent-list":await he(i.agent);break;case "agent-create":await fe(i.agent,i.model);break;case "agent-delete":await me(i.agent);break;case "data-upload":await ve(new g({apiKey:t}));break}}catch(x){A(k.red(`Error: ${x.message}`));}}}),n.parse(process.argv);}Ke().catch(console.error);function je(n){switch(n){case "main":return "Main Menu:";case "agents":return "Agents & Tools:";case "text":return "Langtune (Text Operations):";case "vision":return "Langvision (Vision Operations):";case "settings":return "Settings:";default:return "Select an option:"}}export{Ke as main};//# sourceMappingURL=cli.mjs.map
14
+ `));let a=await password({message:"Enter your Langtrain API Key:",validate(t){if(!t||t.length===0)return "API Key is required"}});isCancel(a)&&(cancel("Operation cancelled"),process.exit(0));let r=u();r.start("Verifying API Key...");try{let e=await new l({apiKey:a}).getStatus();r.stop(green(`Authenticated as ${e.plan==="pro"?"PRO":e.plan.toUpperCase()}`));let n=f();$e({...n,apiKey:a});return}catch{r.stop(red("Invalid API Key. Please try again."));}}}async function B(a){let r=new l({apiKey:a}),t=u();t.start("Verifying subscription plan...");try{let e=await r.getStatus(),n=e.plan==="pro"?bgMagenta(" PRO "):e.plan.toUpperCase();return t.stop(green(`Authenticated as ${n}`)),e.is_active===!1&&console.log(yellow("Warning: Your subscription is not active. Some features may be limited.")),e}catch(e){return t.stop(red("Failed to verify subscription.")),e.response&&e.response.status===401&&console.log(red("Invalid API Key. Please run login again.")),null}}function Se(a,r,t){r?.plan==="pro"||r?.plan==="enterprise";switch(a){case "main":let n=[{value:"nav-agents",label:"Agents",hint:"Manage & Chat with AI Agents"},{value:"nav-text",label:"Langtune (Text)",hint:"Fine-tuning & Generation"},{value:"nav-vision",label:"Langvision (Vision)",hint:"Vision Analysis & Tuning"},{value:"nav-guard",label:"Data Guardrails",hint:"Quality & Safety Rules"},{value:"init",label:"Initialize Project",hint:"Scaffold new Langtrain app"},{value:"deploy",label:"Deploy",hint:"Push config to Cloud"},{value:"dev",label:"Start Dev Server",hint:"Watch mode"},{value:"env",label:"Secrets (Env)",hint:"Manage API Keys"},{value:"logs",label:"Logs",hint:"View Agent Logs"},{value:"doctor",label:"Doctor",hint:"Check environment health"},{value:"nav-settings",label:"Settings",hint:"Subscription & Auth"}];return t||n.unshift({value:"login",label:"Login to Langtrain",hint:"Required for most features"}),n.push({value:"exit",label:"Exit"}),n;case "agents":return [{value:"agent-list",label:"List & Run Agents",hint:"Chat with active agents"},{value:"agent-create",label:"Create New Agent",hint:"Deploy a new agent"},{value:"agent-delete",label:"Delete Agent",hint:"Remove an agent"},{value:"back",label:"\u2190 Back to Main Menu"}];case "text":return [{value:"tune-finetune",label:"Fine-tune Text Model",hint:"Create custom LLM"},{value:"tune-list",label:"List Jobs",hint:"Check training status"},{value:"tune-generate",label:"Generate Text",hint:"Test your models"},{value:"data-upload",label:"Upload Dataset",hint:"Upload JSONL for training"},{value:"back",label:"\u2190 Back to Main Menu"}];case "guard":return [{value:"guard-list",label:"List Guardrails",hint:"View active rules"},{value:"guard-create",label:"Create Guardrail",hint:"Define new rules"},{value:"data-refine",label:"Refine Dataset",hint:"Apply guardrail to data"},{value:"back",label:"\u2190 Back to Main Menu"}];case "vision":return [{value:"vision-finetune",label:"Fine-tune Vision Model",hint:"Create custom VLM"},{value:"vision-generate",label:"Generate Vision Response",hint:"Test vision models"},{value:"back",label:"\u2190 Back to Main Menu"}];case "settings":return [{value:"status",label:t?`Subscription Status (${r?.plan||"Free"})`:"Check Status (Login required)"},{value:"login",label:t?"Update API Key":"Login"},{value:"back",label:"\u2190 Back to Main Menu"}];default:return []}}I();$();I();r();async function xe(){let a=f();if(!a.apiKey){w(red('Not logged in. Run "login" first.'));return}let r=new l({apiKey:a.apiKey}),t=u();t.start("Fetching subscription status...");try{let e=await r.getStatus();t.stop(green("Subscription Status:")),console.log(gray("Plan: ")+(e.plan==="pro"?bgMagenta(" PRO "):e.plan.toUpperCase())),console.log(gray("Active: ")+(e.is_active?green("Yes"):red("No"))),e.expires_at&&console.log(gray("Expires: ")+new Date(e.expires_at).toLocaleDateString()),console.log(gray(`
15
+ Limits:`)),console.log(` Models: ${e.limits.max_models===-1?"Unlimited":e.limits.max_models}`),console.log(` Training Jobs: ${e.limits.max_training_jobs}`);}catch(e){t.stop(red("Failed to fetch status.")),console.error(e.message);}}$();I();r();async function ke(a,r){let t="",e=u();e.start("Fetching available text models...");try{let l=await r.list("text");e.stop(`Found ${l.length} text models`),l.length>0&&(t=await select({message:"Select base model:",options:l.map(c=>({value:c.id,label:c.id,hint:c.owned_by}))}));}catch{e.stop(yellow("Failed to fetch models. Using manual input.")),t=await text({message:"Enter base model (e.g., gpt-3.5-turbo):",placeholder:"gpt-3.5-turbo",validate(c){if(!c||c.length===0)return "Value is required!"}});}isCancel(t)&&(cancel("Operation cancelled."),process.exit(0));let n=await text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(l){if(!l||l.length===0)return "Value is required!"}});isCancel(n)&&cancel("Operation cancelled.");let i=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(i)&&cancel("Operation cancelled.");let o=await select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(isCancel(o)&&cancel("Operation cancelled."),o==="yes"){let l$1=u();l$1.start("Connecting to Cloud...");try{let c=f();if(!c.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new l({apiKey:c.apiKey}).getStatus()).features.includes("cloud_finetuning")){l$1.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let T=await confirm({message:"Upgrade to Pro for cloud tracking?"});T&&!isCancel(T)&&console.log(bgMagenta(black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new j({apiKey:c.apiKey}),j$1=new k({apiKey:c.apiKey});l$1.message("Uploading dataset...");let Q=await S.upload(n);l$1.message("Creating Job...");let Z=await j$1.createJob({name:`cli-sft-${Date.now()}`,base_model:t,dataset_id:Q.id,task:"text",hyperparameters:{n_epochs:parseInt(i)}});l$1.stop(green(`Job tracked: ${Z.id}`));}catch(c){l$1.stop(red(`Tracking failed: ${c.message}`));let v=await confirm({message:"Continue with local training anyway?"});if(!v||isCancel(v))return}}let s=u();s.start("Starting local fine-tuning...");try{let l={model:t,trainFile:n,preset:"default",epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await a.finetune(l),s.stop(green("Fine-tuning job started successfully!"));}catch(l){throw s.stop(red("Failed to start job.")),l}}async function Fe(a){let r=await text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});isCancel(r)&&cancel("Operation cancelled");let t=await text({message:"Enter prompt:",placeholder:"Hello world"});isCancel(t)&&cancel("Operation cancelled");let e=u();e.start("Connecting to Langtrain Inference API...");try{let n=await a.generate(r,{prompt:t});e.stop("Generation complete"),w("Response:"),console.log(K.pastel(n));}catch(n){throw e.stop(red("Generation failed.")),n}}async function Ae(a){let r=u();r.start("Fetching fine-tuning jobs...");let e=f().workspace_id;if(!(!e&&(r.stop(yellow("Workspace ID required to list jobs.")),e=await text({message:"Enter Workspace ID:"}),isCancel(e))))try{let n=await a.listJobs(e);if(r.stop(`Found ${n.data.length} jobs`),n.data.length===0){console.log(yellow("No jobs found."));return}let i=q(["ID","Status","Model","Progress","Created"]);n.data.forEach(s=>{let l=s.status==="succeeded"?green:s.status==="failed"?red:yellow;i.push([s.id.substring(0,8)+"...",l(s.status),s.base_model,(s.progress||0)+"%",new Date(s.created_at).toLocaleDateString()]);}),console.log(i.toString()),console.log("");let o=await select({message:"Select a job to view details:",options:n.data.map(s=>({value:s.id,label:`${s.name||s.id} (${s.status})`,hint:`Created: ${new Date(s.created_at).toLocaleDateString()}`}))});if(isCancel(o))return;await Ie(a,o);}catch(n){r.stop(red(`Failed to list jobs: ${n.message}`));}}async function Ie(a,r){let t=r;if(!t&&(t=await text({message:"Enter Job ID:"}),isCancel(t)))return;let e=u();e.start(`Fetching status for ${t}...`);try{let n=await a.getJob(t);if(e.stop(`Job Status: ${n.status.toUpperCase()}`),console.log(gray("------------------------------------------------")),console.log(`${bgMagenta(black(" Job Details "))}`),console.log(`ID: ${n.id}`),console.log(`Name: ${n.name}`),console.log(`Status: ${n.status==="succeeded"?green(n.status):n.status}`),console.log(`Model: ${n.base_model}`),console.log(`Progress: ${n.progress||0}%`),n.error_message&&console.log(red(`Error: ${n.error_message}`)),console.log(gray("------------------------------------------------")),n.status==="running"||n.status==="queued"){let i=await select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});i==="refresh"&&await Ie(a,t),i==="cancel"&&await Ye(a,t);}}catch(n){e.stop(red(`Failed to get job status: ${n.message}`));}}async function Ye(a,r){let t=await confirm({message:"Are you sure you want to cancel this job?"});if(!t||isCancel(t))return;let e=u();e.start("Canceling job...");try{await a.cancelJob(r),e.stop(green("Job canceled successfully."));}catch(n){e.stop(red(`Failed to cancel job: ${n.message}`));}}$();I();r();async function Le(a,r){let t="",e=u();e.start("Fetching available vision models...");try{let l=await r.list("vision");e.stop(`Found ${l.length} vision models`),l.length>0?t=await select({message:"Select base vision model:",options:l.map(c=>({value:c.id,label:c.id,hint:c.owned_by}))}):t=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{e.stop(yellow("Failed to fetch models. Using manual input.")),t=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}isCancel(t)&&(cancel("Operation cancelled"),process.exit(0));let n=await text({message:"Enter dataset path:",placeholder:"./dataset"});isCancel(n)&&cancel("Operation cancelled");let i=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(i)&&cancel("Operation cancelled");let o=await select({message:"Track this job on Langtrain Cloud?",options:[{value:"yes",label:"Yes",hint:"Upload dataset and log job"},{value:"no",label:"No",hint:"Local only"}]});if(isCancel(o)&&cancel("Operation cancelled"),o==="yes"){let l$1=u();l$1.start("Connecting to Cloud...");try{let c=f();if(!c.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new l({apiKey:c.apiKey}).getStatus()).features.includes("cloud_finetuning")){l$1.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let T=await confirm({message:"Upgrade to Pro for cloud tracking?"});T&&!isCancel(T)&&console.log(bgMagenta(black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let S=new j({apiKey:c.apiKey}),j$1=new k({apiKey:c.apiKey});l$1.message("Uploading dataset...");let Q=await S.upload(n,void 0,"fine-tune-vision");l$1.message("Creating Job...");let Z=await j$1.createJob({name:`cli-vision-${Date.now()}`,base_model:t,dataset_id:Q.id,task:"vision",training_method:"lora",hyperparameters:{n_epochs:parseInt(i)}});l$1.stop(green(`Job tracked: ${Z.id}`));}catch(c){l$1.stop(red(`Tracking failed: ${c.message}`));let v=await confirm({message:"Continue with local training anyway?"});if(!v||isCancel(v))return}}let s=u();s.start("Analyzing dataset structure..."),await new Promise(l=>setTimeout(l,800)),s.message("Starting vision fine-tuning on Langtrain Cloud...");try{let l={model:t,dataset:n,epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await a.finetune(l),s.stop(green("Vision fine-tuning started successfully!"));}catch(l){throw s.stop(red("Failed to start vision job.")),l}}async function De(a){let r=await text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});isCancel(r)&&cancel("Operation cancelled");let t=await text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});isCancel(t)&&cancel("Operation cancelled");let e=u();e.start("Uploading image and context..."),await new Promise(n=>setTimeout(n,600)),e.message("Generating vision response...");try{let n=await a.generate(r,{prompt:t});e.stop("Generation complete"),w("Response:"),console.log(K.pastel(n));}catch(n){throw e.stop(red("Generation failed.")),n}}ie();$();I();async function re(){w("Initializing new Langtrain project...");let a=process.cwd();if(G.existsSync(se.join(a,"langtrain.config.json"))){ve("langtrain.config.json already exists in this directory.");let o=await confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(isCancel(o)||!o){_("Initialization cancelled.");return}}let r=await text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:se.basename(a),validate(o){if(!o||o.length===0)return "Project name is required!"}});if(isCancel(r)){cancel("Operation cancelled.");return}let t=f(),e=t.apiKey;if(e)R("Found existing Langtrain credentials.");else {let o=await confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(isCancel(o)){cancel("Operation cancelled.");return}if(o)await J(),t=f(),e=t.apiKey;else if(e=await text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),isCancel(e)){cancel("Operation cancelled.");return}}u().start("Creating configuration...");let i={name:r,apiKey:e||void 0,environment:"development",agents:[{name:"support-bot",description:"A helpful customer support assistant",config:{model:"llama-3-8b",system_prompt:"You are a helpful customer support assistant.",temperature:.7}}]};G.writeFileSync(se.join(a,"langtrain.config.json"),JSON.stringify(i,null,2)),R("Project initialized successfully!"),console.log(F.dim(`
16
+ Next steps:`)),console.log(` 1. Run ${F.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${F.cyan("lt dev")} to start the local development loop.`),_("Happy coding!");}$();I();async function Ee(){w("Running Langtrain Doctor...");let a=u(),r=0;a.start("Checking Node.js environment...");let t=process.version,e=Pe.platform(),n=Pe.arch();parseInt(t.replace("v","").split(".")[0])<18?(a.stop(F.red(`Node.js version ${t} is outdated. Please upgrade to v18+.`)),r++):a.stop(`Node.js ${t} (${e} ${n})`),a.start("Checking configuration...");let i=f();if(!i.apiKey)a.stop(F.yellow("API Key is missing. Run `langtrain login` or set LANGTRAIN_API_KEY.")),r++;else {a.stop("Configuration found."),a.start("Checking API connectivity...");try{let o=await B(i.apiKey);a.stop(`Connected to Langtrain Cloud (Plan: ${F.green(o?.plan||"unknown")})`);}catch(o){a.stop(F.red(`Failed to connect to Langtrain Cloud: ${o.message}`)),r++;}}console.log(""),r===0?R("Your Langtrain environment is healthy! Ready to build."):be(`Found ${r} issue(s). Please resolve them for the best experience.`),_("Doctor check complete.");}le();$();I();async function N(a){w("Deploying configuration to Langtrain Cloud...");let r=f(),t=r.agents||[];if(t.length===0){w(yellow("No agents found in langtrain.config.json"));return}for(let e of t){let n=u();n.start(`Deploying agent: ${e.name}...`);try{let i=await a.list(),o=i.find(s=>s.name===e.name);if(o)n.stop(yellow(`Agent ${e.name} already exists (ID: ${o.id}). Skipping update (not supported yet).`));else {let s={workspace_id:r.workspace_id||i[0]?.workspace_id||"",name:e.name,description:e.description,config:e.config};if(!s.workspace_id){n.stop(red(`Failed: Workspace ID missing in config for ${e.name}`));continue}await a.create(s),n.stop(green(`Agent ${e.name} deployed successfully!`));}}catch(i){n.stop(red(`Failed to deploy ${e.name}: ${i.message}`));}}R("Deployment complete.");}$();async function ce(a){w("Starting Langtrain Development Server...");let r=se.join(process.cwd(),"langtrain.config.json");if(!G.existsSync(r)){w(red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(gray(`Watching ${r} for changes...`));let t=false;await N(a),G.watch(r,async e=>{if(e==="change"&&!t){t=true,console.log(yellow("Configuration changed. Redeploying...")),await new Promise(n=>setTimeout(n,500));try{await N(a);}catch(n){console.error(red(`Deploy failed: ${n.message}`));}finally{t=false,console.log(gray(`Watching ${r}...`));}}}),await new Promise(()=>{});}$();I();r();async function ge(a){let r=f(),t=new q$1({apiKey:r.apiKey||"",baseUrl:r.baseUrl}),e=u();e.start("Fetching guardrails...");try{let n=await t.list();if(e.stop(`Found ${n.length} guardrails`),n.length===0){console.log(yellow('No guardrails found. Create one with "lt guardrails create".'));return}n.forEach(i=>{console.log(green(`\u2022 ${i.name}`)+gray(` (ID: ${i.id})`)),i.description&&console.log(gray(` ${i.description}`)),console.log(gray(` Config: PII=${i.config.pii_enabled}, MinLen=${i.config.min_length}`)),console.log("");});}catch(n){e.stop(red(`Failed to list guardrails: ${n.message}`));}}async function pe(a){let r=f(),t=new q$1({apiKey:r.apiKey||"",baseUrl:r.baseUrl});w("Create a new Data Guardrail");let e=await text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(c){if(!c)return "Name is required"}});if(isCancel(e))return;let n=await text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(isCancel(n))return;let i=await text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(c){if(isNaN(Number(c)))return "Must be a number"}});if(isCancel(i))return;let o=await confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(isCancel(o))return;let s=await text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(isCancel(s))return;let l=u();l.start("Creating guardrail...");try{let c=s.split(",").map(S=>S.trim()).filter(S=>S.length>0),v={name:e,description:n,config:{min_length:Number(i),pii_enabled:o,regex_patterns:c,profanity_enabled:!1}},k=await t.create(v);l.stop(green(`Guardrail "${k.name}" created successfully!`)),console.log(gray(`ID: ${k.id}`));}catch(c){l.stop(red(`Failed to create guardrail: ${c.message}`));}}$();$();I();async function Xe(a){let r=u();r.start("Fetching secrets...");let t=f();try{let e=await a.list(t.workspace_id);if(r.stop(`Found ${e.length} secrets`),e.length===0){console.log(gray('No secrets found. Use "lt env set" to add one.'));return}console.log(gray("------------------------------------------------")),e.forEach(n=>{console.log(`${n.key.padEnd(30)} ${gray("******")}`);}),console.log(gray("------------------------------------------------"));}catch(e){r.stop(red(`Failed to list secrets: ${e.message}`));}}async function et(a,r){let t="",e="";if(t=await text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),isCancel(t)||(e=await text({message:"Secret Value:",placeholder:"sk-..."}),isCancel(e)))return;let n=u();n.start(`Setting ${t}...`);let i=f();try{await a.set(t,e,i.workspace_id),n.stop(green(`Secret ${t} set successfully.`));}catch(o){n.stop(red(`Failed to set secret: ${o.message}`));}}async function ue(a){let r=await select({message:"Manage Secrets",options:[{value:"list",label:"List Secrets"},{value:"set",label:"Set Secret"},{value:"remove",label:"Remove Secret"},{value:"back",label:"Back"}]});if(!(isCancel(r)||r==="back")&&(r==="list"&&await Xe(a),r==="set"&&await et(a),r==="remove")){let t=await text({message:"Key to remove:"});if(!isCancel(t)){let e=u();e.start("Removing...");try{let n=f();await a.delete(t,n.workspace_id),e.stop(green("Removed."));}catch(n){e.stop(red(`Failed: ${n.message}`));}}}}$();$();async function de(a,r){let t=u(),e="";if(r){t.start("Finding agent...");try{let o=(await a.list()).find(s=>s.name===r||s.id===r);if(o)e=o.id;else {t.stop(red(`Agent "${r}" not found.`));return}t.stop(green(`Found agent: ${o.name}`));}catch(i){t.stop(red(`Failed to list agents: ${i.message}`));return}}else {t.start("Fetching agents...");try{let i=await a.list();if(t.stop(`Found ${i.length} agents`),i.length===0){console.log(yellow("No agents found."));return}let o=await select({message:"Select agent to view logs:",options:i.map(s=>({value:s.id,label:s.name}))});if(isCancel(o))return;e=o;}catch(i){t.stop(red(`Failed to list agents: ${i.message}`));return}}let n=u();n.start("Fetching logs...");try{let i=await a.logs(e);n.stop("Logs fetched."),console.log(gray("------------------------------------------------")),console.log(`${bgMagenta(black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(o=>console.log(o)):console.log(gray("(No logs found)")),console.log(gray("------------------------------------------------"));}catch(i){n.stop(red(`Failed to fetch logs: ${i.message}`));}}r();var fe={version:"0.1.20",description:"Unified JavaScript SDK for Langtrain Ecosystem"};async function at(){let a=new Command,r=fe.version;a.name("langtrain").description(fe.description).version(r),a.command("init").description("Initialize a new Langtrain project").action(re),a.command("deploy").description("Deploy configuration to Langtrain Cloud").action(async()=>{let i=f(),o=i.apiKey||"",s=new h({apiKey:o,baseUrl:i.baseUrl});await N(s);}),a.command("dev").description("Start local development server (Watch Mode)").action(async()=>{let i=f(),o=i.apiKey||"",s=new h({apiKey:o,baseUrl:i.baseUrl});await ce(s);}),a.command("env").description("Manage secrets and environment variables").action(async()=>{let i=f(),o$1=i.apiKey||"",s=new o({apiKey:o$1,baseUrl:i.baseUrl});await ue(s);}),a.command("logs [agent]").description("Stream logs from a deployed agent").action(async i=>{let o=f(),s=o.apiKey||"",l=new h({apiKey:s,baseUrl:o.baseUrl});await de(l,i);}),a.action(async()=>{we(r),process.argv.includes("--first-run")&&(process.stdin.isTTY?(w("Welcome to Langtrain! Let's get you set up."),await J()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let o$1=f(),s=o$1.apiKey||"",l=null;if(s)try{l=await B(s);}catch{}let c={vision:new d({apiKey:s}),tune:new f$1({apiKey:s}),agent:new h({apiKey:s,baseUrl:o$1.baseUrl}),model:new m({apiKey:s,baseUrl:o$1.baseUrl}),train:new k({apiKey:s,baseUrl:o$1.baseUrl}),secret:new o({apiKey:s,baseUrl:o$1.baseUrl})},v="main";for(;;){let k$1=await select({message:n(v),options:Se(v,l,!!s)});if(isCancel(k$1))if(v==="main")_("Goodbye!"),process.exit(0);else {v="main";continue}let S=k$1;if(S==="exit"&&(_("Goodbye!"),process.exit(0)),S==="back"){v="main";continue}if(S.startsWith("nav-")){v=S.replace("nav-","");continue}try{switch(S){case "login":await J(),o$1=f(),s=o$1.apiKey||"",c={vision:new d({apiKey:s}),tune:new f$1({apiKey:s}),agent:new h({apiKey:s,baseUrl:o$1.baseUrl}),model:new m({apiKey:s,baseUrl:o$1.baseUrl}),train:new k({apiKey:s,baseUrl:o$1.baseUrl}),secret:new o({apiKey:s,baseUrl:o$1.baseUrl})};try{l=await B(s);}catch{}break;case "status":await xe();break;case "init":await re();break;case "deploy":await N(c.agent);break;case "dev":await ce(c.agent);break;case "env":await ue(c.secret);break;case "logs":await de(c.agent);break;case "doctor":await Ee();break;case "tune-finetune":await ke(c.tune,c.model);break;case "tune-list":await Ae(c.train);break;case "tune-generate":await Fe(c.tune);break;case "vision-finetune":await Le(c.vision,c.model);break;case "vision-generate":await De(c.vision);break;case "agent-list":await _e(c.agent);break;case "agent-create":await Ke(c.agent,c.model);break;case "agent-delete":await Ue(c.agent);break;case "data-upload":await Y(new j({apiKey:s}));break;case "guard-list":await ge(null);break;case "guard-create":await pe(null);break;case "data-refine":await H(new j({apiKey:s}));break}}catch(j){_(F.red(`Error: ${j.message}`));}}});let t=a.command("data").description("Manage datasets");t.command("upload [file]").description("Upload a dataset").action(async i=>{let o=f(),s=o.apiKey||"",l=new j({apiKey:s,baseUrl:o.baseUrl});await Y(l);}),t.command("analyze").description("Analyze a dataset with AI").action(async()=>{let i=f(),o=i.apiKey||"",s=new j({apiKey:o,baseUrl:i.baseUrl}),{handleDataList:l}=(le(),c(je));await l(s);}),t.command("refine [fileId]").description("Refine a dataset using guardrails").action(async i=>{let o=f(),s=o.apiKey||"",l=new j({apiKey:s,baseUrl:o.baseUrl});await H(l,i);});let e=a.command("guardrails").description("Manage data guardrails");e.command("list").description("List available guardrails").action(async()=>{await ge();}),e.command("create").description("Create a new guardrail").action(async()=>{await pe();}),at().catch(console.error);function n(i){switch(i){case "main":return "Main Menu:";case "agents":return "Agents & Tools:";case "text":return "Langtune (Text Operations):";case "vision":return "Langvision (Vision Operations):";case "settings":return "Settings:";default:return "Select an option:"}}}export{at as main};//# sourceMappingURL=cli.mjs.map
15
17
  //# sourceMappingURL=cli.mjs.map