langtrain 0.2.2 → 0.2.4
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.js +12 -12
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +12 -12
- package/dist/cli.mjs.map +1 -1
- package/package.json +1 -2
- package/src/cli/auth.ts +8 -3
- package/src/cli/index.ts +3 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var chunkK5LXUJ4G_js=require('./chunk-K5LXUJ4G.js'),commander=require('commander'),prompts=require('@clack/prompts'),colors=require('kleur/colors'),E=require('gradient-string'),qe=require('cli-table3'),J=require('fs'),ae=require('path'),Ue=require('os'),ke=require('axios'),child_process=require('child_process'),util=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var E__default=/*#__PURE__*/_interopDefault(E);var qe__default=/*#__PURE__*/_interopDefault(qe);var J__default=/*#__PURE__*/_interopDefault(J);var ae__default=/*#__PURE__*/_interopDefault(ae);var Ue__default=/*#__PURE__*/_interopDefault(Ue);var ke__default=/*#__PURE__*/_interopDefault(ke);function z(e){return new qe__default.default({head:e.map(o=>
|
|
2
|
+
'use strict';var chunkK5LXUJ4G_js=require('./chunk-K5LXUJ4G.js'),commander=require('commander'),prompts=require('@clack/prompts'),colors=require('kleur/colors'),E=require('gradient-string'),qe=require('cli-table3'),J=require('fs'),ae=require('path'),Ue=require('os'),ke=require('axios'),child_process=require('child_process'),util=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var E__default=/*#__PURE__*/_interopDefault(E);var qe__default=/*#__PURE__*/_interopDefault(qe);var J__default=/*#__PURE__*/_interopDefault(J);var ae__default=/*#__PURE__*/_interopDefault(ae);var Ue__default=/*#__PURE__*/_interopDefault(Ue);var ke__default=/*#__PURE__*/_interopDefault(ke);function z(e){return new qe__default.default({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 H(e){console.clear(),console.log(E__default.default(["#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,26 @@
|
|
|
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(`${colors.bgMagenta(colors.black(` Langtrain SDK v${e} `))}
|
|
10
|
-
`);}function $(e){console.log(colors.magenta(`\u25C6 ${e}`));}function
|
|
10
|
+
`);}function $(e){console.log(colors.magenta(`\u25C6 ${e}`));}function K(e){console.log(colors.gray(`\u2514 ${e}`));}function d(){return {start:e=>process.stdout.write(`${colors.magenta("\u25CF")} ${e}\r`),stop:e=>{console.log(e?`${colors.green("\u2714")} ${e}`:"");},message:e=>process.stdout.write(`${colors.magenta("\u25CF")} ${e}\r`)}}function R(e){console.log(colors.green(`\u2714 ${e}`));}function ve(e){console.log(colors.yellow(`\u26A0 Warning: ${e}`));}function $e(e){console.log(colors.blue(`\u2139 ${e}`));}var A={bgMagenta:colors.bgMagenta,black:colors.black,red:colors.red,green:colors.green,yellow:colors.yellow,gray:colors.gray,cyan:colors.cyan,bold:colors.bold,dim:colors.dim,blue:colors.blue,magenta:colors.magenta,white:colors.white};var X=ae__default.default.join(Ue__default.default.homedir(),".langtrain"),ee=ae__default.default.join(X,"config.json");function f(){if(!J__default.default.existsSync(ee))return {};try{return JSON.parse(J__default.default.readFileSync(ee,"utf-8"))}catch{return {}}}function Z(e){J__default.default.existsSync(X)||J__default.default.mkdirSync(X,{recursive:true}),J__default.default.writeFileSync(ee,JSON.stringify(e,null,2));}var Ze=util.promisify(child_process.exec);function Se(){return `${(f().baseUrl||"https://api.langtrain.ai").replace(/\/$/,"")}/api/v1`}async function Qe(e){try{let o=process.platform==="win32"?`start ${e}`:process.platform==="darwin"?`open "${e}"`:`xdg-open "${e}"`;await Ze(o);}catch{}}function te(){return !!f().apiKey}async function O(){let e=d();e.start("Connecting to Langtrain...");try{let{data:o}=await ke__default.default.post(`${Se()}/auth/device/code`),{device_code:a,user_code:t,verification_url:n,expires_in:i,interval:s}=o;e.stop(colors.green("Connected.")),console.log(`
|
|
11
11
|
`+colors.bgMagenta(colors.black(" AUTHENTICATION "))+`
|
|
12
12
|
`),console.log(` To log in, please open your browser to:
|
|
13
13
|
${colors.cyan(n+"?code="+t)}
|
|
14
14
|
`),prompts.note(`Confirmation Code:
|
|
15
|
-
${colors.bold(t)}`,"Verify in Browser"),console.log(colors.gray(" Opening browser automatically...")),await Qe(`${n}?code=${t}`);let r=d();r.start("Waiting for approval in browser...");let c=Date.now(),l=i*1e3;for(;Date.now()-c<l;)try{let{data:h}=await ke__default.default.post(`${Se}/auth/device/token?device_code=${a}`);if(h.status==="approved"){let b=h.api_key;r.stop(colors.green("Approved!"));let k=d();k.start("Verifying credentials...");let T=await new chunkK5LXUJ4G_js.h({apiKey:b}).getStatus(),G=T.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):T.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):" FREE ";k.stop(colors.green(`Authenticated ${G}`));let M=f();Z({...M,apiKey:b}),console.log(colors.green(` \u2714 Credentials saved to ~/.langtrain/config.json
|
|
15
|
+
${colors.bold(t)}`,"Verify in Browser"),console.log(colors.gray(" Opening browser automatically...")),await Qe(`${n}?code=${t}`);let r=d();r.start("Waiting for approval in browser...");let c=Date.now(),l=i*1e3;for(;Date.now()-c<l;)try{let{data:h}=await ke__default.default.post(`${Se()}/auth/device/token?device_code=${a}`);if(h.status==="approved"){let b=h.api_key;r.stop(colors.green("Approved!"));let k=d();k.start("Verifying credentials...");let T=await new chunkK5LXUJ4G_js.h({apiKey:b}).getStatus(),G=T.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):T.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):" FREE ";k.stop(colors.green(`Authenticated ${G}`));let M=f();Z({...M,apiKey:b}),console.log(colors.green(` \u2714 Credentials saved to ~/.langtrain/config.json
|
|
16
16
|
`));return}if(h.status==="expired"){r.stop(colors.red("Device code expired."));break}await new Promise(b=>setTimeout(b,s*1e3));}catch{await new Promise(b=>setTimeout(b,s*1e3));}r.stop(colors.yellow("Login timed out."));}catch{e.stop(colors.red("Could not reach Langtrain server."));}for(console.log(colors.gray(`
|
|
17
17
|
Browser login failed or timed out. Falling back to manual entry.`));;){console.log(colors.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(colors.gray(" Get your API Key at: ")+colors.cyan("https://app.langtrain.xyz/home/api")),console.log(colors.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
18
|
`));let o=await prompts.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"}});prompts.isCancel(o)&&(prompts.cancel("Operation cancelled"),process.exit(0));let a=d();a.start("Verifying API Key...");try{let n=await new chunkK5LXUJ4G_js.h({apiKey:o}).getStatus(),i=n.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):n.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):" FREE ";a.stop(colors.green(`Authenticated ${i}`));let s=f();Z({...s,apiKey:o}),console.log(colors.green(` \u2714 Credentials saved to ~/.langtrain/config.json
|
|
19
19
|
`));return}catch{a.stop(colors.red("Invalid API Key. Please try again."));}}}async function ne(){let e=f();delete e.apiKey,Z(e),console.log(colors.green(`
|
|
20
20
|
\u2714 Logged out. Credentials cleared.
|
|
21
21
|
`));}async function q(e){let o=new chunkK5LXUJ4G_js.h({apiKey:e}),a=d();a.start("Checking subscription...");try{let t=await o.getStatus(),n=t.plan==="pro"?colors.bgMagenta(colors.black(" PRO ")):t.plan==="enterprise"?colors.bgMagenta(colors.black(" ENTERPRISE ")):colors.bold(" FREE ");return a.stop(colors.green(`Plan: ${n}`)),t.is_active===!1&&console.log(colors.yellow(` \u26A0 Subscription inactive. Some features may be limited.
|
|
22
|
-
`)),t}catch(t){return a.stop(colors.red("Failed to verify subscription.")),t.response&&t.response.status===401&&console.log(colors.red(" API Key expired. Please login again.")),null}}function xe(e,o,a){if(!a)return [{value:"login",label:"\u2192 Login",hint:"Authenticate with your API key"},{value:"docs",label:" Documentation",hint:"https://docs.langtrain.ai"},{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
|
|
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(colors.red("Failed to fetch status.")),console.error(t.message);}}async function Le(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 prompts.select({message:"Select base model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}));}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.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!"}});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled."),process.exit(0));let n=await prompts.text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.length===0)return "Value is required!"}});prompts.isCancel(n)&&prompts.cancel("Operation cancelled.");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled.");let s=await prompts.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(prompts.isCancel(s)&&prompts.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 chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let M=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!prompts.isCancel(M)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let k=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),K=new chunkK5LXUJ4G_js.g({apiKey:l.apiKey});c.message("Uploading dataset...");let T=await k.upload(n);c.message("Creating Job...");let G=await K.createJob({name:`cli-sft-${Date.now()}`,base_model:a,dataset_id:T.id,task:"text",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${G.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let h=await prompts.confirm({message:"Continue with local training anyway?"});if(!h||prompts.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(colors.green("Fine-tuning job started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start job.")),c}}async function Ie(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt:",placeholder:"Hello world"});prompts.isCancel(a)&&prompts.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__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function Fe(e){let o=d();o.start("Fetching fine-tuning jobs...");let t=f().workspace_id;if(!(!t&&(o.stop(colors.yellow("Workspace ID required to list jobs.")),t=await prompts.text({message:"Enter Workspace ID:"}),prompts.isCancel(t))))try{let n=await e.listJobs(t);if(o.stop(`Found ${n.data.length} jobs`),n.data.length===0){console.log(colors.yellow("No jobs found."));return}let i=z(["ID","Status","Model","Progress","Created"]);n.data.forEach(r=>{let c=r.status==="succeeded"?colors.green:r.status==="failed"?colors.red:colors.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 prompts.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(prompts.isCancel(s))return;await De(e,s);}catch(n){o.stop(colors.red(`Failed to list jobs: ${n.message}`));}}async function De(e,o){let a=o;if(!a&&(a=await prompts.text({message:"Enter Job ID:"}),prompts.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(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Job Details "))}`),console.log(`ID: ${n.id}`),console.log(`Name: ${n.name}`),console.log(`Status: ${n.status==="succeeded"?colors.green(n.status):n.status}`),console.log(`Model: ${n.base_model}`),console.log(`Progress: ${n.progress||0}%`),n.error_message&&console.log(colors.red(`Error: ${n.error_message}`)),console.log(colors.gray("------------------------------------------------")),n.status==="running"||n.status==="queued"){let i=await prompts.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(colors.red(`Failed to get job status: ${n.message}`));}}async function Xe(e,o){let a=await prompts.confirm({message:"Are you sure you want to cancel this job?"});if(!a||prompts.isCancel(a))return;let t=d();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(colors.green("Job canceled successfully."));}catch(n){t.stop(colors.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 prompts.select({message:"Select base vision model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}):a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled"),process.exit(0));let n=await prompts.text({message:"Enter dataset path:",placeholder:"./dataset"});prompts.isCancel(n)&&prompts.cancel("Operation cancelled");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled");let s=await prompts.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(prompts.isCancel(s)&&prompts.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 chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let M=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!prompts.isCancel(M)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let k=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),K=new chunkK5LXUJ4G_js.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 K.createJob({name:`cli-vision-${Date.now()}`,base_model:a,dataset_id:T.id,task:"vision",training_method:"lora",hyperparameters:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${G.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let h=await prompts.confirm({message:"Continue with local training anyway?"});if(!h||prompts.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(colors.green("Vision fine-tuning started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start vision job.")),c}}async function Pe(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});prompts.isCancel(a)&&prompts.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__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function _e(e,o){let a=await prompts.text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(prompts.isCancel(a)){prompts.cancel("Operation cancelled");return}let t=await prompts.text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(prompts.isCancel(t))return;let n=await prompts.text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(prompts.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 prompts.select({message:"Select Agent Model:",options:c.map(l=>({value:l.id,label:l.id}))}));}catch{s.stop(colors.yellow("Could not fetch models, using default."));}if(prompts.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(colors.yellow("Workspace ID needed (no existing agents found)."));let b=await prompts.text({message:"Enter Workspace ID (UUID):",validate(k){if(!k||k.length===0)return "Required"}});if(prompts.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(colors.green(`Agent "${h.name}" created successfully! ID: ${h.id}`));}catch(c){throw r.stop(colors.red("Failed to create agent.")),c}}async function Ke(e){let o=d();o.start("Fetching agents...");let a=await e.list();if(o.stop(`Found ${a.length} agents`),a.length===0){$(colors.yellow("No agents to delete."));return}let t=await prompts.select({message:"Select an agent to DELETE:",options:a.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(prompts.isCancel(t))return;if(await prompts.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"){$(colors.gray("Deletion cancelled."));return}let i=d();i.start("Deleting agent...");try{await e.delete(t),i.stop(colors.green("Agent deleted successfully."));}catch(s){throw i.stop(colors.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){$(colors.yellow("No agents found in your workspace."));return}let t=z(["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 prompts.select({message:"Select an agent to run:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});prompts.isCancel(n)||await Me(e,n,a.find(i=>i.id===n)?.name||"Agent");}async function Me(e,o,a,t){$(colors.bgMagenta(colors.black(` Chatting with ${a} `))),console.log(colors.gray('Type "exit" to quit conversation.'));let n;for(;;){let i=await prompts.text({message:"You:",placeholder:"Type a message..."});if(prompts.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__default.default.pastel(`Agent: ${r.output.response}`)):console.log(E__default.default.pastel(`Agent: ${JSON.stringify(r.output)}`)),n=r.conversation_id;}catch(r){s.stop(colors.red("Error running agent.")),console.error(r);}}}async function oe(){$("Initializing new Langtrain project...");let e=process.cwd();if(J__default.default.existsSync(ae__default.default.join(e,"langtrain.config.json"))){$e("langtrain.config.json already exists in this directory.");let s=await prompts.confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(prompts.isCancel(s)||!s){_("Initialization cancelled.");return}}let o=await prompts.text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae__default.default.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(prompts.isCancel(o)){prompts.cancel("Operation cancelled.");return}let a=f(),t=a.apiKey;if(t)R("Found existing Langtrain credentials.");else {let s=await prompts.confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(prompts.isCancel(s)){prompts.cancel("Operation cancelled.");return}if(s)await O(),a=f(),t=a.apiKey;else if(t=await prompts.text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),prompts.isCancel(t)){prompts.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__default.default.writeFileSync(ae__default.default.join(e,"langtrain.config.json"),JSON.stringify(i,null,2)),R("Project initialized successfully!"),console.log(L.dim(`
|
|
24
|
-
Next steps:`)),console.log(` 1. Run ${L.cyan("lt deploy")} to push your agent to the cloud.`),console.log(` 2. Run ${L.cyan("lt dev")} to start the local development loop.`),_("Happy coding!");}async function Ne(){$("Running Langtrain Doctor...");let e=d(),o=0;e.start("Checking Node.js environment...");let a=process.version,t=Ue__default.default.platform(),n=Ue__default.default.arch();parseInt(a.replace("v","").split(".")[0])<18?(e.stop(L.red(`Node.js version ${a} is outdated. Please upgrade to v18+.`)),o++):e.stop(`Node.js ${a} (${t} ${n})`),e.start("Checking configuration...");let i=f();if(!i.apiKey)e.stop(L.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 q(i.apiKey);e.stop(`Connected to Langtrain Cloud (Plan: ${L.green(s?.plan||"unknown")})`);}catch(s){e.stop(L.red(`Failed to connect to Langtrain Cloud: ${s.message}`)),o++;}}console.log(""),o===0?R("Your Langtrain environment is healthy! Ready to build."):ve(`Found ${o} issue(s). Please resolve them for the best experience.`),_("Doctor check complete.");}async function ie(e){let a=f().workspace_id,t=await prompts.text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(s){if(!s)return "Required";if(!J__default.default.existsSync(s))return "File not found"}});if(prompts.isCancel(t))return;let n=await prompts.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(prompts.isCancel(n))return;let i=d();i.start("Uploading file...");try{let s=await e.upload(t,a,n);i.stop(colors.green("File uploaded successfully!")),console.log(colors.gray(`ID: ${s.id}`)),console.log(colors.gray(`Name: ${s.filename}`)),console.log(colors.gray(`Bytes: ${s.bytes}`));}catch(s){i.stop(colors.red(`Upload failed: ${s.message}`));}}async function se(e,o){let a=f(),t=new chunkK5LXUJ4G_js.m({apiKey:a.apiKey||"",baseUrl:a.baseUrl});if(!o){let r=d();r.start("Fetching files...");try{let c=a.workspace_id||"",l=await e.list(c);if(r.stop(`Found ${l.length} files`),l.length===0){console.log(colors.yellow("No files found. Upload one first."));return}let h=await prompts.select({message:"Select file to refine:",options:l.map(b=>({value:b.id,label:`${b.filename} (${tt(b.bytes)})`}))});if(prompts.isCancel(h))return;o=h;}catch(c){r.stop(colors.red(`Failed to fetch files: ${c.message}`));return}}let n=d();n.start("Fetching guardrails...");let i="";try{let r=await t.list();if(n.stop(`Found ${r.length} guardrails`),r.length===0){console.log(colors.yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let c=await prompts.select({message:"Select a Guardrail to apply:",options:r.map(l=>({value:l.id,label:l.name,hint:l.description}))});if(prompts.isCancel(c))return;i=c;}catch(r){n.stop(colors.red(`Failed to fetch guardrails: ${r.message}`));return}let s=d();s.start("Applying guardrail (filtering dataset)...");try{let r=await t.apply(o,i);s.stop(colors.green("Dataset refined successfully!")),console.log(colors.gray("Stats:")),console.log(`Original Rows: ${r.original_rows}`),console.log(`Filtered Rows: ${r.filtered_rows}`),console.log(colors.red(`Removed: ${r.removed_rows} rows`)),console.log(colors.green(`New Dataset ID: ${r.new_dataset_id}`));}catch(r){s.stop(colors.red(`Failed to refine dataset: ${r.message}`));}}function tt(e,o=2){if(!+e)return "0 Bytes";let a=1024,t=o<0?0:o,n=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(e)/Math.log(a));return `${parseFloat((e/Math.pow(a,i)).toFixed(t))} ${n[i]}`}async function V(e){$("Deploying configuration to Langtrain Cloud...");let o=f(),a=o.agents||[];if(a.length===0){$(colors.yellow("No agents found in langtrain.config.json"));return}for(let t of a){let n=d();n.start(`Deploying agent: ${t.name}...`);try{let i=await e.list(),s=i.find(r=>r.name===t.name);if(s)n.stop(colors.yellow(`Agent ${t.name} already exists (ID: ${s.id}). Skipping update (not supported yet).`));else {let r={workspace_id:o.workspace_id||i[0]?.workspace_id||"",name:t.name,description:t.description,config:t.config};if(!r.workspace_id){n.stop(colors.red(`Failed: Workspace ID missing in config for ${t.name}`));continue}await e.create(r),n.stop(colors.green(`Agent ${t.name} deployed successfully!`));}}catch(i){n.stop(colors.red(`Failed to deploy ${t.name}: ${i.message}`));}}R("Deployment complete.");}async function re(e){$("Starting Langtrain Development Server...");let o=ae__default.default.join(process.cwd(),"langtrain.config.json");if(!J__default.default.existsSync(o)){$(colors.red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(colors.gray(`Watching ${o} for changes...`));let a=false;await V(e),J__default.default.watch(o,async t=>{if(t==="change"&&!a){a=true,console.log(colors.yellow("Configuration changed. Redeploying...")),await new Promise(n=>setTimeout(n,500));try{await V(e);}catch(n){console.error(colors.red(`Deploy failed: ${n.message}`));}finally{a=false,console.log(colors.gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}async function le(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl}),t=d();t.start("Fetching guardrails...");try{let n=await a.list();if(t.stop(`Found ${n.length} guardrails`),n.length===0){console.log(colors.yellow('No guardrails found. Create one with "lt guardrails create".'));return}n.forEach(i=>{console.log(colors.green(`\u2022 ${i.name}`)+colors.gray(` (ID: ${i.id})`)),i.description&&console.log(colors.gray(` ${i.description}`)),console.log(colors.gray(` Config: PII=${i.config.pii_enabled}, MinLen=${i.config.min_length}`)),console.log("");});}catch(n){t.stop(colors.red(`Failed to list guardrails: ${n.message}`));}}async function ce(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl});$("Create a new Data Guardrail");let t=await prompts.text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(l){if(!l)return "Name is required"}});if(prompts.isCancel(t))return;let n=await prompts.text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(prompts.isCancel(n))return;let i=await prompts.text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(l){if(isNaN(Number(l)))return "Must be a number"}});if(prompts.isCancel(i))return;let s=await prompts.confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(prompts.isCancel(s))return;let r=await prompts.text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(prompts.isCancel(r))return;let c=d();c.start("Creating guardrail...");try{let l=r.split(",").map(k=>k.trim()).filter(k=>k.length>0),h={name:t,description:n,config:{min_length:Number(i),pii_enabled:s,regex_patterns:l,profanity_enabled:!1}},b=await a.create(h);c.stop(colors.green(`Guardrail "${b.name}" created successfully!`)),console.log(colors.gray(`ID: ${b.id}`));}catch(l){c.stop(colors.red(`Failed to create guardrail: ${l.message}`));}}async function at(e){let o=d();o.start("Fetching secrets...");let a=f();try{let t=await e.list(a.workspace_id);if(o.stop(`Found ${t.length} secrets`),t.length===0){console.log(colors.gray('No secrets found. Use "lt env set" to add one.'));return}console.log(colors.gray("------------------------------------------------")),t.forEach(n=>{console.log(`${n.key.padEnd(30)} ${colors.gray("******")}`);}),console.log(colors.gray("------------------------------------------------"));}catch(t){o.stop(colors.red(`Failed to list secrets: ${t.message}`));}}async function ot(e,o){let a="",t="";if(a=await prompts.text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),prompts.isCancel(a)||(t=await prompts.text({message:"Secret Value:",placeholder:"sk-..."}),prompts.isCancel(t)))return;let n=d();n.start(`Setting ${a}...`);let i=f();try{await e.set(a,t,i.workspace_id),n.stop(colors.green(`Secret ${a} set successfully.`));}catch(s){n.stop(colors.red(`Failed to set secret: ${s.message}`));}}async function ge(e){let o=await prompts.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(!(prompts.isCancel(o)||o==="back")&&(o==="list"&&await at(e),o==="set"&&await ot(e),o==="remove")){let a=await prompts.text({message:"Key to remove:"});if(!prompts.isCancel(a)){let t=d();t.start("Removing...");try{let n=f();await e.delete(a,n.workspace_id),t.stop(colors.green("Removed."));}catch(n){t.stop(colors.red(`Failed: ${n.message}`));}}}}async function pe(e,o){let a=d(),t="";if(o){a.start("Finding agent...");try{let s=(await e.list()).find(r=>r.name===o||r.id===o);if(s)t=s.id;else {a.stop(colors.red(`Agent "${o}" not found.`));return}a.stop(colors.green(`Found agent: ${s.name}`));}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}else {a.start("Fetching agents...");try{let i=await e.list();if(a.stop(`Found ${i.length} agents`),i.length===0){console.log(colors.yellow("No agents found."));return}let s=await prompts.select({message:"Select agent to view logs:",options:i.map(r=>({value:r.id,label:r.name}))});if(prompts.isCancel(s))return;t=s;}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}let n=d();n.start("Fetching logs...");try{let i=await e.logs(t);n.stop("Logs fetched."),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(s=>console.log(s)):console.log(colors.gray("(No logs found)")),console.log(colors.gray("------------------------------------------------"));}catch(i){n.stop(colors.red(`Failed to fetch logs: ${i.message}`));}}var it=Date.now(),U=0,Oe=0;async function de(){let e=f(),o=e.apiKey;if(console.log(""),console.log(colors.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(colors.bold(" \u2551 TOKEN USAGE \u2551")),console.log(colors.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(colors.yellow(` Login required to view token usage.
|
|
25
|
-
`));return}let a=d();a.start("Fetching token usage...");try{let t=chunkK5LXUJ4G_js.a("axios"),n=e.baseUrl||"https://api.langtrain.xyz",s=(await t.get(`${n}/v1/usage/tokens`,{headers:{Authorization:`Bearer ${o}`}})).data;a.stop(colors.green("Token usage retrieved")),console.log("");let r=s.tokens_used||0,c=s.token_limit||1e4,l=Math.round(r/c*100),h=Math.max(0,c-r),b=30,k=Math.round(l/100*b),
|
|
26
|
-
`)),console.log(` ${colors.dim("Session calls:")} ${U}`),console.log(` ${colors.dim("Est. tokens:")} ~${U*150}`),console.log("");}}async function Ve(){let e=Date.now()-it,o=Math.round(e/1e3),a=Math.floor(o/60),t=a>0?`${a}m ${o%60}s`:`${o}s`,n=0,i=0;console.log(""),console.log(colors.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(colors.bold(" \u2551 SESSION TELEMETRY \u2551")),console.log(colors.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(` ${colors.dim("Session:")} ${t}`),console.log(` ${colors.dim("API calls:")} ${U}`),console.log(` ${colors.dim("Avg latency:")} ${n}ms`),console.log(` ${colors.dim("Errors:")} ${Oe} (${i}%)`),console.log(""),console.log(colors.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(` ${colors.dim("Node:")} ${process.version}`),console.log(` ${colors.dim("Platform:")} ${process.platform} ${process.arch}`),console.log(` ${colors.dim("Memory:")} ${Math.round(process.memoryUsage().heapUsed/1024/1024)}MB heap`),console.log(` ${colors.dim("Config:")} ~/.langtrain/config.json`),console.log("");let s=f();if(s.apiKey){let r=d();r.start("Pinging API...");try{let c=chunkK5LXUJ4G_js.a("axios"),l=s.baseUrl||"https://api.langtrain.xyz",h=Date.now();await c.get(`${l}/health`,{timeout:5e3});let b=Date.now()-h;r.stop(colors.green(`API healthy (${b}ms)`));}catch{r.stop(colors.yellow("API unreachable"));}}console.log("");}var Ge={version:"0.2.
|
|
27
|
-
`));}function Je(e,o){return {vision:new chunkK5LXUJ4G_js.q({apiKey:e}),tune:new chunkK5LXUJ4G_js.r({apiKey:e}),agent:new chunkK5LXUJ4G_js.d({apiKey:e,baseUrl:o}),model:new chunkK5LXUJ4G_js.i({apiKey:e,baseUrl:o}),train:new chunkK5LXUJ4G_js.g({apiKey:e,baseUrl:o}),secret:new chunkK5LXUJ4G_js.k({apiKey:e,baseUrl:o})}}function ct(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 gt(){let e=new commander.Command,o=Ge.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 n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await V(s);}),e.command("dev").description("Start local development server").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await re(s);}),e.command("env").description("Manage secrets and environment variables").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.k({apiKey:i,baseUrl:n.baseUrl});await ge(s);}),e.command("logs [agent]").description("Stream logs from a deployed agent").action(async n=>{let i=f(),s=i.apiKey||"",r=new chunkK5LXUJ4G_js.d({apiKey:s,baseUrl:i.baseUrl});await pe(r,n);}),e.command("login").description("Authenticate with your API key").action(async()=>{await O();}),e.command("logout").description("Clear stored credentials").action(async()=>{await ne();}),e.command("tokens").description("View token usage for current period").action(de);let a=e.command("data").description("Manage datasets");a.command("upload [file]").description("Upload a dataset").action(async()=>{let n=f(),i=new chunkK5LXUJ4G_js.f({apiKey:n.apiKey||"",baseUrl:n.baseUrl});await ie(i);}),a.command("refine [fileId]").description("Refine a dataset using guardrails").action(async n=>{let i=f(),s=new chunkK5LXUJ4G_js.f({apiKey:i.apiKey||"",baseUrl:i.baseUrl});await se(s,n);});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()=>{H(o),process.argv.includes("--first-run")&&(process.stdin.isTTY?($("Welcome to Langtrain! Let's get you set up."),await O()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let i=f(),s=i.apiKey||"",r=te(),c=null;if(r&&s){try{c=await q(s);}catch{}Be(c);}else console.log(
|
|
28
|
-
`));let l=r?Je(s,i.baseUrl):null,h="main";for(;;){let b=await prompts.select({message:ct(h),options:xe(h,c,r)});if(prompts.isCancel(b))if(h==="main")
|
|
29
|
-
`));break;case "docs":console.log(
|
|
22
|
+
`)),t}catch(t){return a.stop(colors.red("Failed to verify subscription.")),t.response&&t.response.status===401&&console.log(colors.red(" API Key expired. Please login again.")),null}}function xe(e,o,a){if(!a)return [{value:"login",label:"\u2192 Login",hint:"Authenticate with your API key"},{value:"docs",label:" Documentation",hint:"https://docs.langtrain.ai"},{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 Le(){let e=f();if(!e.apiKey){$(colors.red('Not logged in. Run "login" first.'));return}let o=new chunkK5LXUJ4G_js.h({apiKey:e.apiKey}),a=d();a.start("Fetching subscription status...");try{let t=await o.getStatus();a.stop(colors.green("Subscription Status:")),console.log(colors.gray("Plan: ")+(t.plan==="pro"?colors.bgMagenta(" PRO "):t.plan.toUpperCase())),console.log(colors.gray("Active: ")+(t.is_active?colors.green("Yes"):colors.red("No"))),t.expires_at&&console.log(colors.gray("Expires: ")+new Date(t.expires_at).toLocaleDateString()),console.log(colors.gray(`
|
|
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(colors.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 prompts.select({message:"Select base model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}));}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.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!"}});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled."),process.exit(0));let n=await prompts.text({message:"Enter path to training file:",placeholder:"./data.jsonl",validate(c){if(!c||c.length===0)return "Value is required!"}});prompts.isCancel(n)&&prompts.cancel("Operation cancelled.");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled.");let s=await prompts.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(prompts.isCancel(s)&&prompts.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 chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let M=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!prompts.isCancel(M)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let k=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),_=new chunkK5LXUJ4G_js.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:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${G.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let h=await prompts.confirm({message:"Continue with local training anyway?"});if(!h||prompts.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(colors.green("Fine-tuning job started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start job.")),c}}async function Fe(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./output/model",initialValue:"./output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt:",placeholder:"Hello world"});prompts.isCancel(a)&&prompts.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__default.default.pastel(n));}catch(n){throw t.stop(colors.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(colors.yellow("Workspace ID required to list jobs.")),t=await prompts.text({message:"Enter Workspace ID:"}),prompts.isCancel(t))))try{let n=await e.listJobs(t);if(o.stop(`Found ${n.data.length} jobs`),n.data.length===0){console.log(colors.yellow("No jobs found."));return}let i=z(["ID","Status","Model","Progress","Created"]);n.data.forEach(r=>{let c=r.status==="succeeded"?colors.green:r.status==="failed"?colors.red:colors.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 prompts.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(prompts.isCancel(s))return;await De(e,s);}catch(n){o.stop(colors.red(`Failed to list jobs: ${n.message}`));}}async function De(e,o){let a=o;if(!a&&(a=await prompts.text({message:"Enter Job ID:"}),prompts.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(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Job Details "))}`),console.log(`ID: ${n.id}`),console.log(`Name: ${n.name}`),console.log(`Status: ${n.status==="succeeded"?colors.green(n.status):n.status}`),console.log(`Model: ${n.base_model}`),console.log(`Progress: ${n.progress||0}%`),n.error_message&&console.log(colors.red(`Error: ${n.error_message}`)),console.log(colors.gray("------------------------------------------------")),n.status==="running"||n.status==="queued"){let i=await prompts.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(colors.red(`Failed to get job status: ${n.message}`));}}async function Xe(e,o){let a=await prompts.confirm({message:"Are you sure you want to cancel this job?"});if(!a||prompts.isCancel(a))return;let t=d();t.start("Canceling job...");try{await e.cancelJob(o),t.stop(colors.green("Job canceled successfully."));}catch(n){t.stop(colors.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 prompts.select({message:"Select base vision model:",options:c.map(l=>({value:l.id,label:l.id,hint:l.owned_by}))}):a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}catch{t.stop(colors.yellow("Failed to fetch models. Using manual input.")),a=await prompts.text({message:"Enter base vision model:",placeholder:"llava-v1.5-7b",initialValue:"llava-v1.5-7b"});}prompts.isCancel(a)&&(prompts.cancel("Operation cancelled"),process.exit(0));let n=await prompts.text({message:"Enter dataset path:",placeholder:"./dataset"});prompts.isCancel(n)&&prompts.cancel("Operation cancelled");let i=await prompts.text({message:"Num Epochs:",placeholder:"3",initialValue:"3"});prompts.isCancel(i)&&prompts.cancel("Operation cancelled");let s=await prompts.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(prompts.isCancel(s)&&prompts.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 chunkK5LXUJ4G_js.h({apiKey:l.apiKey}).getStatus()).features.includes("cloud_finetuning")){c.stop(colors.red('Feature "cloud_finetuning" is not available on your plan.'));let M=await prompts.confirm({message:"Upgrade to Pro for cloud tracking?"});M&&!prompts.isCancel(M)&&console.log(colors.bgMagenta(colors.black(" Visit https://langtrain.ai/dashboard/billing to upgrade. ")));return}let k=new chunkK5LXUJ4G_js.f({apiKey:l.apiKey}),_=new chunkK5LXUJ4G_js.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:{n_epochs:parseInt(i)}});c.stop(colors.green(`Job tracked: ${G.id}`));}catch(l){c.stop(colors.red(`Tracking failed: ${l.message}`));let h=await prompts.confirm({message:"Continue with local training anyway?"});if(!h||prompts.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(colors.green("Vision fine-tuning started successfully!"));}catch(c){throw r.stop(colors.red("Failed to start vision job.")),c}}async function Pe(e){let o=await prompts.text({message:"Enter model path:",placeholder:"./vision-output/model",initialValue:"./vision-output/model"});prompts.isCancel(o)&&prompts.cancel("Operation cancelled");let a=await prompts.text({message:"Enter prompt/image path:",placeholder:"Describe this image..."});prompts.isCancel(a)&&prompts.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__default.default.pastel(n));}catch(n){throw t.stop(colors.red("Generation failed.")),n}}async function Ke(e,o){let a=await prompts.text({message:"Agent Name:",placeholder:"e.g. Support Bot",validate(c){if(!c||c.length===0)return "API Key is required"}});if(prompts.isCancel(a)){prompts.cancel("Operation cancelled");return}let t=await prompts.text({message:"Description:",placeholder:"e.g. A helpful support assistant"});if(prompts.isCancel(t))return;let n=await prompts.text({message:"System Prompt:",placeholder:"e.g. You are a helpful assistant.",initialValue:"You are a helpful assistant."});if(prompts.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 prompts.select({message:"Select Agent Model:",options:c.map(l=>({value:l.id,label:l.id}))}));}catch{s.stop(colors.yellow("Could not fetch models, using default."));}if(prompts.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(colors.yellow("Workspace ID needed (no existing agents found)."));let b=await prompts.text({message:"Enter Workspace ID (UUID):",validate(k){if(!k||k.length===0)return "Required"}});if(prompts.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(colors.green(`Agent "${h.name}" created successfully! ID: ${h.id}`));}catch(c){throw r.stop(colors.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){$(colors.yellow("No agents to delete."));return}let t=await prompts.select({message:"Select an agent to DELETE:",options:a.map(s=>({value:s.id,label:s.name,hint:s.description||"No description"}))});if(prompts.isCancel(t))return;if(await prompts.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"){$(colors.gray("Deletion cancelled."));return}let i=d();i.start("Deleting agent...");try{await e.delete(t),i.stop(colors.green("Agent deleted successfully."));}catch(s){throw i.stop(colors.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){$(colors.yellow("No agents found in your workspace."));return}let t=z(["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 prompts.select({message:"Select an agent to run:",options:a.map(i=>({value:i.id,label:i.name,hint:i.description||"No description"}))});prompts.isCancel(n)||await Me(e,n,a.find(i=>i.id===n)?.name||"Agent");}async function Me(e,o,a,t){$(colors.bgMagenta(colors.black(` Chatting with ${a} `))),console.log(colors.gray('Type "exit" to quit conversation.'));let n;for(;;){let i=await prompts.text({message:"You:",placeholder:"Type a message..."});if(prompts.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__default.default.pastel(`Agent: ${r.output.response}`)):console.log(E__default.default.pastel(`Agent: ${JSON.stringify(r.output)}`)),n=r.conversation_id;}catch(r){s.stop(colors.red("Error running agent.")),console.error(r);}}}async function oe(){$("Initializing new Langtrain project...");let e=process.cwd();if(J__default.default.existsSync(ae__default.default.join(e,"langtrain.config.json"))){$e("langtrain.config.json already exists in this directory.");let s=await prompts.confirm({message:"Do you want to re-initialize and overwrite the config?",initialValue:false});if(prompts.isCancel(s)||!s){K("Initialization cancelled.");return}}let o=await prompts.text({message:"What is the name of your project?",placeholder:"my-ai-app",initialValue:ae__default.default.basename(e),validate(s){if(!s||s.length===0)return "Project name is required!"}});if(prompts.isCancel(o)){prompts.cancel("Operation cancelled.");return}let a=f(),t=a.apiKey;if(t)R("Found existing Langtrain credentials.");else {let s=await prompts.confirm({message:"You are not logged in. Do you want to log in now?",initialValue:true});if(prompts.isCancel(s)){prompts.cancel("Operation cancelled.");return}if(s)await O(),a=f(),t=a.apiKey;else if(t=await prompts.text({message:"Enter your Langtrain API Key (optional for local dev):",placeholder:"lt_sk_...",initialValue:""}),prompts.isCancel(t)){prompts.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__default.default.writeFileSync(ae__default.default.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 Ne(){$("Running Langtrain Doctor...");let e=d(),o=0;e.start("Checking Node.js environment...");let a=process.version,t=Ue__default.default.platform(),n=Ue__default.default.arch();parseInt(a.replace("v","").split(".")[0])<18?(e.stop(A.red(`Node.js version ${a} is outdated. Please upgrade to v18+.`)),o++):e.stop(`Node.js ${a} (${t} ${n})`),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 q(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?R("Your Langtrain environment is healthy! Ready to build."):ve(`Found ${o} issue(s). Please resolve them for the best experience.`),K("Doctor check complete.");}async function ie(e){let a=f().workspace_id,t=await prompts.text({message:"Path to file:",placeholder:"./dataset.jsonl",validate(s){if(!s)return "Required";if(!J__default.default.existsSync(s))return "File not found"}});if(prompts.isCancel(t))return;let n=await prompts.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(prompts.isCancel(n))return;let i=d();i.start("Uploading file...");try{let s=await e.upload(t,a,n);i.stop(colors.green("File uploaded successfully!")),console.log(colors.gray(`ID: ${s.id}`)),console.log(colors.gray(`Name: ${s.filename}`)),console.log(colors.gray(`Bytes: ${s.bytes}`));}catch(s){i.stop(colors.red(`Upload failed: ${s.message}`));}}async function se(e,o){let a=f(),t=new chunkK5LXUJ4G_js.m({apiKey:a.apiKey||"",baseUrl:a.baseUrl});if(!o){let r=d();r.start("Fetching files...");try{let c=a.workspace_id||"",l=await e.list(c);if(r.stop(`Found ${l.length} files`),l.length===0){console.log(colors.yellow("No files found. Upload one first."));return}let h=await prompts.select({message:"Select file to refine:",options:l.map(b=>({value:b.id,label:`${b.filename} (${tt(b.bytes)})`}))});if(prompts.isCancel(h))return;o=h;}catch(c){r.stop(colors.red(`Failed to fetch files: ${c.message}`));return}}let n=d();n.start("Fetching guardrails...");let i="";try{let r=await t.list();if(n.stop(`Found ${r.length} guardrails`),r.length===0){console.log(colors.yellow('No guardrails found. Please create one first using "lt guardrails create".'));return}let c=await prompts.select({message:"Select a Guardrail to apply:",options:r.map(l=>({value:l.id,label:l.name,hint:l.description}))});if(prompts.isCancel(c))return;i=c;}catch(r){n.stop(colors.red(`Failed to fetch guardrails: ${r.message}`));return}let s=d();s.start("Applying guardrail (filtering dataset)...");try{let r=await t.apply(o,i);s.stop(colors.green("Dataset refined successfully!")),console.log(colors.gray("Stats:")),console.log(`Original Rows: ${r.original_rows}`),console.log(`Filtered Rows: ${r.filtered_rows}`),console.log(colors.red(`Removed: ${r.removed_rows} rows`)),console.log(colors.green(`New Dataset ID: ${r.new_dataset_id}`));}catch(r){s.stop(colors.red(`Failed to refine dataset: ${r.message}`));}}function tt(e,o=2){if(!+e)return "0 Bytes";let a=1024,t=o<0?0:o,n=["Bytes","KB","MB","GB","TB"],i=Math.floor(Math.log(e)/Math.log(a));return `${parseFloat((e/Math.pow(a,i)).toFixed(t))} ${n[i]}`}async function V(e){$("Deploying configuration to Langtrain Cloud...");let o=f(),a=o.agents||[];if(a.length===0){$(colors.yellow("No agents found in langtrain.config.json"));return}for(let t of a){let n=d();n.start(`Deploying agent: ${t.name}...`);try{let i=await e.list(),s=i.find(r=>r.name===t.name);if(s)n.stop(colors.yellow(`Agent ${t.name} already exists (ID: ${s.id}). Skipping update (not supported yet).`));else {let r={workspace_id:o.workspace_id||i[0]?.workspace_id||"",name:t.name,description:t.description,config:t.config};if(!r.workspace_id){n.stop(colors.red(`Failed: Workspace ID missing in config for ${t.name}`));continue}await e.create(r),n.stop(colors.green(`Agent ${t.name} deployed successfully!`));}}catch(i){n.stop(colors.red(`Failed to deploy ${t.name}: ${i.message}`));}}R("Deployment complete.");}async function re(e){$("Starting Langtrain Development Server...");let o=ae__default.default.join(process.cwd(),"langtrain.config.json");if(!J__default.default.existsSync(o)){$(colors.red('langtrain.config.json not found. Run "lt init" first.'));return}console.log(colors.gray(`Watching ${o} for changes...`));let a=false;await V(e),J__default.default.watch(o,async t=>{if(t==="change"&&!a){a=true,console.log(colors.yellow("Configuration changed. Redeploying...")),await new Promise(n=>setTimeout(n,500));try{await V(e);}catch(n){console.error(colors.red(`Deploy failed: ${n.message}`));}finally{a=false,console.log(colors.gray(`Watching ${o}...`));}}}),await new Promise(()=>{});}async function le(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl}),t=d();t.start("Fetching guardrails...");try{let n=await a.list();if(t.stop(`Found ${n.length} guardrails`),n.length===0){console.log(colors.yellow('No guardrails found. Create one with "lt guardrails create".'));return}n.forEach(i=>{console.log(colors.green(`\u2022 ${i.name}`)+colors.gray(` (ID: ${i.id})`)),i.description&&console.log(colors.gray(` ${i.description}`)),console.log(colors.gray(` Config: PII=${i.config.pii_enabled}, MinLen=${i.config.min_length}`)),console.log("");});}catch(n){t.stop(colors.red(`Failed to list guardrails: ${n.message}`));}}async function ce(e){let o=f(),a=new chunkK5LXUJ4G_js.m({apiKey:o.apiKey||"",baseUrl:o.baseUrl});$("Create a new Data Guardrail");let t=await prompts.text({message:"Guardrail Name:",placeholder:"e.g. Strict Safety Policy",validate(l){if(!l)return "Name is required"}});if(prompts.isCancel(t))return;let n=await prompts.text({message:"Description (optional):",placeholder:"Filters PII and short text"});if(prompts.isCancel(n))return;let i=await prompts.text({message:"Minimum Text Length (0 for no limit):",initialValue:"0",validate(l){if(isNaN(Number(l)))return "Must be a number"}});if(prompts.isCancel(i))return;let s=await prompts.confirm({message:"Enable PII Filtering (Email/Phone)?",initialValue:false});if(prompts.isCancel(s))return;let r=await prompts.text({message:"Regex Patterns to Block (comma separated, optional):",placeholder:"e.g. bad_word, another_one"});if(prompts.isCancel(r))return;let c=d();c.start("Creating guardrail...");try{let l=r.split(",").map(k=>k.trim()).filter(k=>k.length>0),h={name:t,description:n,config:{min_length:Number(i),pii_enabled:s,regex_patterns:l,profanity_enabled:!1}},b=await a.create(h);c.stop(colors.green(`Guardrail "${b.name}" created successfully!`)),console.log(colors.gray(`ID: ${b.id}`));}catch(l){c.stop(colors.red(`Failed to create guardrail: ${l.message}`));}}async function at(e){let o=d();o.start("Fetching secrets...");let a=f();try{let t=await e.list(a.workspace_id);if(o.stop(`Found ${t.length} secrets`),t.length===0){console.log(colors.gray('No secrets found. Use "lt env set" to add one.'));return}console.log(colors.gray("------------------------------------------------")),t.forEach(n=>{console.log(`${n.key.padEnd(30)} ${colors.gray("******")}`);}),console.log(colors.gray("------------------------------------------------"));}catch(t){o.stop(colors.red(`Failed to list secrets: ${t.message}`));}}async function ot(e,o){let a="",t="";if(a=await prompts.text({message:"Secret Key:",placeholder:"OPENAI_API_KEY"}),prompts.isCancel(a)||(t=await prompts.text({message:"Secret Value:",placeholder:"sk-..."}),prompts.isCancel(t)))return;let n=d();n.start(`Setting ${a}...`);let i=f();try{await e.set(a,t,i.workspace_id),n.stop(colors.green(`Secret ${a} set successfully.`));}catch(s){n.stop(colors.red(`Failed to set secret: ${s.message}`));}}async function ge(e){let o=await prompts.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(!(prompts.isCancel(o)||o==="back")&&(o==="list"&&await at(e),o==="set"&&await ot(e),o==="remove")){let a=await prompts.text({message:"Key to remove:"});if(!prompts.isCancel(a)){let t=d();t.start("Removing...");try{let n=f();await e.delete(a,n.workspace_id),t.stop(colors.green("Removed."));}catch(n){t.stop(colors.red(`Failed: ${n.message}`));}}}}async function pe(e,o){let a=d(),t="";if(o){a.start("Finding agent...");try{let s=(await e.list()).find(r=>r.name===o||r.id===o);if(s)t=s.id;else {a.stop(colors.red(`Agent "${o}" not found.`));return}a.stop(colors.green(`Found agent: ${s.name}`));}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}else {a.start("Fetching agents...");try{let i=await e.list();if(a.stop(`Found ${i.length} agents`),i.length===0){console.log(colors.yellow("No agents found."));return}let s=await prompts.select({message:"Select agent to view logs:",options:i.map(r=>({value:r.id,label:r.name}))});if(prompts.isCancel(s))return;t=s;}catch(i){a.stop(colors.red(`Failed to list agents: ${i.message}`));return}}let n=d();n.start("Fetching logs...");try{let i=await e.logs(t);n.stop("Logs fetched."),console.log(colors.gray("------------------------------------------------")),console.log(`${colors.bgMagenta(colors.black(" Recent Logs "))}`),i.logs&&i.logs.length>0?i.logs.forEach(s=>console.log(s)):console.log(colors.gray("(No logs found)")),console.log(colors.gray("------------------------------------------------"));}catch(i){n.stop(colors.red(`Failed to fetch logs: ${i.message}`));}}var it=Date.now(),U=0,Oe=0;async function de(){let e=f(),o=e.apiKey;if(console.log(""),console.log(colors.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(colors.bold(" \u2551 TOKEN USAGE \u2551")),console.log(colors.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(colors.yellow(` Login required to view token usage.
|
|
25
|
+
`));return}let a=d();a.start("Fetching token usage...");try{let t=chunkK5LXUJ4G_js.a("axios"),n=e.baseUrl||"https://api.langtrain.xyz",s=(await t.get(`${n}/v1/usage/tokens`,{headers:{Authorization:`Bearer ${o}`}})).data;a.stop(colors.green("Token usage retrieved")),console.log("");let r=s.tokens_used||0,c=s.token_limit||1e4,l=Math.round(r/c*100),h=Math.max(0,c-r),b=30,k=Math.round(l/100*b),_="\u2588".repeat(k)+"\u2591".repeat(b-k),T=l>90?"\x1B[31m":l>70?"\x1B[33m":"\x1B[32m";console.log(` ${colors.dim("Period:")} ${s.period||"Current Month"}`),console.log(` ${colors.dim("Used:")} ${r.toLocaleString()} tokens`),console.log(` ${colors.dim("Limit:")} ${c.toLocaleString()} tokens`),console.log(` ${colors.dim("Remaining:")} ${h.toLocaleString()} tokens`),console.log(` ${colors.dim("Usage:")} ${T}${_}\x1B[0m ${l}%`),console.log(""),s.breakdown&&(console.log(colors.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(` ${colors.dim("Training:")} ${(s.breakdown.training||0).toLocaleString()}`),console.log(` ${colors.dim("Inference:")} ${(s.breakdown.inference||0).toLocaleString()}`),console.log(` ${colors.dim("Agents:")} ${(s.breakdown.agents||0).toLocaleString()}`),console.log(""));}catch{a.stop(""),console.log(colors.dim(" Token data not available from server.")),console.log(colors.dim(` Showing session estimates:
|
|
26
|
+
`)),console.log(` ${colors.dim("Session calls:")} ${U}`),console.log(` ${colors.dim("Est. tokens:")} ~${U*150}`),console.log("");}}async function Ve(){let e=Date.now()-it,o=Math.round(e/1e3),a=Math.floor(o/60),t=a>0?`${a}m ${o%60}s`:`${o}s`,n=0,i=0;console.log(""),console.log(colors.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(colors.bold(" \u2551 SESSION TELEMETRY \u2551")),console.log(colors.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(` ${colors.dim("Session:")} ${t}`),console.log(` ${colors.dim("API calls:")} ${U}`),console.log(` ${colors.dim("Avg latency:")} ${n}ms`),console.log(` ${colors.dim("Errors:")} ${Oe} (${i}%)`),console.log(""),console.log(colors.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(` ${colors.dim("Node:")} ${process.version}`),console.log(` ${colors.dim("Platform:")} ${process.platform} ${process.arch}`),console.log(` ${colors.dim("Memory:")} ${Math.round(process.memoryUsage().heapUsed/1024/1024)}MB heap`),console.log(` ${colors.dim("Config:")} ~/.langtrain/config.json`),console.log("");let s=f();if(s.apiKey){let r=d();r.start("Pinging API...");try{let c=chunkK5LXUJ4G_js.a("axios"),l=s.baseUrl||"https://api.langtrain.xyz",h=Date.now();await c.get(`${l}/health`,{timeout:5e3});let b=Date.now()-h;r.stop(colors.green(`API healthy (${b}ms)`));}catch{r.stop(colors.yellow("API unreachable"));}}console.log("");}var Ge={version:"0.2.4"};function Be(e){let{dim:o,green:a,yellow:t,cyan:n,bold:i,gray:s}=A,r=e?.plan==="pro"?i(a("PRO")):e?.plan==="enterprise"?i(a("ENTERPRISE")):o("FREE"),c=e?.usage?.tokensUsedThisMonth||0,l=e?.usage?.tokenLimit||1e4,h=Math.round(c/l*100),b=h>80?t(`${h}%`):a(`${h}%`);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:")} ${r} ${o("\u2502")} ${o("Tokens:")} ${c.toLocaleString()}/${l.toLocaleString()} ${b}`),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
|
|
27
|
+
`));}function Je(e,o){return {vision:new chunkK5LXUJ4G_js.q({apiKey:e}),tune:new chunkK5LXUJ4G_js.r({apiKey:e}),agent:new chunkK5LXUJ4G_js.d({apiKey:e,baseUrl:o}),model:new chunkK5LXUJ4G_js.i({apiKey:e,baseUrl:o}),train:new chunkK5LXUJ4G_js.g({apiKey:e,baseUrl:o}),secret:new chunkK5LXUJ4G_js.k({apiKey:e,baseUrl:o})}}function ct(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 gt(){let e=new commander.Command,o=Ge.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 n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await V(s);}),e.command("dev").description("Start local development server").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.d({apiKey:i,baseUrl:n.baseUrl});await re(s);}),e.command("env").description("Manage secrets and environment variables").action(async()=>{let n=f(),i=n.apiKey||"",s=new chunkK5LXUJ4G_js.k({apiKey:i,baseUrl:n.baseUrl});await ge(s);}),e.command("logs [agent]").description("Stream logs from a deployed agent").action(async n=>{let i=f(),s=i.apiKey||"",r=new chunkK5LXUJ4G_js.d({apiKey:s,baseUrl:i.baseUrl});await pe(r,n);}),e.command("login").description("Authenticate with your API key").action(async()=>{await O();}),e.command("logout").description("Clear stored credentials").action(async()=>{await ne();}),e.command("tokens").description("View token usage for current period").action(de);let a=e.command("data").description("Manage datasets");a.command("upload [file]").description("Upload a dataset").action(async()=>{let n=f(),i=new chunkK5LXUJ4G_js.f({apiKey:n.apiKey||"",baseUrl:n.baseUrl});await ie(i);}),a.command("refine [fileId]").description("Refine a dataset using guardrails").action(async n=>{let i=f(),s=new chunkK5LXUJ4G_js.f({apiKey:i.apiKey||"",baseUrl:i.baseUrl});await se(s,n);});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()=>{H(o),process.argv.includes("--first-run")&&(process.stdin.isTTY?($("Welcome to Langtrain! Let's get you set up."),await O()):(console.log('Langtrain installed! Run "npx langtrain login" to authenticate.'),process.exit(0)));let i=f(),s=i.apiKey||"",r=te(),c=null;if(r&&s){try{c=await q(s);}catch{}Be(c);}else console.log(A.dim(` Not logged in. Only basic options available.
|
|
28
|
+
`));let l=r?Je(s,i.baseUrl):null,h="main";for(;;){let b=await prompts.select({message:ct(h),options:xe(h,c,r)});if(prompts.isCancel(b))if(h==="main")K("Goodbye!"),process.exit(0);else {h="main";continue}let k=b;if(k==="exit"&&(K("Goodbye!"),process.exit(0)),k==="back"){h="main";continue}if(k.startsWith("nav-")){h=k.replace("nav-","");continue}try{switch(k){case "login":if(await O(),i=f(),s=i.apiKey||"",r=te(),r){try{c=await q(s);}catch{}l=Je(s,i.baseUrl),console.clear(),H(o),Be(c);}break;case "logout":await ne(),s="",r=!1,c=null,l=null,console.clear(),H(o),console.log(A.dim(` Logged out. Only basic options available.
|
|
29
|
+
`));break;case "docs":console.log(A.cyan(`
|
|
30
30
|
\u{1F4D6} https://docs.langtrain.ai
|
|
31
|
-
`));break;case "status":await
|
|
31
|
+
`));break;case "status":await Le();break;case "tokens":await de();break;case "telemetry":await Ve();break;case "doctor":await Ne();break;case "init":await oe();break;case "deploy":l&&await V(l.agent);break;case "dev":l&&await re(l.agent);break;case "env":l&&await ge(l.secret);break;case "logs":l&&await pe(l.agent);break;case "tune-finetune":l&&await Ae(l.tune,l.model);break;case "tune-list":l&&await Ie(l.train);break;case "tune-generate":l&&await Fe(l.tune);break;case "vision-finetune":l&&await Ee(l.vision,l.model);break;case "vision-generate":l&&await Pe(l.vision);break;case "agent-list":l&&await Te(l.agent);break;case "agent-create":l&&await Ke(l.agent,l.model);break;case "agent-delete":l&&await _e(l.agent);break;case "data-upload":s&&await ie(new chunkK5LXUJ4G_js.f({apiKey:s}));break;case "data-refine":s&&await se(new chunkK5LXUJ4G_js.f({apiKey:s}));break;case "guard-list":await le(null);break;case "guard-create":await ce(null);break}}catch(_){K(A.red(`Error: ${_.message}`));}}}),e.parse(process.argv);}gt().catch(console.error);exports.main=gt;//# sourceMappingURL=cli.js.map
|
|
32
32
|
//# sourceMappingURL=cli.js.map
|