langtrain 0.2.6 → 0.2.9
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/{chunk-WIGKVYUR.mjs → chunk-CWSKNQE4.mjs} +3 -3
- package/dist/chunk-CWSKNQE4.mjs.map +1 -0
- package/dist/{chunk-N6MFB652.js → chunk-JVHUW2HM.js} +3 -3
- package/dist/chunk-JVHUW2HM.js.map +1 -0
- package/dist/cli.js +16 -19
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +16 -19
- package/dist/cli.mjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +3 -3
- package/src/cli/auth.ts +9 -79
- package/src/lib/base.ts +12 -10
- package/dist/chunk-N6MFB652.js.map +0 -1
- package/dist/chunk-WIGKVYUR.mjs.map +0 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {d
|
|
2
|
+
import {d,k,f as f$1,h,a,m,g,i,r,q}from'./chunk-CWSKNQE4.mjs';import {Command}from'commander';import {select,isCancel,confirm,text,cancel,password}from'@clack/prompts';import {dim,white,magenta,blue,bold,cyan,gray,yellow,green,red,black,bgMagenta}from'kleur/colors';import D from'gradient-string';import Ge from'cli-table3';import B from'fs';import ae from'path';import Te from'os';import {exec}from'child_process';import {promisify}from'util';function z(e){return new Ge({head:e.map(o=>A.magenta(A.bold(o))),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"]}})}function W(e){console.clear(),console.log(D(["#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
|
|
@@ -7,26 +7,23 @@ import {d as d$1,k,f as f$1,h,a,m,g,i,r,q as q$1}from'./chunk-WIGKVYUR.mjs';impo
|
|
|
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
9
|
`)),console.log(`${bgMagenta(black(` Langtrain SDK v${e} `))}
|
|
10
|
-
`);}function
|
|
10
|
+
`);}function v(e){console.log(magenta(`\u25C6 ${e}`));}function K(e){console.log(gray(`\u2514 ${e}`));}function u(){return {start:e=>process.stdout.write(`${magenta("\u25CF")} ${e}\r`),stop:e=>{console.log(e?`${green("\u2714")} ${e}`:"");},message:e=>process.stdout.write(`${magenta("\u25CF")} ${e}\r`)}}function T(e){console.log(green(`\u2714 ${e}`));}function be(e){console.log(yellow(`\u26A0 Warning: ${e}`));}function ve(e){console.log(blue(`\u2139 ${e}`));}var A={bgMagenta:bgMagenta,black:black,red:red,green:green,yellow:yellow,gray:gray,cyan:cyan,bold:bold,dim:dim,blue:blue,magenta:magenta,white:white};var Q=ae.join(Te.homedir(),".langtrain"),X=ae.join(Q,"config.json");function f(){if(!B.existsSync(X))return {};try{return JSON.parse(B.readFileSync(X,"utf-8"))}catch{return {}}}function ee(e){B.existsSync(Q)||B.mkdirSync(Q,{recursive:true}),B.writeFileSync(X,JSON.stringify(e,null,2));}promisify(exec);function te(){return !!f().apiKey}async function N(){for(console.log(`
|
|
11
11
|
`+bgMagenta(black(" AUTHENTICATION "))+`
|
|
12
|
-
`),console.log(
|
|
13
|
-
|
|
14
|
-
`),
|
|
15
|
-
|
|
16
|
-
`));
|
|
17
|
-
Browser login failed or timed out. Falling back to manual entry.`));;){console.log(dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(gray(" Get your API Key at: ")+cyan("https://app.langtrain.xyz/home/api")),console.log(dim(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
18
|
-
`));let o=await password({message:"Enter your Langtrain API Key:",validate(t){if(!t||t.length===0)return "API Key is required";if(t.length<10)return "Invalid key format"}});isCancel(o)&&(cancel("Operation cancelled"),process.exit(0));let a=d();a.start("Verifying API Key...");try{let n=await new h({apiKey:o}).getStatus(),i=n.plan==="pro"?bgMagenta(black(" PRO ")):n.plan==="enterprise"?bgMagenta(black(" ENTERPRISE ")):" FREE ";a.stop(green(`Authenticated ${i}`));let s=f();Z({...s,apiKey:o}),console.log(green(` \u2714 Credentials saved to ~/.langtrain/config.json
|
|
19
|
-
`));return}catch{a.stop(red("Invalid API Key. Please try again."));}}}async function ne(){let e=f();delete e.apiKey,Z(e),console.log(green(`
|
|
12
|
+
`),console.log(gray(" To log in, you will need your personal API Key."));;){console.log(dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(gray(" Get your API Key at: ")+cyan("https://app.langtrain.xyz/home/api")),console.log(dim(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
13
|
+
`));let e=await password({message:"Enter your Langtrain API Key:",validate(n){if(!n||n.length===0)return "API Key is required";if(n.length<10)return "Invalid key format"}});isCancel(e)&&(cancel("Login cancelled."),process.exit(0));let o=u();o.start("Verifying API Key...");try{let t=await new h({apiKey:e}).getStatus(),a=t.plan==="pro"?bgMagenta(black(" PRO ")):t.plan==="enterprise"?bgMagenta(black(" ENTERPRISE ")):" FREE ";o.stop(green(`Authenticated ${a}`));let i=f();ee({...i,apiKey:e}),console.log(green(` \u2714 Credentials saved locally. You are now logged in!
|
|
14
|
+
`));return}catch(n){o.stop(red("Invalid API Key.")),n.message&&console.log(red(`
|
|
15
|
+
Server Error: ${n.message}`)),console.log(yellow(` Please ensure your key is valid and you have an active account.
|
|
16
|
+
`));}}}async function ne(){let e=f();delete e.apiKey,ee(e),console.log(green(`
|
|
20
17
|
\u2714 Logged out. Credentials cleared.
|
|
21
|
-
`));}async function
|
|
22
|
-
`)),t}catch(t){return
|
|
23
|
-
Limits:`)),console.log(` Models: ${t.limits.max_models===-1?"Unlimited":t.limits.max_models}`),console.log(` Training Jobs: ${t.limits.max_training_jobs}`);}catch(t){a.stop(red("Failed to fetch status.")),console.error(t.message);}}async function Ae(e,o){let a="",t=d();t.start("Fetching available text models...");try{let c=await o.list("text");t.stop(`Found ${c.length} text models`),c.length>0&&(a=await select({message:"Select base model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}));}catch{t.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(l){if(!l||l.length===0)return "Value is required!"}});}isCancel(a)&&(cancel("Operation cancelled."),process.exit(0));let n=await text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.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 s=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(s)&&cancel("Operation cancelled."),s==="yes"){let c=d();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let M=await confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!isCancel(M)&&console.log(bgMagenta(black(" Visit https://langtrain.xyz/dashboard/billing to upgrade. ")));return}let k=new f$1({apiKey:l.apiKey}),_=new g({apiKey:l.apiKey});c.message("Uploading dataset...");let T=await k.upload(n);c.message("Creating Job...");let G=await _.createJob({name:`cli-sft-${Date.now()}`,base_model:a,dataset_id:T.id,task:"text",hyperparameters:{epochs:parseInt(i)}});c.stop(green(`Job tracked: ${G.id}`));}catch(l){c.stop(red(`Tracking failed: ${l.message}`));let h=await confirm({message:"Continue with local training anyway?"});if(!h||isCancel(h))return}}let r=d();r.start("Starting local fine-tuning...");try{let c={model:a,trainFile:n,preset:"default",epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await e.finetune(c),r.stop(green("Fine-tuning job started successfully!"));}catch(c){throw r.stop(red("Failed to start job.")),c}}async function Fe(e){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 t=d();t.start("Connecting to Langtrain Inference API...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),$("Response:"),console.log(E.pastel(n));}catch(n){throw t.stop(red("Generation failed.")),n}}async function Ie(e){let o=d();o.start("Fetching fine-tuning jobs...");let t=f().workspace_id;if(!(!t&&(o.stop(yellow("Workspace ID required to list jobs.")),t=await text({message:"Enter Workspace ID:"}),isCancel(t))))try{let n=await e.listJobs(t);if(o.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(r=>{let c=r.status==="completed"?green:r.status==="failed"?red:yellow;i.push([r.id.substring(0,8)+"...",c(r.status),r.base_model,(r.progress||0)+"%",new Date(r.created_at).toLocaleDateString()]);}),console.log(i.toString()),console.log("");let s=await select({message:"Select a job to view details:",options:n.data.map(r=>({value:r.id,label:`${r.name||r.id} (${r.status})`,hint:`Created: ${new Date(r.created_at).toLocaleDateString()}`}))});if(isCancel(s))return;await De(e,s);}catch(n){o.stop(red(`Failed to list jobs: ${n.message}`));}}async function De(e,o){let a=o;if(!a&&(a=await text({message:"Enter Job ID:"}),isCancel(a)))return;let t=d();t.start(`Fetching status for ${a}...`);try{let n=await e.getJob(a);if(t.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==="completed"?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==="pending"){let i=await select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});i==="refresh"&&await De(e,a),i==="cancel"&&await Xe(e,a);}}catch(n){t.stop(red(`Failed to get job status: ${n.message}`));}}async function Xe(e,o){let a=await confirm({message:"Are you sure you want to cancel this job?"});if(!a||isCancel(a))return;let t=d();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(green("Job canceled successfully."));}catch(n){t.stop(red(`Failed to cancel job: ${n.message}`));}}async function Ee(e,o){let a="",t=d();t.start("Fetching available vision models...");try{let c=await o.list("vision");t.stop(`Found ${c.length} vision models`),c.length>0?a=await select({message:"Select base vision model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}):a=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.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 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 s=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(s)&&cancel("Operation cancelled"),s==="yes"){let c=d();c.start("Connecting to Cloud...");try{let l=f();if(!l.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let M=await confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!isCancel(M)&&console.log(bgMagenta(black(" Visit https://langtrain.xyz/dashboard/billing to upgrade. ")));return}let k=new f$1({apiKey:l.apiKey}),_=new g({apiKey:l.apiKey});c.message("Uploading dataset...");let T=await k.upload(n,void 0,"fine-tune-vision");c.message("Creating Job...");let G=await _.createJob({name:`cli-vision-${Date.now()}`,base_model:a,dataset_id:T.id,task:"vision",training_method:"lora",hyperparameters:{epochs:parseInt(i)}});c.stop(green(`Job tracked: ${G.id}`));}catch(l){c.stop(red(`Tracking failed: ${l.message}`));let h=await confirm({message:"Continue with local training anyway?"});if(!h||isCancel(h))return}}let r=d();r.start("Analyzing dataset structure..."),await new Promise(c=>setTimeout(c,800)),r.message("Starting vision fine-tuning on Langtrain Cloud...");try{let c={model:a,dataset:n,epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await e.finetune(c),r.stop(green("Vision fine-tuning started successfully!"));}catch(c){throw r.stop(red("Failed to start vision job.")),c}}async function Pe(e){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 t=d();t.start("Uploading image and context..."),await new Promise(n=>setTimeout(n,600)),t.message("Generating vision response...");try{let n=await e.generate(o,{prompt:a});t.stop("Generation complete"),$("Response:"),console.log(E.pastel(n));}catch(n){throw t.stop(red("Generation failed.")),n}}async function Ke(e,o){let a=await text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(isCancel(a)){cancel("Operation cancelled");return}let t=await text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(isCancel(t))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",s=d();s.start("Fetching agent models...");try{let c=await o.list("agent");s.stop(`Found ${c.length} models`),c.length>0&&(i=await select({message:"Select Agent Model:",options:c.map(l=>({value:l.id,label:l.id}))}));}catch{s.stop(yellow("Could not fetch models, using default."));}if(isCancel(i))return;let r=d();r.start("Creating agent...");try{let c=await e.list(),l="";if(c.length>0)l=c[0].workspace_id;else {r.stop(yellow("Workspace ID needed (no existing agents found)."));let b=await text({message:"Enter Workspace ID (UUID):",validate(k){if(!k||k.length===0)return "Required"}});if(isCancel(b))return;l=b,r.start("Creating agent...");}let h=await e.create({workspace_id:l,name:a,description:t,config:{system_prompt:n,model:i}});r.stop(green(`Agent "${h.name}" created successfully! ID: ${h.id}`));}catch(c){throw r.stop(red("Failed to create agent.")),c}}async function _e(e){let o=d();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){$(yellow("No agents to delete."));return}let t=await select({message:"Select an agent to DELETE:",options:a.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(isCancel(t))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"){$(gray("Deletion cancelled."));return}let i=d();i.start("Deleting agent...");try{await e.delete(t),i.stop(green("Agent deleted successfully."));}catch(s){throw i.stop(red("Failed to delete agent.")),s}}async function Te(e){let o=d();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){$(yellow("No agents found in your workspace."));return}let t=q(["ID","Name","Model","Created"]);a.forEach(i=>{t.push([i.id.substring(0,8)+"...",i.name,i.config?.model||"default",new Date(i.created_at).toLocaleDateString()]);}),console.log(t.toString()),console.log("");let n=await select({message:"Select an agent to run:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});isCancel(n)||await Me(e,n,a.find(i=>i.id===n)?.name||"Agent");}async function Me(e,o,a,t){$(bgMagenta(black(` Chatting with ${a} `))),console.log(gray('Type "exit" to quit conversation.'));let n;for(;;){let i=await text({message:"You:",placeholder:"Type a message..."});if(isCancel(i)||i==="exit")break;let s=d();s.start("Agent is thinking...");try{let r=await e.execute(o,{prompt:i},[],n);s.stop(),r.output?.response?console.log(E.pastel(`Agent: ${r.output.response}`)):console.log(E.pastel(`Agent: ${JSON.stringify(r.output)}`)),n=r.conversation_id;}catch(r){s.stop(red("Error running agent.")),console.error(r);}}}async function oe(){$("Initializing new Langtrain project...");let e=process.cwd();if(J.existsSync(ae.join(e,"langtrain.config.json"))){$e("langtrain.config.json already exists in this directory.");let s=await confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(isCancel(s)||!s){K("Initialization cancelled.");return}}let o=await text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(isCancel(o)){cancel("Operation cancelled.");return}let a=f(),t=a.apiKey;if(t)R("Found existing Langtrain credentials.");else {let s=await confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(isCancel(s)){cancel("Operation cancelled.");return}if(s)await O(),a=f(),t=a.apiKey;else if(t=await text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),isCancel(t)){cancel("Operation cancelled.");return}}d().start("Creating configuration...");let i={name:o,apiKey:t||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}}]};J.writeFileSync(ae.join(e,"langtrain.config.json"),JSON.stringify(i,null,2)),R("Project initialized successfully!"),console.log(A.dim(`
|
|
24
|
-
Next steps:`)),console.log(` 1. Run ${A.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${A.cyan("lt dev")} to start the local development loop.`),K("Happy coding!");}async function
|
|
25
|
-
`));return}let
|
|
26
|
-
`)),console.log(` ${dim("Session calls:")} ${
|
|
27
|
-
`));}function
|
|
28
|
-
`));let l
|
|
18
|
+
`));}async function J(e){let o=new h({apiKey:e}),n=u();n.start("Checking subscription...");try{let t=await o.getStatus(),a=t.plan==="pro"?bgMagenta(black(" PRO ")):t.plan==="enterprise"?bgMagenta(black(" ENTERPRISE ")):bold(" FREE ");return n.stop(green(`Plan: ${a}`)),t.is_active===!1&&console.log(yellow(` \u26A0 Subscription inactive. Some features may be limited.
|
|
19
|
+
`)),t}catch(t){return n.stop(red("Failed to verify subscription.")),t.response&&t.response.status===401&&console.log(red(" API Key expired. Please login again.")),null}}function Ce(e,o,n){if(!n)return [{value:"login",label:"\u2192 Login",hint:"Authenticate with your API key"},{value:"docs",label:" Documentation",hint:"https://docs.langtrain.xyz"},{value:"exit",label:" Exit"}];let t=o?.plan==="pro"?"PRO":o?.plan==="enterprise"?"ENTERPRISE":"FREE";switch(e){case "main":return [{value:"nav-agents",label:" Agents",hint:"Manage & deploy AI agents"},{value:"nav-text",label:" Langtune",hint:"Text fine-tuning & generation"},{value:"nav-vision",label:" Langvision",hint:"Vision fine-tuning & analysis"},{value:"nav-guard",label:" Guardrails",hint:"Data quality & safety rules"},{value:"init",label:" Init Project",hint:"Scaffold new Langtrain app"},{value:"deploy",label:" Deploy",hint:"Push to Langtrain Cloud"},{value:"dev",label:" Dev Server",hint:"Local watch mode"},{value:"env",label:" Secrets",hint:"Manage environment variables"},{value:"logs",label:" Logs",hint:"Stream agent logs"},{value:"tokens",label:" Token Usage",hint:"View consumption this period"},{value:"telemetry",label:" Telemetry",hint:"Session stats & API health"},{value:"doctor",label:" Doctor",hint:"Check environment health"},{value:"nav-settings",label:" Settings",hint:`Plan: ${t}`},{value:"exit",label:" Exit"}];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"}];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"}];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"}];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"}];case "settings":return [{value:"status",label:`Subscription (${t})`,hint:"View plan details"},{value:"tokens",label:"Token Usage",hint:"View consumption"},{value:"telemetry",label:"Telemetry",hint:"Session & API health"},{value:"login",label:"Update API Key",hint:"Change credentials"},{value:"logout",label:"Logout",hint:"Clear stored credentials"},{value:"back",label:"\u2190 Back"}];default:return []}}async function ke(){let e=f();if(!e.apiKey){v(red('Not logged in. Run "login" first.'));return}let o=new h({apiKey:e.apiKey}),n=u();n.start("Fetching subscription status...");try{let t=await o.getStatus();n.stop(green("Subscription Status:")),console.log(gray("Plan: ")+(t.plan==="pro"?bgMagenta(" PRO "):t.plan.toUpperCase())),console.log(gray("Active: ")+(t.is_active?green("Yes"):red("No"))),t.expires_at&&console.log(gray("Expires: ")+new Date(t.expires_at).toLocaleDateString()),console.log(gray(`
|
|
20
|
+
Limits:`)),console.log(` Models: ${t.limits.max_models===-1?"Unlimited":t.limits.max_models}`),console.log(` Training Jobs: ${t.limits.max_training_jobs}`);}catch(t){n.stop(red("Failed to fetch status.")),console.error(t.message);}}async function Se(e,o){let n="",t=u();t.start("Fetching available text models...");try{let c=await o.list("text");t.stop(`Found ${c.length} text models`),c.length>0&&(n=await select({message:"Select base model:",options:c.map(r=>({value:r.id,label:r.id,hint:r.owned_by}))}));}catch{t.stop(yellow("Failed to fetch models. Using manual input.")),n=await text({message:"Enter base model (e.g., gpt-3.5-turbo):",placeholder:"gpt-3.5-turbo",validate(r){if(!r||r.length===0)return "Value is required!"}});}isCancel(n)&&(cancel("Operation cancelled."),process.exit(0));let a=await text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.length===0)return "Value is required!"}});isCancel(a)&&cancel("Operation cancelled.");let i=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(i)&&cancel("Operation cancelled.");let s=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(s)&&cancel("Operation cancelled."),s==="yes"){let c=u();c.start("Connecting to Cloud...");try{let r=f();if(!r.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new h({apiKey:r.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let V=await confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!isCancel(V)&&console.log(bgMagenta(black(" Visit https://langtrain.xyz/dashboard/billing to upgrade. ")));return}let S=new f$1({apiKey:r.apiKey}),M=new g({apiKey:r.apiKey});c.message("Uploading dataset...");let O=await S.upload(a);c.message("Creating Job...");let Y=await M.createJob({name:`cli-sft-${Date.now()}`,base_model:n,dataset_id:O.id,task:"text",hyperparameters:{epochs:parseInt(i)}});c.stop(green(`Job tracked: ${Y.id}`));}catch(r){c.stop(red(`Tracking failed: ${r.message}`));let w=await confirm({message:"Continue with local training anyway?"});if(!w||isCancel(w))return}}let l=u();l.start("Starting local fine-tuning...");try{let c={model:n,trainFile:a,preset:"default",epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./output"};await e.finetune(c),l.stop(green("Fine-tuning job started successfully!"));}catch(c){throw l.stop(red("Failed to start job.")),c}}async function xe(e){let o=await text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});isCancel(o)&&cancel("Operation cancelled");let n=await text({message:"Enter prompt:",placeholder:"Hello world"});isCancel(n)&&cancel("Operation cancelled");let t=u();t.start("Connecting to Langtrain Inference API...");try{let a=await e.generate(o,{prompt:n});t.stop("Generation complete"),v("Response:"),console.log(D.pastel(a));}catch(a){throw t.stop(red("Generation failed.")),a}}async function Ae(e){let o=u();o.start("Fetching fine-tuning jobs...");let t=f().workspace_id;if(!(!t&&(o.stop(yellow("Workspace ID required to list jobs.")),t=await text({message:"Enter Workspace ID:"}),isCancel(t))))try{let a=await e.listJobs(t);if(o.stop(`Found ${a.data.length} jobs`),a.data.length===0){console.log(yellow("No jobs found."));return}let i=z(["ID","Status","Model","Progress","Created"]);a.data.forEach(l=>{let c=l.status==="completed"?green:l.status==="failed"?red:yellow;i.push([l.id.substring(0,8)+"...",c(l.status),l.base_model,(l.progress||0)+"%",new Date(l.created_at).toLocaleDateString()]);}),console.log(i.toString()),console.log("");let s=await select({message:"Select a job to view details:",options:a.data.map(l=>({value:l.id,label:`${l.name||l.id} (${l.status})`,hint:`Created: ${new Date(l.created_at).toLocaleDateString()}`}))});if(isCancel(s))return;await Le(e,s);}catch(a){o.stop(red(`Failed to list jobs: ${a.message}`));}}async function Le(e,o){let n=o;if(!n&&(n=await text({message:"Enter Job ID:"}),isCancel(n)))return;let t=u();t.start(`Fetching status for ${n}...`);try{let a=await e.getJob(n);if(t.stop(`Job Status: ${a.status.toUpperCase()}`),console.log(gray("------------------------------------------------")),console.log(`${bgMagenta(black(" Job Details "))}`),console.log(`ID: ${a.id}`),console.log(`Name: ${a.name}`),console.log(`Status: ${a.status==="completed"?green(a.status):a.status}`),console.log(`Model: ${a.base_model}`),console.log(`Progress: ${a.progress||0}%`),a.error_message&&console.log(red(`Error: ${a.error_message}`)),console.log(gray("------------------------------------------------")),a.status==="running"||a.status==="pending"){let i=await select({message:"Action:",options:[{value:"refresh",label:"Refresh Status"},{value:"cancel",label:"Cancel Job"},{value:"back",label:"Back"}]});i==="refresh"&&await Le(e,n),i==="cancel"&&await We(e,n);}}catch(a){t.stop(red(`Failed to get job status: ${a.message}`));}}async function We(e,o){let n=await confirm({message:"Are you sure you want to cancel this job?"});if(!n||isCancel(n))return;let t=u();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(green("Job canceled successfully."));}catch(a){t.stop(red(`Failed to cancel job: ${a.message}`));}}async function Ie(e,o){let n="",t=u();t.start("Fetching available vision models...");try{let c=await o.list("vision");t.stop(`Found ${c.length} vision models`),c.length>0?n=await select({message:"Select base vision model:",options:c.map(r=>({value:r.id,label:r.id,hint:r.owned_by}))}):n=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.stop(yellow("Failed to fetch models. Using manual input.")),n=await text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}isCancel(n)&&(cancel("Operation cancelled"),process.exit(0));let a=await text({message:"Enter dataset path:",placeholder:"./dataset"});isCancel(a)&&cancel("Operation cancelled");let i=await text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});isCancel(i)&&cancel("Operation cancelled");let s=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(s)&&cancel("Operation cancelled"),s==="yes"){let c=u();c.start("Connecting to Cloud...");try{let r=f();if(!r.apiKey)throw new Error('API Key required. Run "login" first.');if(!(await new h({apiKey:r.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(red('Feature "cloud_finetuning" is not available on your plan.'));let V=await confirm({message:"Upgrade to Pro for cloud tracking?"});V&&!isCancel(V)&&console.log(bgMagenta(black(" Visit https://langtrain.xyz/dashboard/billing to upgrade. ")));return}let S=new f$1({apiKey:r.apiKey}),M=new g({apiKey:r.apiKey});c.message("Uploading dataset...");let O=await S.upload(a,void 0,"fine-tune-vision");c.message("Creating Job...");let Y=await M.createJob({name:`cli-vision-${Date.now()}`,base_model:n,dataset_id:O.id,task:"vision",training_method:"lora",hyperparameters:{epochs:parseInt(i)}});c.stop(green(`Job tracked: ${Y.id}`));}catch(r){c.stop(red(`Tracking failed: ${r.message}`));let w=await confirm({message:"Continue with local training anyway?"});if(!w||isCancel(w))return}}let l=u();l.start("Analyzing dataset structure..."),await new Promise(c=>setTimeout(c,800)),l.message("Starting vision fine-tuning on Langtrain Cloud...");try{let c={model:n,dataset:a,epochs:parseInt(i),batchSize:1,learningRate:2e-5,loraRank:16,outputDir:"./vision-output"};await e.finetune(c),l.stop(green("Vision fine-tuning started successfully!"));}catch(c){throw l.stop(red("Failed to start vision job.")),c}}async function Fe(e){let o=await text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});isCancel(o)&&cancel("Operation cancelled");let n=await text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});isCancel(n)&&cancel("Operation cancelled");let t=u();t.start("Uploading image and context..."),await new Promise(a=>setTimeout(a,600)),t.message("Generating vision response...");try{let a=await e.generate(o,{prompt:n});t.stop("Generation complete"),v("Response:"),console.log(D.pastel(a));}catch(a){throw t.stop(red("Generation failed.")),a}}async function De(e,o){let n=await text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(isCancel(n)){cancel("Operation cancelled");return}let t=await text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(isCancel(t))return;let a=await text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(isCancel(a))return;let i="gpt-4o",s=u();s.start("Fetching agent models...");try{let c=await o.list("agent");s.stop(`Found ${c.length} models`),c.length>0&&(i=await select({message:"Select Agent Model:",options:c.map(r=>({value:r.id,label:r.id}))}));}catch{s.stop(yellow("Could not fetch models, using default."));}if(isCancel(i))return;let l=u();l.start("Creating agent...");try{let c=await e.list(),r="";if(c.length>0)r=c[0].workspace_id;else {l.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;r=k,l.start("Creating agent...");}let w=await e.create({workspace_id:r,name:n,description:t,config:{system_prompt:a,model:i}});l.stop(green(`Agent "${w.name}" created successfully! ID: ${w.id}`));}catch(c){throw l.stop(red("Failed to create agent.")),c}}async function Ee(e){let o=u();o.start("Fetching agents...");let n=await e.list();if(o.stop(`Found ${n.length} agents`),n.length===0){v(yellow("No agents to delete."));return}let t=await select({message:"Select an agent to DELETE:",options:n.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(isCancel(t))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"){v(gray("Deletion cancelled."));return}let i=u();i.start("Deleting agent...");try{await e.delete(t),i.stop(green("Agent deleted successfully."));}catch(s){throw i.stop(red("Failed to delete agent.")),s}}async function Pe(e){let o=u();o.start("Fetching agents...");let n=await e.list();if(o.stop(`Found ${n.length} agents`),n.length===0){v(yellow("No agents found in your workspace."));return}let t=z(["ID","Name","Model","Created"]);n.forEach(i=>{t.push([i.id.substring(0,8)+"...",i.name,i.config?.model||"default",new Date(i.created_at).toLocaleDateString()]);}),console.log(t.toString()),console.log("");let a=await select({message:"Select an agent to run:",options:n.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});isCancel(a)||await Ke(e,a,n.find(i=>i.id===a)?.name||"Agent");}async function Ke(e,o,n,t){v(bgMagenta(black(` Chatting with ${n} `))),console.log(gray('Type "exit" to quit conversation.'));let a;for(;;){let i=await text({message:"You:",placeholder:"Type a message..."});if(isCancel(i)||i==="exit")break;let s=u();s.start("Agent is thinking...");try{let l=await e.execute(o,{prompt:i},[],a);s.stop(),l.output?.response?console.log(D.pastel(`Agent: ${l.output.response}`)):console.log(D.pastel(`Agent: ${JSON.stringify(l.output)}`)),a=l.conversation_id;}catch(l){s.stop(red("Error running agent.")),console.error(l);}}}async function oe(){v("Initializing new Langtrain project...");let e=process.cwd();if(B.existsSync(ae.join(e,"langtrain.config.json"))){ve("langtrain.config.json already exists in this directory.");let s=await confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(isCancel(s)||!s){K("Initialization cancelled.");return}}let o=await text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(isCancel(o)){cancel("Operation cancelled.");return}let n=f(),t=n.apiKey;if(t)T("Found existing Langtrain credentials.");else {let s=await confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(isCancel(s)){cancel("Operation cancelled.");return}if(s)await N(),n=f(),t=n.apiKey;else if(t=await text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),isCancel(t)){cancel("Operation cancelled.");return}}u().start("Creating configuration...");let i={name:o,apiKey:t||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}}]};B.writeFileSync(ae.join(e,"langtrain.config.json"),JSON.stringify(i,null,2)),T("Project initialized successfully!"),console.log(A.dim(`
|
|
21
|
+
Next steps:`)),console.log(` 1. Run ${A.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${A.cyan("lt dev")} to start the local development loop.`),K("Happy coding!");}async function _e(){v("Running Langtrain Doctor...");let e=u(),o=0;e.start("Checking Node.js environment...");let n=process.version,t=Te.platform(),a=Te.arch();parseInt(n.replace("v","").split(".")[0])<18?(e.stop(A.red(`Node.js version ${n} is outdated. Please upgrade to v18+.`)),o++):e.stop(`Node.js ${n} (${t} ${a})`),e.start("Checking configuration...");let i=f();if(!i.apiKey)e.stop(A.yellow("API Key is missing. Run `langtrain login` or set LANGTRAIN_API_KEY.")),o++;else {e.stop("Configuration found."),e.start("Checking API connectivity...");try{let s=await J(i.apiKey);e.stop(`Connected to Langtrain Cloud (Plan: ${A.green(s?.plan||"unknown")})`);}catch(s){e.stop(A.red(`Failed to connect to Langtrain Cloud: ${s.message}`)),o++;}}console.log(""),o===0?T("Your Langtrain environment is healthy! Ready to build."):be(`Found ${o} issue(s). Please resolve them for the best experience.`),K("Doctor check complete.");}async function ie(e){let n=f().workspace_id,t=await text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(s){if(!s)return "Required";if(!B.existsSync(s))return "File not found"}});if(isCancel(t))return;let a=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(a))return;let i=u();i.start("Uploading file...");try{let s=await e.upload(t,n,a);i.stop(green("File uploaded successfully!")),console.log(gray(`ID: ${s.id}`)),console.log(gray(`Name: ${s.filename}`)),console.log(gray(`Bytes: ${s.bytes}`));}catch(s){i.stop(red(`Upload failed: ${s.message}`));}}async function se(e,o){let n=f(),t=new m({apiKey:n.apiKey||"",baseUrl:n.baseUrl});if(!o){let l=u();l.start("Fetching files...");try{let c=n.workspace_id||"",r=await e.list(c);if(l.stop(`Found ${r.length} files`),r.length===0){console.log(yellow("No files found. Upload one first."));return}let w=await select({message:"Select file to refine:",options:r.map(k=>({value:k.id,label:`${k.filename} (${He(k.bytes)})`}))});if(isCancel(w))return;o=w;}catch(c){l.stop(red(`Failed to fetch files: ${c.message}`));return}}let a=u();a.start("Fetching guardrails...");let i="";try{let l=await t.list();if(a.stop(`Found ${l.length} guardrails`),l.length===0){console.log(yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let c=await select({message:"Select a Guardrail to apply:",options:l.map(r=>({value:r.id,label:r.name,hint:r.description}))});if(isCancel(c))return;i=c;}catch(l){a.stop(red(`Failed to fetch guardrails: ${l.message}`));return}let s=u();s.start("Applying guardrail (filtering dataset)...");try{let l=await t.apply(o,i);s.stop(green("Dataset refined successfully!")),console.log(gray("Stats:")),console.log(`Original Rows: ${l.original_rows}`),console.log(`Filtered Rows: ${l.filtered_rows}`),console.log(red(`Removed: ${l.removed_rows} rows`)),console.log(green(`New Dataset ID: ${l.new_dataset_id}`));}catch(l){s.stop(red(`Failed to refine dataset: ${l.message}`));}}function He(e,o=2){if(!+e)return "0 Bytes";let n=1024,t=o<0?0:o,a=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(e)/Math.log(n));return `${parseFloat((e/Math.pow(n,i)).toFixed(t))} ${a[i]}`}async function j(e){v("Deploying configuration to Langtrain Cloud...");let o=f(),n=o.agents||[];if(n.length===0){v(yellow("No agents found in langtrain.config.json"));return}for(let t of n){let a=u();a.start(`Deploying agent: ${t.name}...`);try{let i=await e.list(),s=i.find(l=>l.name===t.name);if(s)a.stop(yellow(`Agent ${t.name} already exists (ID: ${s.id}). Skipping update (not supported yet).`));else {let l={workspace_id:o.workspace_id||i[0]?.workspace_id||"",name:t.name,description:t.description,config:t.config};if(!l.workspace_id){a.stop(red(`Failed: Workspace ID missing in config for ${t.name}`));continue}await e.create(l),a.stop(green(`Agent ${t.name} deployed successfully!`));}}catch(i){a.stop(red(`Failed to deploy ${t.name}: ${i.message}`));}}T("Deployment complete.");}async function re(e){v("Starting Langtrain Development Server...");let o=ae.join(process.cwd(),"langtrain.config.json");if(!B.existsSync(o)){v(red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(gray(`Watching ${o} for changes...`));let n=false;await j(e),B.watch(o,async t=>{if(t==="change"&&!n){n=true,console.log(yellow("Configuration changed. Redeploying...")),await new Promise(a=>setTimeout(a,500));try{await j(e);}catch(a){console.error(red(`Deploy failed: ${a.message}`));}finally{n=false,console.log(gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}async function le(e){let o=f(),n=new m({apiKey:o.apiKey||"",baseUrl:o.baseUrl}),t=u();t.start("Fetching guardrails...");try{let a=await n.list();if(t.stop(`Found ${a.length} guardrails`),a.length===0){console.log(yellow('No guardrails found. Create one with "lt guardrails create".'));return}a.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(a){t.stop(red(`Failed to list guardrails: ${a.message}`));}}async function ce(e){let o=f(),n=new m({apiKey:o.apiKey||"",baseUrl:o.baseUrl});v("Create a new Data Guardrail");let t=await text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(r){if(!r)return "Name is required"}});if(isCancel(t))return;let a=await text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(isCancel(a))return;let i=await text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(r){if(isNaN(Number(r)))return "Must be a number"}});if(isCancel(i))return;let s=await confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(isCancel(s))return;let l=await text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(isCancel(l))return;let c=u();c.start("Creating guardrail...");try{let r=l.split(",").map(S=>S.trim()).filter(S=>S.length>0),w={name:t,description:a,config:{min_length:Number(i),pii_enabled:s,regex_patterns:r,profanity_enabled:!1}},k=await n.create(w);c.stop(green(`Guardrail "${k.name}" created successfully!`)),console.log(gray(`ID: ${k.id}`));}catch(r){c.stop(red(`Failed to create guardrail: ${r.message}`));}}async function Qe(e){let o=u();o.start("Fetching secrets...");let n=f();try{let t=await e.list(n.workspace_id);if(o.stop(`Found ${t.length} secrets`),t.length===0){console.log(gray('No secrets found. Use "lt env set" to add one.'));return}console.log(gray("------------------------------------------------")),t.forEach(a=>{console.log(`${a.key.padEnd(30)} ${gray("******")}`);}),console.log(gray("------------------------------------------------"));}catch(t){o.stop(red(`Failed to list secrets: ${t.message}`));}}async function Xe(e,o){let n="",t="";if(n=await text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),isCancel(n)||(t=await text({message:"Secret Value:",placeholder:"sk-..."}),isCancel(t)))return;let a=u();a.start(`Setting ${n}...`);let i=f();try{await e.set(n,t,i.workspace_id),a.stop(green(`Secret ${n} set successfully.`));}catch(s){a.stop(red(`Failed to set secret: ${s.message}`));}}async function ge(e){let o=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(o)||o==="back")&&(o==="list"&&await Qe(e),o==="set"&&await Xe(e),o==="remove")){let n=await text({message:"Key to remove:"});if(!isCancel(n)){let t=u();t.start("Removing...");try{let a=f();await e.delete(n,a.workspace_id),t.stop(green("Removed."));}catch(a){t.stop(red(`Failed: ${a.message}`));}}}}async function pe(e,o){let n=u(),t="";if(o){n.start("Finding agent...");try{let s=(await e.list()).find(l=>l.name===o||l.id===o);if(s)t=s.id;else {n.stop(red(`Agent "${o}" not found.`));return}n.stop(green(`Found agent: ${s.name}`));}catch(i){n.stop(red(`Failed to list agents: ${i.message}`));return}}else {n.start("Fetching agents...");try{let i=await e.list();if(n.stop(`Found ${i.length} agents`),i.length===0){console.log(yellow("No agents found."));return}let s=await select({message:"Select agent to view logs:",options:i.map(l=>({value:l.id,label:l.name}))});if(isCancel(s))return;t=s;}catch(i){n.stop(red(`Failed to list agents: ${i.message}`));return}}let a=u();a.start("Fetching logs...");try{let i=await e.logs(t);a.stop("Logs fetched."),console.log(gray("------------------------------------------------")),console.log(`${bgMagenta(black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(s=>console.log(s)):console.log(gray("(No logs found)")),console.log(gray("------------------------------------------------"));}catch(i){a.stop(red(`Failed to fetch logs: ${i.message}`));}}var et=Date.now(),_=0,Ue=0;async function ue(){let e=f(),o=e.apiKey;if(console.log(""),console.log(bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(bold(" \u2551 TOKEN USAGE \u2551")),console.log(bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),!o){console.log(yellow(` Login required to view token usage.
|
|
22
|
+
`));return}let n=u();n.start("Fetching token usage...");try{let t=a("axios"),a$1=e.baseUrl||"https://api.langtrain.xyz",s=(await t.get(`${a$1}/v1/usage/tokens`,{headers:{Authorization:`Bearer ${o}`}})).data;n.stop(green("Token usage retrieved")),console.log("");let l=s.tokens_used||0,c=s.token_limit||1e4,r=Math.round(l/c*100),w=Math.max(0,c-l),k=30,S=Math.round(r/100*k),M="\u2588".repeat(S)+"\u2591".repeat(k-S),O=r>90?"\x1B[31m":r>70?"\x1B[33m":"\x1B[32m";console.log(` ${dim("Period:")} ${s.period||"Current Month"}`),console.log(` ${dim("Used:")} ${l.toLocaleString()} tokens`),console.log(` ${dim("Limit:")} ${c.toLocaleString()} tokens`),console.log(` ${dim("Remaining:")} ${w.toLocaleString()} tokens`),console.log(` ${dim("Usage:")} ${O}${M}\x1B[0m ${r}%`),console.log(""),s.breakdown&&(console.log(dim(" \u2500\u2500 Breakdown \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${dim("Training:")} ${(s.breakdown.training||0).toLocaleString()}`),console.log(` ${dim("Inference:")} ${(s.breakdown.inference||0).toLocaleString()}`),console.log(` ${dim("Agents:")} ${(s.breakdown.agents||0).toLocaleString()}`),console.log(""));}catch{n.stop(""),console.log(dim(" Token data not available from server.")),console.log(dim(` Showing session estimates:
|
|
23
|
+
`)),console.log(` ${dim("Session calls:")} ${_}`),console.log(` ${dim("Est. tokens:")} ~${_*150}`),console.log("");}}async function Ne(){let e=Date.now()-et,o=Math.round(e/1e3),n=Math.floor(o/60),t=n>0?`${n}m ${o%60}s`:`${o}s`,a$1=0,i=0;console.log(""),console.log(bold(" \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")),console.log(bold(" \u2551 SESSION TELEMETRY \u2551")),console.log(bold(" \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")),console.log(""),console.log(` ${dim("Session:")} ${t}`),console.log(` ${dim("API calls:")} ${_}`),console.log(` ${dim("Avg latency:")} ${a$1}ms`),console.log(` ${dim("Errors:")} ${Ue} (${i}%)`),console.log(""),console.log(dim(" \u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${dim("Node:")} ${process.version}`),console.log(` ${dim("Platform:")} ${process.platform} ${process.arch}`),console.log(` ${dim("Memory:")} ${Math.round(process.memoryUsage().heapUsed/1024/1024)}MB heap`),console.log(` ${dim("Config:")} ~/.langtrain/config.json`),console.log("");let s=f();if(s.apiKey){let l=u();l.start("Pinging API...");try{let c=a("axios"),r=s.baseUrl||"https://api.langtrain.xyz",w=Date.now();await c.get(`${r}/health`,{timeout:5e3});let k=Date.now()-w;l.stop(green(`API healthy (${k}ms)`));}catch{l.stop(yellow("API unreachable"));}}console.log("");}var je={version:"0.2.9"};function Oe(e){let{dim:o,green:n,yellow:t,cyan:a,bold:i,gray:s}=A,l=e?.plan==="pro"?i(n("PRO")):e?.plan==="enterprise"?i(n("ENTERPRISE")):o("FREE"),c=e?.usage?.tokensUsedThisMonth||0,r=e?.usage?.tokenLimit||1e4,w=Math.round(c/r*100),k=w>80?t(`${w}%`):n(`${w}%`);console.log(o(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(` ${o("Plan:")} ${l} ${o("\u2502")} ${o("Tokens:")} ${c.toLocaleString()}/${r.toLocaleString()} ${k}`),console.log(o(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
24
|
+
`));}function Ve(e,o){return {vision:new q({apiKey:e}),tune:new r({apiKey:e}),agent:new d({apiKey:e,baseUrl:o}),model:new i({apiKey:e,baseUrl:o}),train:new g({apiKey:e,baseUrl:o}),secret:new k({apiKey:e,baseUrl:o})}}function ot(e){switch(e){case "main":return "What would you like to do?";case "agents":return "Agents:";case "text":return "Langtune (Text):";case "vision":return "Langvision (Vision):";case "guard":return "Guardrails:";case "settings":return "Settings:";default:return "Select an option:"}}async function it(){let e=new Command,o=je.version;e.name("langtrain").description("Langtrain CLI \u2014 Fine-tuning, Agents, and AI Ops").version(o),e.command("init").description("Initialize a new Langtrain project").action(oe),e.command("deploy").description("Deploy configuration to Langtrain Cloud").action(async()=>{let a=f(),i=a.apiKey||"",s=new d({apiKey:i,baseUrl:a.baseUrl});await j(s);}),e.command("dev").description("Start local development server").action(async()=>{let a=f(),i=a.apiKey||"",s=new d({apiKey:i,baseUrl:a.baseUrl});await re(s);}),e.command("env").description("Manage secrets and environment variables").action(async()=>{let a=f(),i=a.apiKey||"",s=new k({apiKey:i,baseUrl:a.baseUrl});await ge(s);}),e.command("logs [agent]").description("Stream logs from a deployed agent").action(async a=>{let i=f(),s=i.apiKey||"",l=new d({apiKey:s,baseUrl:i.baseUrl});await pe(l,a);}),e.command("login").description("Authenticate with your API key").action(async()=>{await N();}),e.command("logout").description("Clear stored credentials").action(async()=>{await ne();}),e.command("tokens").description("View token usage for current period").action(ue);let n=e.command("data").description("Manage datasets");n.command("upload [file]").description("Upload a dataset").action(async()=>{let a=f(),i=new f$1({apiKey:a.apiKey||"",baseUrl:a.baseUrl});await ie(i);}),n.command("refine [fileId]").description("Refine a dataset using guardrails").action(async a=>{let i=f(),s=new f$1({apiKey:i.apiKey||"",baseUrl:i.baseUrl});await se(s,a);});let t=e.command("guardrails").description("Manage data guardrails");t.command("list").description("List available guardrails").action(async()=>await le()),t.command("create").description("Create a new guardrail").action(async()=>await ce()),e.action(async()=>{W(o),process.argv.includes("--first-run")&&(process.stdin.isTTY?(v("Welcome to Langtrain! Let's get you set up."),await N()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let i=f(),s=i.apiKey||"",l=te(),c=null;if(l&&s){try{c=await J(s);}catch{}Oe(c);}else console.log(A.dim(` Not logged in. Only basic options available.
|
|
25
|
+
`));let r=l?Ve(s,i.baseUrl):null,w="main";for(;;){let k=await select({message:ot(w),options:Ce(w,c,l)});if(isCancel(k))if(w==="main")K("Goodbye!"),process.exit(0);else {w="main";continue}let S=k;if(S==="exit"&&(K("Goodbye!"),process.exit(0)),S==="back"){w="main";continue}if(S.startsWith("nav-")){w=S.replace("nav-","");continue}try{switch(S){case "login":if(await N(),i=f(),s=i.apiKey||"",l=te(),l){try{c=await J(s);}catch{}r=Ve(s,i.baseUrl),console.clear(),W(o),Oe(c);}break;case "logout":await ne(),s="",l=!1,c=null,r=null,console.clear(),W(o),console.log(A.dim(` Logged out. Only basic options available.
|
|
29
26
|
`));break;case "docs":console.log(A.cyan(`
|
|
30
27
|
\u{1F4D6} https://docs.langtrain.xyz
|
|
31
|
-
`));break;case "status":await
|
|
28
|
+
`));break;case "status":await ke();break;case "tokens":await ue();break;case "telemetry":await Ne();break;case "doctor":await _e();break;case "init":await oe();break;case "deploy":r&&await j(r.agent);break;case "dev":r&&await re(r.agent);break;case "env":r&&await ge(r.secret);break;case "logs":r&&await pe(r.agent);break;case "tune-finetune":r&&await Se(r.tune,r.model);break;case "tune-list":r&&await Ae(r.train);break;case "tune-generate":r&&await xe(r.tune);break;case "vision-finetune":r&&await Ie(r.vision,r.model);break;case "vision-generate":r&&await Fe(r.vision);break;case "agent-list":r&&await Pe(r.agent);break;case "agent-create":r&&await De(r.agent,r.model);break;case "agent-delete":r&&await Ee(r.agent);break;case "data-upload":s&&await ie(new f$1({apiKey:s}));break;case "data-refine":s&&await se(new f$1({apiKey:s}));break;case "guard-list":await le(null);break;case "guard-create":await ce(null);break}}catch(M){K(A.red(`Error: ${M.message}`));}}}),e.parse(process.argv);}it().catch(console.error);export{it as main};//# sourceMappingURL=cli.mjs.map
|
|
32
29
|
//# sourceMappingURL=cli.mjs.map
|