@ciandt-flow/cli 1.3.0-beta.152 → 1.4.0-beta.162

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.
Files changed (2) hide show
  1. package/dist/index.js +73 -71
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -1,114 +1,116 @@
1
1
  #!/usr/bin/env node
2
- import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import fc,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import Ll,{HTTPError}from'ky';import*as mt from'crypto';import {randomUUID}from'crypto';import*as G from'fs';import G__default,{readFileSync,existsSync,realpathSync}from'fs';import*as F from'path';import F__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as ge from'os';import ge__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as to from'readline';import {createInterface}from'readline';import pr from'keytar';import bn from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import C from'chalk';import ic from'ink-big-text';import $c from'ink-spinner';import*as Se from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp as cp$1}from'fs/promises';import Uc from'extract-zip';import Kc from'proper-lockfile';import eo from'semver';import {execa}from'execa';import Eo from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var Lo="FLOW",_="flow-skills",dn="flow-cli",Ct="internal",or="external",dt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},Ro={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},mn=new Set(["internal","external"]),At={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},Re=5,We=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Mo=new Set(["skill","mcp","plugin"]),f=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,catalogFilters:{types:new Set(Mo),origins:new Set(mn)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:""}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Mo)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(mn)},selectedIndex:0}))}));var ir="aes-256-gcm",il=16,_o=16,$t=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=mt.randomBytes(il),n=mt.createCipheriv(ir,this.key,r,{authTagLength:_o}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),i=n.getAuthTag();return {iv:r.toString("hex"),authTag:i.toString("hex"),ciphertext:o.toString("hex"),algorithm:ir}}decrypt(t){if(t.algorithm!==ir)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=mt.createDecipheriv(ir,this.key,Buffer.from(t.iv,"hex"),{authTagLength:_o});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var sl=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,al=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,ll=/[A-Za-z0-9+/]{40,}={0,2}/g;function fn(e){return e.replace(sl,"Bearer ***").replace(al,"***").replace(ll,"***")}var Lt=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
3
- `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var Rt=".claude",Oo=".flow";function Do(e,t){return F.join(ge.homedir(),Rt,"plugins","cache",_,e,t)}function gn(e){return F.join(ge.homedir(),Rt,"plugins","marketplaces",_,"plugins","native",e)}function sr(){return F.join(ge.homedir(),Rt,"plugins","marketplaces",_,".claude-plugin","marketplace.json")}function No(){return F.join(ge.homedir(),Rt,"plugins","known_marketplaces.json")}function Fo(){return F.join(ge.homedir(),Rt,"plugins","marketplaces",_)}function Uo(){return F.join(ge.homedir(),Oo,"cache","install.lock")}function Ko(){return F.join(ge.homedir(),Oo,"logs","flowsetup.log")}function Mt(e){let t=e==="global"?ge.homedir():process.cwd();return F.join(t,".claude","skills")}function yn(e){let t=e==="global"?ge.homedir():process.cwd();return F.join(t,".claude","skills-lock.json")}var cl=5*1024*1024,ul=3,ar=class{filePath;constructor(){this.filePath=Ko(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
- `;try{G.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=F.dirname(this.filePath);G.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(G.statSync(this.filePath).size>cl){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);G.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=F.dirname(this.filePath),r=F.basename(this.filePath,".log"),n=G.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(ul))G.unlinkSync(F.join(t,o));}catch{}}};var lr=class{write(t){process.stdout.write(t.message+`
5
- `);}};var ft={debug:0,info:1,warn:2,error:3},Ye={context:"cli",transports:[],minLevel:"warn",debugModules:null};function pl(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function ne(e,t){if(e==="tui"){let r=pl();Ye={context:e,transports:[new Lt("tui"),new ar],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Ye={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Ye={context:e,transports:[new Lt("cli")],minLevel:"debug",debugModules:null}:Ye={context:e,transports:[new lr],minLevel:"info",debugModules:null};}function jo(){return Ye.transports}function Bo(e,t){let{debugModules:r,minLevel:n}=Ye;return Ye.context==="tui"&&r&&r!=="all"?r.has(t)?ft[e]>=ft.debug:ft[e]>=ft.warn:ft[e]>=ft[n]}var Jo=new Map;function cr(e,t,r){if(!Bo(e,t))return;let n={level:e,module:t,message:fn(r),timestamp:new Date};for(let o of jo())o.write(n);}function S(e){let t=Jo.get(e);if(t)return t;let r={debug:n=>cr("debug",e,n),info:n=>cr("info",e,n),warn:n=>cr("warn",e,n),error:n=>cr("error",e,n)};return Jo.set(e,r),r}var hn=S("encryption"),Sn="__encrypted__";function dl(e){return typeof e=="object"&&e!==null&&Sn in e&&e[Sn]===true}function wn(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Sn]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return hn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(dl(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return hn.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return hn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var xn=promisify(execFile),gl=promisify(exec),gt=class{static async isAvailable(){try{return await gl("command -v security"),!0}catch{return false}}async getSecret(t,r){try{let{stdout:n}=await xn("security",["find-generic-password","-w","-a",r,"-s",t]);return n.trim()||null}catch{return null}}async setSecret(t,r,n){await xn("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]);}async deleteSecret(t,r){try{return await xn("security",["delete-generic-password","-a",r,"-s",t]),!0}catch{return false}}getStoragePath(){return "macOS Keychain (security)"}};var Vo=promisify(execFile),In=promisify(exec),wl=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],ur=S("encryption:linux-keyvault");async function xl(e,t){let r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,o=setInterval(()=>{process.stderr.write(`\r${r[n++%r.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function Il(e){let t=to.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var Me=class e{static async isAvailable(){try{return await In("command -v secret-tool"),!0}catch{return false}}static async detectPackageManager(){for(let t of wl)try{return await In(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;ur.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return ur.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await Il(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return ur.info(`Running: ${t.command}`),await xl("Installing secret-tool...",()=>In(t.command)),e.isAvailable()}catch{return ur.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{let{stdout:n}=await Vo("secret-tool",["lookup","service",t,"account",r]);return n.trim()||null}catch{return null}}async setSecret(t,r,n){await new Promise((o,i)=>{let s=spawn("secret-tool",["store","--label",t,"service",t,"account",r]);s.stdin.end(n,"utf8"),s.on("close",c=>{c===0?o():i(new Error(`secret-tool exited with code ${c}`));}),s.on("error",i);});}async deleteSecret(t,r){try{return await Vo("secret-tool",["clear","service",t,"account",r]),!0}catch{return false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var qo=S("encryption:windows-keyvault"),yt=class{static async isAvailable(){try{return await pr.getPassword("__flow_probe__","__flow_probe__"),!0}catch{return false}}async getSecret(t,r){try{return await pr.getPassword(t,r)}catch(n){let o=n instanceof Error?n.message.split(`
6
- `)[0]:"unknown error";return qo.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{await pr.setPassword(t,r,n);}catch(o){let i=o instanceof Error?o.message.split(`
7
- `)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${i}`;throw qo.error(s),new Error(s)}}async deleteSecret(t,r){try{return await pr.deletePassword(t,r)}catch{return false}}getStoragePath(){return "Windows Credential Manager (keytar)"}};var bl=32,vl="flow-plugins-cli-fallback",vn="flow-plugins-cli-fallback",Pl={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function El(){let e=`${ge.hostname()}${ge.userInfo().username}`;return mt.scryptSync(e,vl,bl)}function Tl(){let e=El(),t=new $t(e),r=wn(t);return new bn({projectName:vn,serialize:r.serialize,deserialize:r.deserialize})}var mr=null;function dr(){return mr||(mr=Tl()),mr}var W=class{warned=false;async getSecret(t,r){return dr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Pl[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
2
+ import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import gc,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import Rl,{HTTPError}from'ky';import*as yt from'crypto';import {randomUUID}from'crypto';import*as z from'fs';import z__default,{readFileSync,existsSync,realpathSync}from'fs';import*as U from'path';import U__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as he from'os';import he__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as oo from'readline';import {createInterface}from'readline';import mr from'keytar';import En from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import C from'chalk';import sc from'ink-big-text';import Lc from'ink-spinner';import*as Ie from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp as cp$1}from'fs/promises';import Kc from'extract-zip';import jc from'proper-lockfile';import no from'semver';import {execa}from'execa';import Co from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var Mo="FLOW",O="flow-skills",fn="flow-cli",Lt="internal",ar="external",gt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},Oo={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},gn=new Set(["internal","external"]),Rt={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},Oe=5,Ze=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Do=new Set(["skill","mcp","plugin"]),f=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,catalogFilters:{types:new Set(Do),origins:new Set(gn)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:""}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Do)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(gn)},selectedIndex:0}))}));var lr="aes-256-gcm",sl=16,No=16,_t=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=yt.randomBytes(sl),n=yt.createCipheriv(lr,this.key,r,{authTagLength:No}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),i=n.getAuthTag();return {iv:r.toString("hex"),authTag:i.toString("hex"),ciphertext:o.toString("hex"),algorithm:lr}}decrypt(t){if(t.algorithm!==lr)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=yt.createDecipheriv(lr,this.key,Buffer.from(t.iv,"hex"),{authTagLength:No});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var al=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,ll=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,cl=/[A-Za-z0-9+/]{40,}={0,2}/g;function yn(e){return e.replace(al,"Bearer ***").replace(ll,"***").replace(cl,"***")}var Mt=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
3
+ `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var Ot=".claude",Fo=".flow";function Uo(e,t){return U.join(he.homedir(),Ot,"plugins","cache",O,e,t)}function Sn(e){return U.join(he.homedir(),Ot,"plugins","marketplaces",O,"plugins","native",e)}function cr(){return U.join(he.homedir(),Ot,"plugins","marketplaces",O,".claude-plugin","marketplace.json")}function Ko(){return U.join(he.homedir(),Ot,"plugins","known_marketplaces.json")}function jo(){return U.join(he.homedir(),Ot,"plugins","marketplaces",O)}function Bo(){return U.join(he.homedir(),Fo,"cache","install.lock")}function Jo(){return U.join(he.homedir(),Fo,"logs","flowsetup.log")}function Dt(e){let t=e==="global"?he.homedir():process.cwd();return U.join(t,".claude","skills")}function hn(e){let t=e==="global"?he.homedir():process.cwd();return U.join(t,".claude","skills-lock.json")}var ul=5*1024*1024,pl=3,ur=class{filePath;constructor(){this.filePath=Jo(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
+ `;try{z.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=U.dirname(this.filePath);z.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(z.statSync(this.filePath).size>ul){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);z.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=U.dirname(this.filePath),r=U.basename(this.filePath,".log"),n=z.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(pl))z.unlinkSync(U.join(t,o));}catch{}}};var pr=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var St={debug:0,info:1,warn:2,error:3},et={context:"cli",transports:[],minLevel:"warn",debugModules:null};function dl(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function oe(e,t){if(e==="tui"){let r=dl();et={context:e,transports:[new Mt("tui"),new ur],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?et={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?et={context:e,transports:[new Mt("cli")],minLevel:"debug",debugModules:null}:et={context:e,transports:[new pr],minLevel:"info",debugModules:null};}function Ho(){return et.transports}function Vo(e,t){let{debugModules:r,minLevel:n}=et;return et.context==="tui"&&r&&r!=="all"?r.has(t)?St[e]>=St.debug:St[e]>=St.warn:St[e]>=St[n]}var Go=new Map;function dr(e,t,r){if(!Vo(e,t))return;let n={level:e,module:t,message:yn(r),timestamp:new Date};for(let o of Ho())o.write(n);}function S(e){let t=Go.get(e);if(t)return t;let r={debug:n=>dr("debug",e,n),info:n=>dr("info",e,n),warn:n=>dr("warn",e,n),error:n=>dr("error",e,n)};return Go.set(e,r),r}var wn=S("encryption"),xn="__encrypted__";function ml(e){return typeof e=="object"&&e!==null&&xn in e&&e[xn]===true}function In(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[xn]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return wn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(ml(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return wn.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return wn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var bn=promisify(execFile),yl=promisify(exec),ue=S("encryption:macos-keyvault"),ht=class{static async isAvailable(){try{let{stdout:t}=await yl("command -v security");return ue.debug(`security binary found at: ${t.trim()}`),!0}catch{return ue.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{ue.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await bn("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return ue.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ue.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{ue.debug(`Storing secret: service=${t}, account=${r}`),await bn("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),ue.debug("security add-generic-password succeeded");}catch(o){let i=o;throw ue.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),o}}async deleteSecret(t,r){try{return ue.debug(`Deleting secret: service=${t}, account=${r}`),await bn("security",["delete-generic-password","-a",r,"-s",t]),ue.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return ue.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};var vn=promisify(execFile),Pn=promisify(exec),xl=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],R=S("encryption:linux-keyvault");async function Il(e,t){let r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,o=setInterval(()=>{process.stderr.write(`\r${r[n++%r.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function bl(e){let t=oo.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var De=class e{static async isAvailable(){try{let{stdout:t}=await Pn("command -v secret-tool");R.debug(`secret-tool found at: ${t.trim()}`);}catch{return R.debug("secret-tool binary not found in PATH"),false}try{return await vn("secret-tool",["lookup","service","__flow_connectivity_check__"]),R.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(R.debug(`Secret Service D-Bus not available: ${n}`),false):(R.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of xl)try{return await Pn(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;R.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return R.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await bl(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return R.info(`Running: ${t.command}`),await Il("Installing secret-tool...",()=>Pn(t.command)),e.isAvailable()}catch{return R.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{R.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await vn("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return R.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return R.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){R.debug(`Storing secret: service=${t}, account=${r}`),R.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),R.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),R.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,i)=>{let s=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),c="";s.stderr.on("data",a=>{c+=a.toString();}),s.stdin.end(n,"utf8"),s.on("close",a=>{a===0?(R.debug("secret-tool store succeeded"),o()):(R.error(`secret-tool store failed: code=${a}, stderr=${c.trim()}`),i(new Error(`secret-tool exited with code ${a}${c?`: ${c.trim()}`:""}`)));}),s.on("error",a=>{R.error(`secret-tool store spawn error: ${a.message}`),i(a);});});}async deleteSecret(t,r){try{return R.debug(`Deleting secret: service=${t}, account=${r}`),await vn("secret-tool",["clear","service",t,"account",r]),R.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return R.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var pe=S("encryption:windows-keyvault"),wt=class{static async isAvailable(){try{return await mr.getPassword("__flow_probe__","__flow_probe__"),pe.debug("Windows Credential Manager is available (keytar probe succeeded)"),!0}catch(t){let r=t instanceof Error?t.message.split(`
6
+ `)[0]:"unknown error";return pe.debug(`Windows Credential Manager not available: ${r}`),false}}async getSecret(t,r){try{pe.debug(`Looking up secret: service=${t}, account=${r}`);let n=await mr.getPassword(t,r);return pe.debug(`keytar getPassword result: ${n?"found":"empty"}`),n}catch(n){let o=n instanceof Error?n.message.split(`
7
+ `)[0]:"unknown error";return pe.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{pe.debug(`Storing secret: service=${t}, account=${r}`),await mr.setPassword(t,r,n),pe.debug("keytar setPassword succeeded");}catch(o){let i=o instanceof Error?o.message.split(`
8
+ `)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${i}`;throw pe.error(s),new Error(s)}}async deleteSecret(t,r){try{pe.debug(`Deleting secret: service=${t}, account=${r}`);let n=await mr.deletePassword(t,r);return pe.debug(`keytar deletePassword result: ${n}`),n}catch(n){let o=n instanceof Error?n.message.split(`
9
+ `)[0]:"unknown error";return pe.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (keytar)"}};var vl=32,Pl="flow-plugins-cli-fallback",Tn="flow-plugins-cli-fallback",El={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function Tl(){let e=`${he.hostname()}${he.userInfo().username}`;return yt.scryptSync(e,Pl,vl)}function kl(){let e=Tl(),t=new _t(e),r=In(t);return new En({projectName:Tn,serialize:r.serialize,deserialize:r.deserialize})}var gr=null;function fr(){return gr||(gr=kl()),gr}var X=class{warned=false;async getSecret(t,r){return fr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=El[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
8
10
  using a machine-derived key. For stronger security, ${o}.
9
- `),this.warned=true;}dr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=dr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return dr().path}static hasExistingData(){try{let t=new bn({projectName:vn});return G.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new bn({projectName:vn});G.rmSync(t.path,{force:!0});}catch{}mr=null;}};async function Pn(){if(W.hasExistingData())return new W;switch(process.platform){case "darwin":return await gt.isAvailable()?new gt:new W;case "linux":return await Me.isAvailable()?new Me:await Me.ensureInstalled()?new Me:new W;case "win32":return await yt.isAvailable()?new yt:new W;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var kl=S("config:credentials"),Te="flow-plugins-cli",En="credentials",Tn="token-cache",kn="user-info",yr=null;async function _e(){return yr||(yr=Pn()),yr}function hr(){yr=null;}async function O(){let t=await(await _e()).getSecret(Te,En);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ze(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw kl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await _e()).setSecret(Te,En,JSON.stringify(e));}async function Xo(){let e=await _e();await e.deleteSecret(Te,En),await e.deleteSecret(Te,Tn),await e.deleteSecret(Te,kn);}async function Yo(){return (await _e()).getStoragePath()}async function Zo(e){await(await _e()).setSecret(Te,Tn,JSON.stringify(e));}async function Sr(){let t=await(await _e()).getSecret(Te,Tn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function wr(e){await(await _e()).setSecret(Te,kn,JSON.stringify(e));}async function Qo(){let t=await(await _e()).getSecret(Te,kn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ht(){let e=await Sr();return e?new Date(e.expiresAt)>new Date:false}function xr(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var ei=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];function Cl(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Al(e){if(ei.some(r=>r.test(e)))return true;let t=Cl(e);return !!(t&&ei.some(r=>r.test(t)))}function $l(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function St(e,t){let r=$l(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Al(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Cn=S("api:auth");function Ml(e){if(!We.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var ti={INVALID_CLIENT_SECRET:"Invalid Client Secret \u2014 check the value and try again",INVALID_CLIENT_ID:"Invalid Client ID \u2014 check the value and try again",INVALID_TENANT:"Invalid Tenant \u2014 check the value and try again",TENANT_NOT_FOUND:"Tenant not found \u2014 verify the tenant identifier"};async function _l(e){if(e instanceof HTTPError){let t=e.response.status;Cn.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&ti[r]?new Error(ti[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Cn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Cn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qe(e){let t=St("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ml(e.tenant);let r;try{r=await Ll.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await _l(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Ze(e),await Zo({accessToken:r.access_token,expiresAt:n});let o=xr(r.access_token);await wr({sub:o.sub,name:o.name,email:o.email});}var ri=S("lib:tokenProvider");async function Oe(){if(await ht()){let n=await Sr();if(n)return n.accessToken}ri.debug("Token expired or missing, re-authenticating...");let t=await O();if(!t)throw new Error("Not authenticated. Run: flow auth login");W.clearFallbackFile(),hr(),await Qe(t);let r=await Sr();if(!r)throw new Error("Authentication succeeded but token was not persisted");return ri.debug("Token refreshed successfully"),r.accessToken}var Ir=S("api:metrics");function ni(){return St("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function oi(e,t,r){return Ll.post(e,{json:t,headers:r})}async function Dl(e){let t=await Qo();if(t)return t;let r=xr(e),n={sub:r.sub,name:r.name,email:r.email};return await wr(n),n}async function b(e,t){let r=await Oe(),n=await Dl(r),o=await O();if(!We.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:dn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await oi(ni(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Ir.debug(`Metrics event sent: ${e}`);}catch(s){throw Ir.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function ii(e,t,r){try{let n=r&&We.test(r)?r:"unknown",o={action:e,booster:dn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await oi(ni(),o,{FlowTenant:n}),Ir.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Ir.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var x={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED"};var Nl={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ce={...Nl};function si(e){let t=Date.now();ce={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function et(e){ce.currentStep=e,ce.stepStart=Date.now();}function $(){return {...ce}}function De(){return ce.sessionStart===0?0:Date.now()-ce.sessionStart}function tt(){return ce.stepStart===0?0:Date.now()-ce.stepStart}function ai(){ce.tuiSessionStart=Date.now();}function li(){return ce.tuiSessionStart===0?0:Date.now()-ce.tuiSessionStart}var Fl=3e3,Ul=S("abandonment");async function br(e){let{currentStep:t,sessionStart:r}=$();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:De()};try{await Promise.race([b(x.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Fl))]);}catch(o){Ul.warn(`Abandonment event failed: ${String(o)}`);}}function ci(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Kl=3e3,jl=S("session-end");async function Ot(e){let{activeTab:t,screen:r}=f.getState(),n=li(),i=[b(x.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(br(e));try{await ci(Promise.all(i).then(()=>{}),Kl);}catch(s){jl.warn(`Session end event failed: ${String(s)}`);}}var Vl=2e3;function pi(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=f(s=>s.pendingExit),o=f(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Ot("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Vl);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var Wl=16;function di({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:i}){let s=useRef(t);useEffect(()=>{s.current=t;},[t]),useInput((a,l)=>{if(l.backspace){let u=s.current.slice(0,-1);s.current=u,r(u);}else if(a&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let u=s.current+a;s.current=u,r(u);}},{isActive:o});let c=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Wl)}),jsx(Text,{color:o?"cyan":"gray",children:c}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var ue=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));var Ql=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Ne=Ql.version;function p(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function V(e){process.stdout.write(C.green(` \u2713 ${p(e)}
11
+ `),this.warned=true;}fr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=fr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return fr().path}static hasExistingData(){try{let t=new En({projectName:Tn});return z.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new En({projectName:Tn});z.rmSync(t.path,{force:!0});}catch{}gr=null;}};async function kn(){if(X.hasExistingData())return new X;switch(process.platform){case "darwin":return await ht.isAvailable()?new ht:new X;case "linux":return await De.isAvailable()?new De:await De.ensureInstalled()?new De:new X;case "win32":return await wt.isAvailable()?new wt:new X;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Cl=S("config:credentials"),$e="flow-plugins-cli",Cn="credentials",$n="token-cache",An="user-info",hr=null;async function Ne(){return hr||(hr=kn()),hr}function wr(){hr=null;}async function D(){let t=await(await Ne()).getSecret($e,Cn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function tt(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Cl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ne()).setSecret($e,Cn,JSON.stringify(e));}async function Yo(){let e=await Ne();await e.deleteSecret($e,Cn),await e.deleteSecret($e,$n),await e.deleteSecret($e,An);}async function Zo(){return (await Ne()).getStoragePath()}async function Qo(e){await(await Ne()).setSecret($e,$n,JSON.stringify(e));}async function xr(){let t=await(await Ne()).getSecret($e,$n);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ir(e){await(await Ne()).setSecret($e,An,JSON.stringify(e));}async function ei(){let t=await(await Ne()).getSecret($e,An);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function xt(){let e=await xr();return e?new Date(e.expiresAt)>new Date:false}function br(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var ti=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];function $l(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Al(e){if(ti.some(r=>r.test(e)))return true;let t=$l(e);return !!(t&&ti.some(r=>r.test(t)))}function Ll(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function It(e,t){let r=Ll(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Al(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Ln=S("api:auth");function Ml(e){if(!Ze.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var ri={INVALID_CLIENT_SECRET:"Invalid Client Secret \u2014 check the value and try again",INVALID_CLIENT_ID:"Invalid Client ID \u2014 check the value and try again",INVALID_TENANT:"Invalid Tenant \u2014 check the value and try again",TENANT_NOT_FOUND:"Tenant not found \u2014 verify the tenant identifier"};async function Ol(e){if(e instanceof HTTPError){let t=e.response.status;Ln.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&ri[r]?new Error(ri[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Ln.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Ln.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function rt(e){let t=It("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ml(e.tenant);let r;try{r=await Rl.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await Ol(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await tt(e),await Qo({accessToken:r.access_token,expiresAt:n});let o=br(r.access_token);await Ir({sub:o.sub,name:o.name,email:o.email});}var ni=S("lib:tokenProvider");async function Fe(){if(await xt()){let n=await xr();if(n)return n.accessToken}ni.debug("Token expired or missing, re-authenticating...");let t=await D();if(!t)throw new Error("Not authenticated. Run: flow auth login");X.clearFallbackFile(),wr(),await rt(t);let r=await xr();if(!r)throw new Error("Authentication succeeded but token was not persisted");return ni.debug("Token refreshed successfully"),r.accessToken}var vr=S("api:metrics");function oi(){return It("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ii(e,t,r){return Rl.post(e,{json:t,headers:r})}async function Nl(e){let t=await ei();if(t)return t;let r=br(e),n={sub:r.sub,name:r.name,email:r.email};return await Ir(n),n}async function b(e,t){let r=await Fe(),n=await Nl(r),o=await D();if(!Ze.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:fn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await ii(oi(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),vr.debug(`Metrics event sent: ${e}`);}catch(s){throw vr.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function si(e,t,r){try{let n=r&&Ze.test(r)?r:"unknown",o={action:e,booster:fn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ii(oi(),o,{FlowTenant:n}),vr.debug(`Anonymous metrics event sent: ${e}`);}catch(n){vr.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var x={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED"};var Fl={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},de={...Fl};function ai(e){let t=Date.now();de={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function nt(e){de.currentStep=e,de.stepStart=Date.now();}function A(){return {...de}}function Ue(){return de.sessionStart===0?0:Date.now()-de.sessionStart}function ot(){return de.stepStart===0?0:Date.now()-de.stepStart}function li(){de.tuiSessionStart=Date.now();}function ci(){return de.tuiSessionStart===0?0:Date.now()-de.tuiSessionStart}var Ul=3e3,Kl=S("abandonment");async function Pr(e){let{currentStep:t,sessionStart:r}=A();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Ue()};try{await Promise.race([b(x.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Ul))]);}catch(o){Kl.warn(`Abandonment event failed: ${String(o)}`);}}function ui(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var jl=3e3,Bl=S("session-end");async function Ft(e){let{activeTab:t,screen:r}=f.getState(),n=ci(),i=[b(x.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(Pr(e));try{await ui(Promise.all(i).then(()=>{}),jl);}catch(s){Bl.warn(`Session end event failed: ${String(s)}`);}}var Gl=2e3;function di(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=f(s=>s.pendingExit),o=f(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Ft("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Gl);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var Xl=16;function mi({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:i}){let s=useRef(t);useEffect(()=>{s.current=t;},[t]),useInput((a,l)=>{if(l.backspace){let u=s.current.slice(0,-1);s.current=u,r(u);}else if(a&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let u=s.current+a;s.current=u,r(u);}},{isActive:o});let c=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Xl)}),jsx(Text,{color:o?"cyan":"gray",children:c}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var me=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));var ec=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Ke=ec.version;function p(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function G(e){process.stdout.write(C.green(` \u2713 ${p(e)}
10
12
  `));}function k(e){process.stderr.write(C.red(` \u2717 ${p(e)}
11
13
  `));}function I(e){process.stdout.write(C.cyan(` \u2139 ${p(e)}
12
- `));}function vr(e,t){let r=t.map(c=>c.map(p)),n=[e,...r],o=e.map((c,a)=>Math.max(...n.map(l=>(l[a]??"").length))),i=o.map(c=>"\u2500".repeat(c)).join(" "),s=c=>c.map((a,l)=>a.padEnd(o[l])).join(" ");process.stdout.write(`
14
+ `));}function Er(e,t){let r=t.map(c=>c.map(p)),n=[e,...r],o=e.map((c,a)=>Math.max(...n.map(l=>(l[a]??"").length))),i=o.map(c=>"\u2500".repeat(c)).join(" "),s=c=>c.map((a,l)=>a.padEnd(o[l])).join(" ");process.stdout.write(`
13
15
  `),process.stdout.write(` ${C.bold(s(e))}
14
16
  `),process.stdout.write(` ${C.dim(i)}
15
17
  `);for(let c of r)process.stdout.write(` ${s(c)}
16
18
  `);process.stdout.write(`
17
- `);}function wt(e){process.stdout.write(JSON.stringify(e,null,2)+`
18
- `);}function X(e){process.stdout.write(JSON.stringify(e)+`
19
- `);}function oe(e){process.stderr.write(JSON.stringify(e)+`
20
- `);}function D(e){return e instanceof Error?e.message:String(e)}function Pr(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function rc(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var he=["clientId","clientSecret","tenant"],nc={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function mi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),u=useRef(0),{setCredentials:g,setJustAuthenticated:v}=ue(),{setFocus:d}=f();useInput((h,T)=>{if(!a){if(T.shift&&T.tab){let y=he.indexOf(r);y>0&&n(he[y-1]);}else if(T.tab){let y=he.indexOf(r);y<he.length-1&&n(he[y+1]);}else if(T.return)if(r==="tenant")E();else {let y=he.indexOf(r);n(he[y+1]);}}},{isActive:true});let E=async()=>{let h={};for(let T of he)e[T].trim()||(h[T]="This field is required");if(Object.keys(h).length>0){i(h);let T=he.find(y=>h[y]);T&&n(T);return}l(true),c(null),u.current+=1;try{await Qe({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:T,...y}=e;g(y),v(!0),f.getState().setScreen("bundleSetup"),d("bundleList"),b(x.CLI_SESSION_STARTED,{cli_version:Ne,os:process.platform,node_version:process.version,duration_ms:De(),interface:"tui"}).catch(()=>{});}catch(T){let y=T instanceof Error?T.message:"Authentication failed";c(y),ii(x.CLI_AUTH_FAILED,{error_code:rc(T),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(T=>({...T,clientSecret:""}));}},m=h=>T=>{t(y=>({...y,[h]:T})),o[h]&&i(y=>({...y,[h]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Lo," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:he.map(h=>jsx(Box,{marginBottom:1,children:jsx(di,{label:nc[h],value:e[h],onChange:m(h),masked:h==="clientSecret",isActive:r===h&&!a,error:o[h]})},h))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",p(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Tr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(ic,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Ne]})})]})}var Ln={discover:"Discover",installed:"Installed"},sc=Object.keys(Ln);function wi(){let e=f(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:sc.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${Ln[t]} `}):jsx(Text,{dimColor:true,children:` ${Ln[t]} `})},t))})}var Y=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Ii(){let e=f(s=>s.focus),t=Y(s=>s.query),r=Y(s=>s.cursorPosition),n=e==="search",o=t.slice(0,r),i=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var uc=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...dt[e]})),pc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Ro[e]}));function bi(){let e=f(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),uc.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),pc.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function vi({type:e}){let{label:t,color:r}=dt[e];return jsx(Text,{color:r,children:t})}function Ti({origin:e}){return e===Ct?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Cr=fc.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(vi,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ti,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Pr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function It({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Ai({items:e,emptyMessage:t}){let r=f(a=>a.selectedIndex);if(e.length===0)return jsx(It,{message:t});let n=Math.max(0,r-Math.floor(Re/2)),o=Math.min(e.length,n+Re);o===e.length&&(n=Math.max(0,o-Re));let i=e.slice(n,o),s=n,c=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((a,l)=>jsx(Cr,{item:a,isSelected:n+l===r},a.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:c>0?`\u2193 ${c} more below`:" "})})]})}function Ri({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function _i({groups:e,emptyMessage:t}){let r=f(d=>d.selectedIndex),n=[],o=0;for(let d of e){n.push({kind:"header",label:d.label,pathHint:d.pathHint,key:`h-${d.scope}`});for(let E of d.items)n.push({kind:"item",item:E,itemIndex:o,key:`i-${d.scope}-${E.name}`}),o++;}if(o===0)return jsx(It,{message:t});let s=n.findIndex(d=>d.kind==="item"&&d.itemIndex===r),c=s>=0?s:0,a=Math.max(0,c-Math.floor(Re/2)),l=Math.min(n.length,a+Re);l===n.length&&(a=Math.max(0,l-Re));let u=n.slice(a,l),g=a,v=n.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),u.map(d=>d.kind==="header"?jsx(Ri,{label:d.label,pathHint:d.pathHint},d.key):jsx(Cr,{item:d.item,isSelected:d.itemIndex===r},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:v>0?`\u2193 ${v} more below`:" "})})]})}var Ic={discover:"Discover",installed:"Installed"};function Di({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(Ii,{}),jsx(bi,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Ic[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(_i,{groups:n,emptyMessage:r}):jsx(Ai,{items:e,emptyMessage:r})]})}function Ni({filteredItems:e,emptyMessage:t,groups:r}){let n=f(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Di,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Di,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Pc={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Plugin | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select"};function Ar(){let e=f(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:Pc[e]})})}function Ui({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",p(e)]})}):null}function $r({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx($c,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Lr({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function at({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=f(a=>a.focus),[s,c]=useState(0);return useInput((a,l)=>{l.upArrow?c(u=>u>0?u-1:u):l.downArrow?c(u=>u<t.length-1?u+1:u):l.return?n(t[s]):l.escape&&o();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",a]}),r?.[a]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[a]]})]},l))})]})}var Kn=Object.entries(At),Gi=[...Kn.map(([,e])=>e.actionLabel),"Cancel"],zi=Object.fromEntries(Kn.map(([,e])=>[e.actionLabel,e.description]));function qi(e){let t=Kn.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function Xi({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=qi(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(at,{itemName:`${e} \u2014 Choose scope`,actions:Gi,descriptions:zi,onAction:i,onClose:s}):jsx(at,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Mr({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=f(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?n("idle"):i==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function Qi({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Mr({activeFocus:"actionMenu",onConfirm:()=>i(t)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let g=r==="enabled"?"Disable":"Enable",v=o&&p(o),d=v?`Update to v${v}`:"Update";return jsx(at,{itemName:e,actions:n?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===g?s(t):h.startsWith("Update")?c?.():a();},onClose:a})}function rs({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Mr({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(at,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function ns(e,t){let r=F.resolve(t);await Se.mkdir(r,{recursive:true});let n=F.join(F.dirname(r),`${randomUUID()}.zip`);try{await Se.writeFile(n,e),await Uc(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let s=F.resolve(r,o.fileName);if(!s.startsWith(r+F.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(F.resolve(F.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Se.unlink(n);}catch{}}}async function Bn(e){await Se.rm(e,{recursive:true,force:true});}async function Ke(){let e=Uo();await Se.mkdir(F.dirname(e),{recursive:true});try{await Se.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Kc.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var Bc={user:"global",project:"project",local:"local"};function Dr(e){return e?Bc[e]:"global"}var we=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},je=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};function Ht(){return Ll.create({prefix:St("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Oe();e.headers.set("Authorization",`Bearer ${t}`);let r=await O();r?.tenant&&We.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Hc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function os(e){if(!e||!Hc.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function xe(){try{let{plugins:e}=await Ht().get("v1/plugins/catalog").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${e.message}`):e}}async function vt(e){os(e);try{return await Ht().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function is(e){os(e);try{let t=await Ht().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Nr(){try{let{profiles:e}=await Ht().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}var Vc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Gc=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Fr(e){if(!Vc.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function zc(e){if(!Gc.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var Be=S("installer");function qc(e,t){let r=`${e}@${_}`,o=Ce().plugins[r];if(o&&!t)throw new we(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Wc(e,t,r){r&&await Bn(t);try{Be.debug(`[${t}] Extracting archive...`),await ns(e,t);}catch(n){throw await Bn(t),n}}function Xc(e,t,r,n,o){let i=Ce(),s={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o},c=i.plugins[e]??[];i.plugins[e]=[...c.filter(a=>a.scope!==n),s],lt(i),Jn(e,true,n);}async function Yc(e,t,r,n,o){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:$().interfaceType});}catch(i){Be.warn(`Failed to send install metrics: ${String(i)}`);}}async function Zc(e,t,r){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(n){Be.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function Ie(e,t={}){let r=Date.now(),n=null;try{Be.debug(`[${e}] Acquiring lock...`),n=await Ke();let{pluginKey:o,alreadyInstalled:i}=qc(e,t.force);Be.debug(`[${e}] Fetching manifest...`);let s=await vt(e);Fr(s.name),zc(s.version),Be.debug(`[${e}] Downloading archive...`);let c=await is(e),a=t.scope??"user",l=Do(s.name,s.version);await Wc(c,l,!!i&&!!t.force),Xc(o,l,s.version,a,"internal"),ss(s,l);let u=Date.now()-r;Be.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await Yc(s.name,s.version,u,Dr(a),"internal"),g}catch(o){throw await Zc(e,o,"internal"),Be.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}function Qc(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:_,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function cs(){let e=sr();if(!G__default.existsSync(e))return null;try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return null}}function eu(){let e=cs();if(e)return e;let t=Qc(),r=sr();return G__default.mkdirSync(F__default.dirname(r),{recursive:true}),Hn(t),t}function Hn(e){let t=sr(),r=`${t}.${randomUUID()}.tmp`;G__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),G__default.renameSync(r,t);}function tu(){let e=No(),t={};try{G__default.existsSync(e)&&(t=JSON.parse(G__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[_])return;t[_]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Fo(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;G__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),G__default.renameSync(r,e);}function ss(e,t){Fr(e.name),tu();let r=gn(e.name);G__default.mkdirSync(F__default.dirname(r),{recursive:true});try{G__default.lstatSync(r),G__default.rmSync(r,{recursive:!0,force:!0});}catch{}G__default.symlinkSync(t,r);let n=eu();n.plugins.some(i=>i.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Hn(n));}function Vn(e){Fr(e);let t=gn(e);try{G__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=cs();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Hn(r);}var nu=S("mcpConfigReader"),ou=500,iu=512;function su(){return F__default.join(ge__default.homedir(),".claude.json")}function au(){return F__default.join(process.cwd(),".mcp.json")}function ps(e){if(!G__default.existsSync(e))return null;try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return nu.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gn(e){if(!Vt(e))return {};let t=e.mcpServers;return Vt(t)?t:{}}function zn(e,t){return Object.keys(e).slice(0,ou).map(n=>({name:p(n.slice(0,iu)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function ms(){let e=[],t=su(),r=ps(t);if(Vt(r)){let c=r,a=Gn(c);e.push(...zn(a,"user"));let l=process.cwd();if(Vt(c.projects)){let u=c.projects[l];if(Vt(u)){let g=Gn(u);e.push(...zn(g,"local"));}}}let n=au(),o=ps(n),i=Gn(o);e.push(...zn(i,"project"));let s=new Map;for(let c of e){let a=`${c.name}@${c.scope}`;s.has(a)||s.set(a,c);}return [...s.values()]}var se=S("storage");async function cu(e,t){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:$().interfaceType});}catch(r){se.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function uu(e,t,r){let n=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:$().interfaceType}).catch(o=>se.warn(`Failed to send ${t} metrics: ${String(o)}`));}function gs(){return F__default.join(ge__default.homedir(),".claude","plugins","installed_plugins.json")}function pu(){return F__default.join(ge__default.homedir(),".claude","plugins")}function fs(e){let t=F__default.resolve(e),r=F__default.resolve(pu()),n=F__default.resolve(F__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+F__default.sep)||t===r,i=t.startsWith(n+F__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function ys(e="user"){return e==="local"?F__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?F__default.join(process.cwd(),".claude","settings.json"):F__default.join(ge__default.homedir(),".claude","settings.json")}function Ce(){let e=gs();if(!G__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(G__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function du(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function hs(e,t){try{G__default.mkdirSync(F__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;G__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),G__default.renameSync(r,e);}catch(r){throw du(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function lt(e){hs(gs(),e);}function Gt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function mu(e,t){let r=F__default.join(e,".claude-plugin"),n=F__default.join(r,"plugin.json");if(G__default.existsSync(n))try{return JSON.parse(G__default.readFileSync(n,"utf-8"))}catch{return null}let o=F__default.join(r,"marketplace.json");if(G__default.existsSync(o))try{let i=JSON.parse(G__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function Yn(e="user"){let t=ys(e);if(!G__default.existsSync(t))return {};try{return JSON.parse(G__default.readFileSync(t,"utf-8"))}catch{return {}}}function Ss(e,t="user"){hs(ys(t),e);}function fu(e,t){let{name:r,marketplace:n}=Gt(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Gt(s).name===r)[0],!o)throw se.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function gu(e,t){let{name:r,marketplace:n}=Gt(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Gt(s).name===r)[0],o?{key:o,name:r}:null}function qn(e="user"){return Yn(e).enabledPlugins??{}}function Wn(e,t="user"){let r=Yn(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,Ss(r,t);}function Jn(e,t,r="user"){let n=Yn(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Ss(n,r);}function yu(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function be(){let e=Ce(),t=qn(),r=qn("project"),n=qn("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:v}=Gt(l),d=u.map(m=>m.scope==="managed"?{...m,scope:"user"}:m);return yu(d).map(m=>{let h=mu(m.installPath,g),y=(o[m.scope]??t)[l];return {name:g,marketplace:v,version:m.version&&m.version!=="unknown"?m.version:void 0,installedAt:m.installedAt,installPath:m.installPath,scope:m.scope,description:h?.description,author:h?.author,status:y===false?"disabled":"enabled"}})}),s=ms(),c=new Set(i.map(l=>`${l.name}@${l.scope}`)),a=s.filter(l=>!c.has(`${l.name}@${l.scope}`));return [...i,...a]}async function Ur(e,t){se.debug(`[${e}] Acquiring lock to uninstall`);let r=await Ke();try{let n=Ce(),o=gu(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=o,c=n.plugins[i];if(t){let a=c.find(g=>g.scope===t);if(!a)throw new Error(`Plugin '${s}' is not installed in ${t} scope`);se.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),fs(a.installPath);let l=F__default.dirname(a.installPath);se.debug(`[${s}] Removing directory: ${l}`),G__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(g=>g.scope!==t);if(u.length===0){let{[i]:g,...v}=n.plugins;lt({...n,plugins:v}),Wn(i,t),Vn(s);}else n.plugins[i]=u,lt(n),Wn(i,t);}else {se.debug(`[${s}] Resolved key: ${i}`);for(let u of c){fs(u.installPath);let g=F__default.dirname(u.installPath);se.debug(`[${s}] Removing directory: ${g}`),G__default.rmSync(g,{recursive:!0,force:!0}),Wn(i,u.scope);}Vn(s);let{[i]:a,...l}=n.plugins;lt({...n,plugins:l});}await cu(s,c[0].origin??"internal"),se.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function zt(e,t,r){se.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Ke();try{let o=Ce(),{key:i,name:s}=fu(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";se.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),Jn(i,t==="enabled",a),uu(s,t,l),se.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var K=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:be()})}));var N=["discover","installed"];function ws(e,t,r){if(t.rightArrow||t.tab){let n=N.indexOf(r.activeTab);return [{type:"setTab",tab:N[(n+1)%N.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let n=N.indexOf(r.activeTab);return [{type:"setTab",tab:N[(n-1+N.length)%N.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function xs(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=N.indexOf(r.activeTab);return [{type:"setTab",tab:N[(o-1+N.length)%N.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=N.indexOf(r.activeTab);return [{type:"setTab",tab:N[(o+1)%N.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=N.indexOf(r.activeTab);return [{type:"setTab",tab:N[(o+1)%N.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function Is(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function bs(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function jr(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=f.getState();for(let i of e)if(i.type==="setTab")t(i.tab);else if(i.type==="setFocus")r(i.focus);else if(i.type==="setSelectedIndex")n(i.index);else if(i.type==="setActionMenuOpen")o(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:c,setCursorPosition:a,cursorPosition:l}=Y.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?f.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?f.getState().selectAllTypes():i.type==="toggleOriginFilter"?f.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&f.getState().selectAllOrigins();}function vs({listLength:e}){let t=f(m=>m.focus),r=f(m=>m.selectedIndex),n=f(m=>m.actionMenuOpen),o=f(m=>m.setFocus),i=f(m=>m.setActionMenuOpen),s=Y(m=>m.query),c=Y(m=>m.setQuery),a=Y(m=>m.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:m,setCursorPosition:h}=Y.getState();h(m.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let m=setTimeout(()=>g(s),300);return ()=>clearTimeout(m)},[s]),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();jr(ws(m,h,{activeTab:T}));},{isActive:t==="tabs"}),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();jr(xs(m,h,{activeTab:T,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((m,h)=>{jr(Is(m,h));},{isActive:t==="actionMenu"}),useInput((m,h)=>{let T=bs(m,h,Y.getState().query),y=T.queryUpdate;if(jr(T.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:A,setCursorPosition:J}=Y.getState();if("backspace"in y)A>0&&(c(L.slice(0,A-1)+L.slice(A)),J(A-1));else if("append"in y)c(L.slice(0,A)+y.append+L.slice(A)),J(A+y.append.length);else if("cursorMove"in y){let q=A+y.cursorMove;q>=0&&q<=L.length&&J(q);}}},{isActive:t==="search"});let v=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(m=>{let{setSelectedIndex:h,selectedIndex:T}=f.getState();m===0?h(0):T>=m&&h(m-1);},[]),E=useCallback(m=>{if(!u)return l.current=m.length,m;let h=u.toLowerCase(),T=m.filter(y=>y.name.toLowerCase().includes(h)||y.description?.toLowerCase().includes(h));return l.current=T.length,T},[u]);return {actionMenuOpen:n,closeMenu:v,selectedIndex:r,clampIndex:d,filteredItems:E}}function Es(){let e=f(c=>c.notification),t=f(c=>c.showNotification),r=f(c=>c.clearNotification),n=ue(c=>c.justAuthenticated),o=ue(c=>c.credentials),i=ue(c=>c.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[n,o]),useEffect(()=>{if(!e)return;let c=setTimeout(r,3e3);return ()=>clearTimeout(c)},[e]),{notify:(c,a)=>{t(c,a);}}}function Ae(e,t,r=false){return r?true:!eo.valid(e)||!eo.valid(t)?false:eo.gt(t,e)}var $e=S("updater");async function xu(e,t,r,n,o){try{await b(x.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:$().interfaceType});}catch(i){$e.warn(`Failed to send update metrics: ${String(i)}`);}}function Iu(e){let t=Ce(),r=`${e}@${_}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Br(e,t={}){let r=Date.now(),n=null;try{$e.debug(`[${e}] Acquiring lock...`),n=await Ke();let o=Iu(e);if(!o)throw $e.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;$e.debug(`[${e}] Fetching manifest...`);let l=(await vt(e)).version;if(!s||!Ae(s,l,t.force))throw $e.debug(`[${e}] Already up to date (v${s??"n/a"})`),new je(e,s??"unknown");$e.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await Ie(e,{force:!0,skipMetrics:!0}),g=Date.now()-r;return await xu(u.name,s,u.version,g,i.origin??"internal"),$e.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){$e.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await Ke();let g=Ce(),v=`${e}@${_}`;throw g.plugins[v]&&(g.plugins[v][0].version=s,g.plugins[v][0].installPath=c,lt(g),$e.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var bu=S("commands:helpers");async function Q(){let e=await O();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Oe();}catch(t){return bu.debug(`Token validation failed: ${String(t)}`),k("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(k("Starter kit not set. Run: flow auth login"),false):true}async function Je(e){let t=to.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Ts(e){let t=to.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(n.trim());});})}var vu=/^[^@]+@[^@]+$/;function qt(e){return vu.test(e)}function Pt(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Pu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function ks(e){if(!Pu.test(e))throw new Error(`Invalid plugin name: "${e}". Plugin names must start with an alphanumeric character and contain only letters, digits, dots, hyphens, underscores, and slashes.`)}var Eu=/^[\w./:@?&=+#%-]+$/;function Jr(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Eu.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Wt=S("claudeProxy"),oo="claude ",Cs="flow ",ro=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},no=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Tu=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/;function ku(e){$s(e);let t=e.slice(oo.length);if(!Tu.test(t))throw new no(e)}var Hr=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function $s(e){if(!e||!/^claude /.test(e))throw new ro(e)}async function ae(e){$s(e);let t=e.slice(oo.length).split(/\s+/).filter(Boolean),r=Cu(t);Wt.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),i=Date.now()-n;return Wt.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${i}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:i}}catch(o){throw Ls(o)?new Hr:o}}function Cu(e){return e.length>=3?e[2]:e.join(" ")}function Ls(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Au(e){return e.startsWith(Cs)?oo+e.slice(Cs.length):e}var $u=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Lu(e,t){return !t||e.includes("--scope")||!$u.test(e)?e:`${e} --scope ${t}`}async function Rs(e,t){let r=e.split("&&").map(o=>Au(o.trim())).filter(Boolean).map(o=>Lu(o,t));if(r.length===0)throw new Error("Empty install command");for(let o of r)ku(o);Wt.debug(`[installCommand] Executing ${r.length} command(s)`);let n=await ae(r[0]);if(n.exitCode!==0)return n;for(let o=1;o<r.length;o++)if(n=await ae(r[o]),n.exitCode!==0)return n;return n}async function Ms(e,t,r){let n=Pt(e),o=t?.trim();if(!o&&(o=(await Ts(`Plugin "${n}" could not be installed.
21
- If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Jr(o),r?.(),Wt.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let i=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Wt.debug(`[${n}] Marketplace added successfully`);}catch(i){throw Ls(i)?new Hr:i}}var He=S("installDispatcher");async function _s(e,t,r){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Dr(r),version:"unknown",duration_ms:t,interface:$().interfaceType});}catch(n){He.warn(`Failed to send external install metrics: ${String(n)}`);}}async function Os(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(r){He.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function io(e,t){let r=Pt(e);ks(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function so(e,t,r,n){let o=io(e,n),i=Pt(e);r?.onStatus?.(`Installing ${i}...`),He.debug(`[${e}] Attempting install: ${o}`);let s=await ae(o);return s.exitCode===0?s:(He.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`),r?.onError?.(s.stderr||`Install failed with exit code ${s.exitCode}`),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await Ms(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),He.debug(`[${e}] Retrying install after marketplace add`),ae(o))}async function Ds(e,t){if(e.origin===or&&e.installCommand){He.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await Rs(e.installCommand,t?.scope);return r.exitCode===0?await _s(e.name,r.duration_ms,t?.scope):await Os(e.name,new Error(r.stderr||"Install failed")),r}if(qt(e.name)){He.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await so(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await _s(e.name,r.duration_ms,t?.scope):await Os(e.name,new Error(r.stderr||"Install failed")),r}return He.debug(`[${e.name}] Routing to internal installer`),Ie(e.name,t)}function Ns(e){return "exitCode"in e}function Fs(){let e=K(s=>s.installedItems),t=K(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await Ds(s,c);if(Ns(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");K.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await Ur(s,c),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async(s,c)=>{let l=e.find(u=>u.name===s)?.status==="enabled"?"disabled":"enabled";await zt(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Br(s),K.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var Gr=S("mcp");function Xt(e,t){e.silent?oe({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):k(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Ks(e,t){e.silent?X({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(V(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function Ru(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function ao(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function js(e,t,r){if(!await Q())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return Xt(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}Gr.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Ru(e,t,r.transport,r.scope);if(!r.force){let i=p(e),s=p(n);if(!await Je(`Install external MCP "${i}"?
19
+ `);}function bt(e){process.stdout.write(JSON.stringify(e,null,2)+`
20
+ `);}function Y(e){process.stdout.write(JSON.stringify(e)+`
21
+ `);}function ie(e){process.stderr.write(JSON.stringify(e)+`
22
+ `);}function N(e){return e instanceof Error?e.message:String(e)}function Tr(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function nc(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var xe=["clientId","clientSecret","tenant"],oc={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function fi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),u=useRef(0),{setCredentials:g,setJustAuthenticated:v}=me(),{setFocus:d}=f();useInput((h,T)=>{if(!a){if(T.shift&&T.tab){let y=xe.indexOf(r);y>0&&n(xe[y-1]);}else if(T.tab){let y=xe.indexOf(r);y<xe.length-1&&n(xe[y+1]);}else if(T.return)if(r==="tenant")E();else {let y=xe.indexOf(r);n(xe[y+1]);}}},{isActive:true});let E=async()=>{let h={};for(let T of xe)e[T].trim()||(h[T]="This field is required");if(Object.keys(h).length>0){i(h);let T=xe.find(y=>h[y]);T&&n(T);return}l(true),c(null),u.current+=1;try{await rt({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:T,...y}=e;g(y),v(!0),f.getState().setScreen("bundleSetup"),d("bundleList"),b(x.CLI_SESSION_STARTED,{cli_version:Ke,os:process.platform,node_version:process.version,duration_ms:Ue(),interface:"tui"}).catch(()=>{});}catch(T){let y=T instanceof Error?T.message:"Authentication failed";c(y),si(x.CLI_AUTH_FAILED,{error_code:nc(T),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(T=>({...T,clientSecret:""}));}},m=h=>T=>{t(y=>({...y,[h]:T})),o[h]&&i(y=>({...y,[h]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Mo," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:xe.map(h=>jsx(Box,{marginBottom:1,children:jsx(mi,{label:oc[h],value:e[h],onChange:m(h),masked:h==="clientSecret",isActive:r===h&&!a,error:o[h]})},h))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",p(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Cr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(sc,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Ke]})})]})}var Mn={discover:"Discover",installed:"Installed"},ac=Object.keys(Mn);function xi(){let e=f(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ac.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${Mn[t]} `}):jsx(Text,{dimColor:true,children:` ${Mn[t]} `})},t))})}var Z=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function bi(){let e=f(s=>s.focus),t=Z(s=>s.query),r=Z(s=>s.cursorPosition),n=e==="search",o=t.slice(0,r),i=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var pc=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...gt[e]})),dc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Oo[e]}));function vi(){let e=f(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),pc.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),dc.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function Pi({type:e}){let{label:t,color:r}=gt[e];return jsx(Text,{color:r,children:t})}function ki({origin:e}){return e===Lt?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Ar=gc.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(Pi,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(ki,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Tr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Pt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Ai({items:e,emptyMessage:t}){let r=f(a=>a.selectedIndex);if(e.length===0)return jsx(Pt,{message:t});let n=Math.max(0,r-Math.floor(Oe/2)),o=Math.min(e.length,n+Oe);o===e.length&&(n=Math.max(0,o-Oe));let i=e.slice(n,o),s=n,c=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((a,l)=>jsx(Ar,{item:a,isSelected:n+l===r},a.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:c>0?`\u2193 ${c} more below`:" "})})]})}function _i({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Oi({groups:e,emptyMessage:t}){let r=f(d=>d.selectedIndex),n=[],o=0;for(let d of e){n.push({kind:"header",label:d.label,pathHint:d.pathHint,key:`h-${d.scope}`});for(let E of d.items)n.push({kind:"item",item:E,itemIndex:o,key:`i-${d.scope}-${E.name}`}),o++;}if(o===0)return jsx(Pt,{message:t});let s=n.findIndex(d=>d.kind==="item"&&d.itemIndex===r),c=s>=0?s:0,a=Math.max(0,c-Math.floor(Oe/2)),l=Math.min(n.length,a+Oe);l===n.length&&(a=Math.max(0,l-Oe));let u=n.slice(a,l),g=a,v=n.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),u.map(d=>d.kind==="header"?jsx(_i,{label:d.label,pathHint:d.pathHint},d.key):jsx(Ar,{item:d.item,isSelected:d.itemIndex===r},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:v>0?`\u2193 ${v} more below`:" "})})]})}var bc={discover:"Discover",installed:"Installed"};function Ni({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(bi,{}),jsx(vi,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:bc[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(Oi,{groups:n,emptyMessage:r}):jsx(Ai,{items:e,emptyMessage:r})]})}function Fi({filteredItems:e,emptyMessage:t,groups:r}){let n=f(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Ni,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Ni,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Ec={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Plugin | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select"};function Lr(){let e=f(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:Ec[e]})})}function Ki({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",p(e)]})}):null}function Rr({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Lc,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function _r({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ut({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=f(a=>a.focus),[s,c]=useState(0);return useInput((a,l)=>{l.upArrow?c(u=>u>0?u-1:u):l.downArrow?c(u=>u<t.length-1?u+1:u):l.return?n(t[s]):l.escape&&o();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",a]}),r?.[a]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[a]]})]},l))})]})}var Jn=Object.entries(Rt),zi=[...Jn.map(([,e])=>e.actionLabel),"Cancel"],qi=Object.fromEntries(Jn.map(([,e])=>[e.actionLabel,e.description]));function Wi(e){let t=Jn.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function Yi({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=Wi(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(ut,{itemName:`${e} \u2014 Choose scope`,actions:zi,descriptions:qi,onAction:i,onClose:s}):jsx(ut,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Or({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=f(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?n("idle"):i==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function es({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Or({activeFocus:"actionMenu",onConfirm:()=>i(t)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let g=r==="enabled"?"Disable":"Enable",v=o&&p(o),d=v?`Update to v${v}`:"Update";return jsx(ut,{itemName:e,actions:n?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===g?s(t):h.startsWith("Update")?c?.():a();},onClose:a})}function ns({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Or({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ut,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function os(e,t){let r=U.resolve(t);await Ie.mkdir(r,{recursive:true});let n=U.join(U.dirname(r),`${randomUUID()}.zip`);try{await Ie.writeFile(n,e),await Kc(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let s=U.resolve(r,o.fileName);if(!s.startsWith(r+U.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(U.resolve(U.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Ie.unlink(n);}catch{}}}async function Vn(e){await Ie.rm(e,{recursive:true,force:true});}async function Je(){let e=Bo();await Ie.mkdir(U.dirname(e),{recursive:true});try{await Ie.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await jc.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var Jc={user:"global",project:"project",local:"local"};function Fr(e){return e?Jc[e]:"global"}var be=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},He=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};function zt(){return Rl.create({prefix:It("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Fe();e.headers.set("Authorization",`Bearer ${t}`);let r=await D();r?.tenant&&Ze.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Vc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function is(e){if(!e||!Vc.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function ve(){try{let{plugins:e}=await zt().get("v1/plugins/catalog").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${e.message}`):e}}async function Tt(e){is(e);try{return await zt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function ss(e){is(e);try{let t=await zt().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Ur(){try{let{profiles:e}=await zt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}var Gc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zc=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Kr(e){if(!Gc.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function qc(e){if(!zc.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var Ve=S("installer");function Wc(e,t){let r=`${e}@${O}`,o=Le().plugins[r];if(o&&!t)throw new be(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Xc(e,t,r){r&&await Vn(t);try{Ve.debug(`[${t}] Extracting archive...`),await os(e,t);}catch(n){throw await Vn(t),n}}function Yc(e,t,r,n,o){let i=Le(),s={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o},c=i.plugins[e]??[];i.plugins[e]=[...c.filter(a=>a.scope!==n),s],pt(i),Gn(e,true,n);}async function Zc(e,t,r,n,o){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:A().interfaceType});}catch(i){Ve.warn(`Failed to send install metrics: ${String(i)}`);}}async function Qc(e,t,r){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(n){Ve.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function Pe(e,t={}){let r=Date.now(),n=null;try{Ve.debug(`[${e}] Acquiring lock...`),n=await Je();let{pluginKey:o,alreadyInstalled:i}=Wc(e,t.force);Ve.debug(`[${e}] Fetching manifest...`);let s=await Tt(e);Kr(s.name),qc(s.version),Ve.debug(`[${e}] Downloading archive...`);let c=await ss(e),a=t.scope??"user",l=Uo(s.name,s.version);await Xc(c,l,!!i&&!!t.force),Yc(o,l,s.version,a,"internal"),as(s,l);let u=Date.now()-r;Ve.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await Zc(s.name,s.version,u,Fr(a),"internal"),g}catch(o){throw await Qc(e,o,"internal"),Ve.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}function eu(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:O,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function us(){let e=cr();if(!z__default.existsSync(e))return null;try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return null}}function tu(){let e=us();if(e)return e;let t=eu(),r=cr();return z__default.mkdirSync(U__default.dirname(r),{recursive:true}),zn(t),t}function zn(e){let t=cr(),r=`${t}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),z__default.renameSync(r,t);}function ru(){let e=Ko(),t={};try{z__default.existsSync(e)&&(t=JSON.parse(z__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[O])return;t[O]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:jo(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),z__default.renameSync(r,e);}function as(e,t){Kr(e.name),ru();let r=Sn(e.name);z__default.mkdirSync(U__default.dirname(r),{recursive:true});try{z__default.lstatSync(r),z__default.rmSync(r,{recursive:!0,force:!0});}catch{}z__default.symlinkSync(t,r);let n=tu();n.plugins.some(i=>i.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),zn(n));}function qn(e){Kr(e);let t=Sn(e);try{z__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=us();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&zn(r);}var ou=S("mcpConfigReader"),iu=500,su=512;function au(){return U__default.join(he__default.homedir(),".claude.json")}function lu(){return U__default.join(process.cwd(),".mcp.json")}function ds(e){if(!z__default.existsSync(e))return null;try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return ou.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wn(e){if(!qt(e))return {};let t=e.mcpServers;return qt(t)?t:{}}function Xn(e,t){return Object.keys(e).slice(0,iu).map(n=>({name:p(n.slice(0,su)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function fs(){let e=[],t=au(),r=ds(t);if(qt(r)){let c=r,a=Wn(c);e.push(...Xn(a,"user"));let l=process.cwd();if(qt(c.projects)){let u=c.projects[l];if(qt(u)){let g=Wn(u);e.push(...Xn(g,"local"));}}}let n=lu(),o=ds(n),i=Wn(o);e.push(...Xn(i,"project"));let s=new Map;for(let c of e){let a=`${c.name}@${c.scope}`;s.has(a)||s.set(a,c);}return [...s.values()]}var ae=S("storage");async function uu(e,t){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:A().interfaceType});}catch(r){ae.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function pu(e,t,r){let n=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:A().interfaceType}).catch(o=>ae.warn(`Failed to send ${t} metrics: ${String(o)}`));}function ys(){return U__default.join(he__default.homedir(),".claude","plugins","installed_plugins.json")}function du(){return U__default.join(he__default.homedir(),".claude","plugins")}function gs(e){let t=U__default.resolve(e),r=U__default.resolve(du()),n=U__default.resolve(U__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+U__default.sep)||t===r,i=t.startsWith(n+U__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Ss(e="user"){return e==="local"?U__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?U__default.join(process.cwd(),".claude","settings.json"):U__default.join(he__default.homedir(),".claude","settings.json")}function Le(){let e=ys();if(!z__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function mu(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function hs(e,t){try{z__default.mkdirSync(U__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),z__default.renameSync(r,e);}catch(r){throw mu(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function pt(e){hs(ys(),e);}function Wt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function fu(e,t){let r=U__default.join(e,".claude-plugin"),n=U__default.join(r,"plugin.json");if(z__default.existsSync(n))try{return JSON.parse(z__default.readFileSync(n,"utf-8"))}catch{return null}let o=U__default.join(r,"marketplace.json");if(z__default.existsSync(o))try{let i=JSON.parse(z__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function eo(e="user"){let t=Ss(e);if(!z__default.existsSync(t))return {};try{return JSON.parse(z__default.readFileSync(t,"utf-8"))}catch{return {}}}function ws(e,t="user"){hs(Ss(t),e);}function gu(e,t){let{name:r,marketplace:n}=Wt(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Wt(s).name===r)[0],!o)throw ae.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function yu(e,t){let{name:r,marketplace:n}=Wt(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Wt(s).name===r)[0],o?{key:o,name:r}:null}function Yn(e="user"){return eo(e).enabledPlugins??{}}function Zn(e,t="user"){let r=eo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,ws(r,t);}function Gn(e,t,r="user"){let n=eo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},ws(n,r);}function Su(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function Ee(){let e=Le(),t=Yn(),r=Yn("project"),n=Yn("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:v}=Wt(l),d=u.map(m=>m.scope==="managed"?{...m,scope:"user"}:m);return Su(d).map(m=>{let h=fu(m.installPath,g),y=(o[m.scope]??t)[l];return {name:g,marketplace:v,version:m.version&&m.version!=="unknown"?m.version:void 0,installedAt:m.installedAt,installPath:m.installPath,scope:m.scope,description:h?.description,author:h?.author,status:y===false?"disabled":"enabled"}})}),s=fs(),c=new Set(i.map(l=>`${l.name}@${l.scope}`)),a=s.filter(l=>!c.has(`${l.name}@${l.scope}`));return [...i,...a]}async function jr(e,t){ae.debug(`[${e}] Acquiring lock to uninstall`);let r=await Je();try{let n=Le(),o=yu(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=o,c=n.plugins[i];if(t){let a=c.find(g=>g.scope===t);if(!a)throw new Error(`Plugin '${s}' is not installed in ${t} scope`);ae.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),gs(a.installPath);let l=U__default.dirname(a.installPath);ae.debug(`[${s}] Removing directory: ${l}`),z__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(g=>g.scope!==t);if(u.length===0){let{[i]:g,...v}=n.plugins;pt({...n,plugins:v}),Zn(i,t),qn(s);}else n.plugins[i]=u,pt(n),Zn(i,t);}else {ae.debug(`[${s}] Resolved key: ${i}`);for(let u of c){gs(u.installPath);let g=U__default.dirname(u.installPath);ae.debug(`[${s}] Removing directory: ${g}`),z__default.rmSync(g,{recursive:!0,force:!0}),Zn(i,u.scope);}qn(s);let{[i]:a,...l}=n.plugins;pt({...n,plugins:l});}await uu(s,c[0].origin??"internal"),ae.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function Xt(e,t,r){ae.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Je();try{let o=Le(),{key:i,name:s}=gu(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";ae.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),Gn(i,t==="enabled",a),pu(s,t,l),ae.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var j=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Ee()})}));var F=["discover","installed"];function xs(e,t,r){if(t.rightArrow||t.tab){let n=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(n+1)%F.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let n=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(n-1+F.length)%F.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function Is(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o-1+F.length)%F.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o+1)%F.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o+1)%F.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function bs(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function vs(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function Jr(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=f.getState();for(let i of e)if(i.type==="setTab")t(i.tab);else if(i.type==="setFocus")r(i.focus);else if(i.type==="setSelectedIndex")n(i.index);else if(i.type==="setActionMenuOpen")o(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:c,setCursorPosition:a,cursorPosition:l}=Z.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?f.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?f.getState().selectAllTypes():i.type==="toggleOriginFilter"?f.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&f.getState().selectAllOrigins();}function Ps({listLength:e}){let t=f(m=>m.focus),r=f(m=>m.selectedIndex),n=f(m=>m.actionMenuOpen),o=f(m=>m.setFocus),i=f(m=>m.setActionMenuOpen),s=Z(m=>m.query),c=Z(m=>m.setQuery),a=Z(m=>m.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:m,setCursorPosition:h}=Z.getState();h(m.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let m=setTimeout(()=>g(s),300);return ()=>clearTimeout(m)},[s]),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Jr(xs(m,h,{activeTab:T}));},{isActive:t==="tabs"}),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Jr(Is(m,h,{activeTab:T,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((m,h)=>{Jr(bs(m,h));},{isActive:t==="actionMenu"}),useInput((m,h)=>{let T=vs(m,h,Z.getState().query),y=T.queryUpdate;if(Jr(T.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:$,setCursorPosition:H}=Z.getState();if("backspace"in y)$>0&&(c(L.slice(0,$-1)+L.slice($)),H($-1));else if("append"in y)c(L.slice(0,$)+y.append+L.slice($)),H($+y.append.length);else if("cursorMove"in y){let W=$+y.cursorMove;W>=0&&W<=L.length&&H(W);}}},{isActive:t==="search"});let v=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(m=>{let{setSelectedIndex:h,selectedIndex:T}=f.getState();m===0?h(0):T>=m&&h(m-1);},[]),E=useCallback(m=>{if(!u)return l.current=m.length,m;let h=u.toLowerCase(),T=m.filter(y=>y.name.toLowerCase().includes(h)||y.description?.toLowerCase().includes(h));return l.current=T.length,T},[u]);return {actionMenuOpen:n,closeMenu:v,selectedIndex:r,clampIndex:d,filteredItems:E}}function Ts(){let e=f(c=>c.notification),t=f(c=>c.showNotification),r=f(c=>c.clearNotification),n=me(c=>c.justAuthenticated),o=me(c=>c.credentials),i=me(c=>c.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[n,o]),useEffect(()=>{if(!e)return;let c=setTimeout(r,3e3);return ()=>clearTimeout(c)},[e]),{notify:(c,a)=>{t(c,a);}}}function Re(e,t,r=false){return r?true:!no.valid(e)||!no.valid(t)?false:no.gt(t,e)}var _e=S("updater");async function Iu(e,t,r,n,o){try{await b(x.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:A().interfaceType});}catch(i){_e.warn(`Failed to send update metrics: ${String(i)}`);}}function bu(e){let t=Le(),r=`${e}@${O}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Hr(e,t={}){let r=Date.now(),n=null;try{_e.debug(`[${e}] Acquiring lock...`),n=await Je();let o=bu(e);if(!o)throw _e.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;_e.debug(`[${e}] Fetching manifest...`);let l=(await Tt(e)).version;if(!s||!Re(s,l,t.force))throw _e.debug(`[${e}] Already up to date (v${s??"n/a"})`),new He(e,s??"unknown");_e.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await Pe(e,{force:!0,skipMetrics:!0}),g=Date.now()-r;return await Iu(u.name,s,u.version,g,i.origin??"internal"),_e.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){_e.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await Je();let g=Le(),v=`${e}@${O}`;throw g.plugins[v]&&(g.plugins[v][0].version=s,g.plugins[v][0].installPath=c,pt(g),_e.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var vu=S("commands:helpers");async function ee(){let e=await D();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Fe();}catch(t){return vu.debug(`Token validation failed: ${String(t)}`),k("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(k("Starter kit not set. Run: flow auth login"),false):true}async function Ge(e){let t=oo.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function ks(e){let t=oo.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(n.trim());});})}var Pu=/^[^@]+@[^@]+$/;function Yt(e){return Pu.test(e)}function kt(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Eu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Cs(e){if(!Eu.test(e))throw new Error(`Invalid plugin name: "${e}". Plugin names must start with an alphanumeric character and contain only letters, digits, dots, hyphens, underscores, and slashes.`)}var Tu=/^[\w./:@?&=+#%-]+$/;function Vr(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Tu.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Zt=S("claudeProxy"),ao="claude ",$s="flow ",io=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},so=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},ku=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/;function Cu(e){Ls(e);let t=e.slice(ao.length);if(!ku.test(t))throw new so(e)}var Gr=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function Ls(e){if(!e||!/^claude /.test(e))throw new io(e)}async function le(e){Ls(e);let t=e.slice(ao.length).split(/\s+/).filter(Boolean),r=$u(t);Zt.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),i=Date.now()-n;return Zt.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${i}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:i}}catch(o){throw Rs(o)?new Gr:o}}function $u(e){return e.length>=3?e[2]:e.join(" ")}function Rs(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Au(e){return e.startsWith($s)?ao+e.slice($s.length):e}var Lu=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Ru(e,t){return !t||e.includes("--scope")||!Lu.test(e)?e:`${e} --scope ${t}`}async function _s(e,t){let r=e.split("&&").map(o=>Au(o.trim())).filter(Boolean).map(o=>Ru(o,t));if(r.length===0)throw new Error("Empty install command");for(let o of r)Cu(o);Zt.debug(`[installCommand] Executing ${r.length} command(s)`);let n=await le(r[0]);if(n.exitCode!==0)return n;for(let o=1;o<r.length;o++)if(n=await le(r[o]),n.exitCode!==0)return n;return n}async function Ms(e,t,r){let n=kt(e),o=t?.trim();if(!o&&(o=(await ks(`Plugin "${n}" could not be installed.
23
+ If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Vr(o),r?.(),Zt.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let i=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Zt.debug(`[${n}] Marketplace added successfully`);}catch(i){throw Rs(i)?new Gr:i}}var ze=S("installDispatcher");async function Os(e,t,r){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Fr(r),version:"unknown",duration_ms:t,interface:A().interfaceType});}catch(n){ze.warn(`Failed to send external install metrics: ${String(n)}`);}}async function Ds(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){ze.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function lo(e,t){let r=kt(e);Cs(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function co(e,t,r,n){let o=lo(e,n),i=kt(e);r?.onStatus?.(`Installing ${i}...`),ze.debug(`[${e}] Attempting install: ${o}`);let s=await le(o);return s.exitCode===0?s:(ze.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`),r?.onError?.(s.stderr||`Install failed with exit code ${s.exitCode}`),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await Ms(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),ze.debug(`[${e}] Retrying install after marketplace add`),le(o))}async function Ns(e,t){if(e.origin===ar&&e.installCommand){ze.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await _s(e.installCommand,t?.scope);return r.exitCode===0?await Os(e.name,r.duration_ms,t?.scope):await Ds(e.name,new Error(r.stderr||"Install failed")),r}if(Yt(e.name)){ze.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await co(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await Os(e.name,r.duration_ms,t?.scope):await Ds(e.name,new Error(r.stderr||"Install failed")),r}return ze.debug(`[${e.name}] Routing to internal installer`),Pe(e.name,t)}function Fs(e){return "exitCode"in e}function Us(){let e=j(s=>s.installedItems),t=j(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await Ns(s,c);if(Fs(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");j.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await jr(s,c),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async(s,c)=>{let l=e.find(u=>u.name===s)?.status==="enabled"?"disabled":"enabled";await Xt(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Hr(s),j.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var qr=S("mcp");function Qt(e,t){e.silent?ie({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):k(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function js(e,t){e.silent?Y({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(G(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function _u(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function uo(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Bs(e,t,r){if(!await ee())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return Qt(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}qr.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=_u(e,t,r.transport,r.scope);if(!r.force){let i=p(e),s=p(n);if(!await Ge(`Install external MCP "${i}"?
22
24
  This will run: ${s}
23
- [y/N] `))return Gr.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:Eo({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await ae(n);return o?.stop(),i.exitCode!==0?(Xt(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&I(`stdout: ${i.stdout}`),1):(Ks(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),Xt(r,{name:e,action:"add",message:D(i)}),1}}async function Bs(e,t){if(!await Q())return 1;Gr.debug(`[${e}] Starting MCP remove`);let r=ao(e,t.scope);if(!t.force){let o=p(e),i=p(r);if(!await Je(`Remove MCP "${o}"?
25
+ [y/N] `))return qr.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:Co({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await le(n);return o?.stop(),i.exitCode!==0?(Qt(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&I(`stdout: ${i.stdout}`),1):(js(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),Qt(r,{name:e,action:"add",message:N(i)}),1}}async function Js(e,t){if(!await ee())return 1;qr.debug(`[${e}] Starting MCP remove`);let r=uo(e,t.scope);if(!t.force){let o=p(e),i=p(r);if(!await Ge(`Remove MCP "${o}"?
24
26
  This will run: ${i}
25
- [y/N] `))return Gr.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:Eo({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await ae(r);return n?.stop(),o.exitCode!==0?(Xt(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(Ks(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Xt(t,{name:e,action:"remove",message:D(o)}),1}}function Js({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=f(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Fs(),v=async(y,L,A)=>{c(true,y),n();try{await L(),o(r.length),i(A,"success");}catch(J){let q=J instanceof Error?J.message:"Something went wrong";s.error(`[withLoading] ${y} failed: ${q}`),i(q,"error");}finally{c(false);}};return {handleInstall:y=>{e&&t&&v(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&v(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";v(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,y),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let y=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${y}...`),n();try{await g(e.name),o(r.length),i(`\u2713 Updated ${e.name}${y}`,"success");}catch(A){if(A instanceof je)i(A.message,"info");else {let J=A instanceof Error?A.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${J}`),i(J,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:y=>{e&&v(`Removing MCP ${e.name}...`,async()=>{let L=ao(e.name,y),A=await ae(L);if(A.exitCode!==0)throw new Error(A.stderr||"MCP removal failed");K.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Yt=["local","project","user"],Mu=new Set(["--transport","--scope","-s"]);function Hs(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(Mu.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Zt(e,t){return t?`${e}::${t}`:e}function lo(e){return e===_?Ct:or}function Vs(e){return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author.name?p(e.author.name):e.author.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??Ct}}function Gs(e,t){let r=lo(e.marketplace);return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author?.name?p(e.author.name):e.author?.name,status:e.status,scope:e.scope,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??r}}function zs(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return Yt.filter(r=>t.has(r)).map(r=>({scope:r,label:At[r].label,pathHint:At[r].pathHint,items:t.get(r)??[]}))}function qs(e){let t=r=>{if(!r)return 1/0;let n=Yt.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Ws({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>Zt(d.name,d.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(d=>d.type==="mcp").map(d=>d.name.toLowerCase())),[t]),c=useMemo(()=>{let d=new Map(e.map(E=>[Zt(E.name,E.author.name),E]));return t.map(E=>{let m=d.get(Zt(E.name,E.author?.name)),h=m?.version,T=!!h&&!!E.version&&Ae(E.version,h);return {...E,updateAvailable:T,catalogItem:m}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(d=>{if(i.has(Zt(d.name,d.author.name)))return false;if(d.type==="mcp"){let E=d.installCommand?Hs(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||E&&s.has(E))return false}return true}).map(d=>Vs(d)):c.map(d=>Gs(d,d.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let E=d.type??"plugin";if(!n.types.has(E))return false;let m=d.origin??"internal";return n.origins.has(m)}),[a,n]),u=useMemo(()=>{let{types:d}=n;if(d.size===1){if(d.has("skill"))return "skills";if(d.has("mcp"))return "MCPs";if(d.has("plugin"))return "plugins"}return "items"},[n]),g=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),v=useMemo(()=>d=>d?e.find(E=>E.name===d.name&&E.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:v}}function Xs(){let[e,t]=useState([]),[r,n]=useState(true),[o,i]=useState(null),s=useRef(false),c=useCallback(async()=>{n(true),i(null);try{let a=await xe();t(a),s.current||(s.current=!0,b(x.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:a.length}).catch(()=>{}));}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c]),{catalog:e,isLoading:r,error:o,refetch:c}}function Ys(){return {items:K(t=>t.installedItems)}}var Fu=S("catalog");function Zs(){let e=f(R=>R.activeTab),t=f(R=>R.notification),r=f(R=>R.loading),n=f(R=>R.loadingMessage),o=f(R=>R.catalogError),i=f(R=>R.setCatalogError),s=f(R=>R.catalogFilters),c=Y(R=>R.query),{catalog:a,isLoading:l,error:u,refetch:g}=Xs(),{items:v}=Ys(),d=K(R=>R.loadFromDisk),{items:E,emptyMessage:m,getSelectedCatalogItem:h}=Ws({catalog:a,installedItems:v,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:T,closeMenu:y,selectedIndex:L,clampIndex:A,filteredItems:J}=vs({listLength:E.length}),q=J(E),Ee=useMemo(()=>e!=="installed"?q:qs(q),[e,q]),cn=useMemo(()=>e==="installed"?zs(Ee):[],[e,Ee]),H=Ee[L]??null,w=useMemo(()=>h(H),[h,H]),{notify:te}=Es(),{handleInstall:B,handleUninstall:U,handleToggleStatus:un,handleUpdate:pn,handleMcpConfigUninstall:$o}=Js({selectedItem:H,selectedCatalogItem:w,items:E,closeMenu:y,clampIndex:A,notify:te});return useEffect(()=>{d();},[]),useEffect(()=>{A(Ee.length);},[Ee.length,A]),useEffect(()=>{u&&(Fu.error(`[catalog] ${u instanceof Error?u.message:String(u)}`),i("Failed to load catalog"));},[u]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Tr,{}),jsx(wi,{}),jsx(Ni,{filteredItems:Ee,groups:cn,emptyMessage:m}),(r||l)&&jsx($r,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Lr,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(Ui,{message:t.message,type:t.type}),T&&H&&(e==="discover"?jsx(Xi,{itemName:H.name,onInstall:B,onClose:y}):H.type==="mcp"?jsx(rs,{itemName:H.name,itemScope:H.scope??"user",onUninstall:$o,onClose:y}):jsx(Qi,{itemName:H.name,itemScope:H.scope??"user",itemStatus:H.status??"enabled",updateAvailable:H.updateAvailable??false,catalogVersion:w?.version,onUninstall:U,onToggleStatus:R=>un(R),onUpdate:pn,onClose:y})),jsx(Ar,{})]})}var P=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(K.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let i=t().plugins.map(s=>s.name===r?{...s,status:n,error:o}:s);e({plugins:i});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var Bu=3;function ea(){let e=P(a=>a.setStarterKits),t=P(a=>a.setIsLoadingStarterKits),r=P(a=>a.setStarterKitsError),n=P(a=>a.setPluginStatus),o=P(a=>a.setStep),i=P(a=>a.computeSummary),s=useCallback(async()=>{t(true),r(null);try{let a=await Nr();e(a);}catch(a){r(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,r,e]);useEffect(()=>{K.getState().loadFromDisk(),s();},[s]);let c=useCallback(async()=>{let a=P.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){n(u.name,"installing");let g="",v=false;for(let d=1;d<=Bu;d++)try{await Ie(u.name),n(u.name,"success"),v=!0;break}catch(E){if(E instanceof we){n(u.name,"success"),v=true;break}g=E instanceof Error?E.message:"Unknown error";}v||(n(u.name,"failed",g),b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:g,interface:$().interfaceType}).catch(()=>{}));}let l=tt();et("summary_review"),b(x.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),K.getState().loadFromDisk(),i(),o("summary");},[n,i,o]);return {loadStarterKits:s,installSelected:c}}var Qt={cursorDelta:0,confirm:false,back:false};function ta(e,t){return t.upArrow?{...Qt,cursorDelta:-1}:t.downArrow?{...Qt,cursorDelta:1}:t.escape?{...Qt,back:true}:t.return?{...Qt,confirm:true}:Qt}var Ju={cursorDelta:0,select:false};function ra(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Ju}var na=fc.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:p(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:p(t.description)})})]})});var yo=5;function oa({onRetry:e}){let t=P(u=>u.starterKits),r=P(u=>u.selectedStarterKitIndex),n=P(u=>u.isLoadingStarterKits),o=P(u=>u.starterKitsError);if(n)return jsx($r,{message:"Loading Starter Kits..."});if(o)return jsx(Lr,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(It,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor(yo/2)),s=Math.min(t.length,i+yo);s===t.length&&(i=Math.max(0,s-yo));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(na,{starterKit:u,isSelected:i+g===r},u.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var sa=fc.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",p(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var wo=8;function aa(){let e=P(u=>u.selectedStarterKit),t=P(u=>u.plugins),r=P(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(x.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,i=Math.max(0,r-Math.floor(wo/2)),s=Math.min(t.length,i+wo);s===t.length&&(i=Math.max(0,s-wo));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:p(e.name)}),jsx(Text,{dimColor:true,children:p(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(sa,{plugin:u,isCursor:i+g===r},u.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var Zu=["Retry failed","Continue anyway"];function la({name:e,status:t,error:r}){let n=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx($c,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",p(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function ca({onComplete:e,onRetry:t}){let r=P(l=>l.plugins),n=P(l=>l.step),o=P(l=>l.successCount),i=P(l=>l.failedCount),s=P(l=>l.summaryActionIndex),c=r.filter(l=>l.selected),a=useRef(false);return useEffect(()=>{if(n==="summary"&&i===0&&!a.current){a.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[n,i,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:c.map(l=>jsx(la,{name:l.name,status:l.status,error:l.error},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:c.filter(l=>l.status==="failed").map(l=>jsx(la,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Zu.map((l,u)=>jsx(Box,{children:jsxs(Text,{bold:u===s,color:u===s?"cyan":void 0,children:[u===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function ua(){let e=P(w=>w.step),t=P(w=>w.starterKits),r=P(w=>w.selectedStarterKitIndex),n=P(w=>w.setSelectedStarterKitIndex),o=P(w=>w.selectStarterKit),i=P(w=>w.plugins),s=P(w=>w.pluginCursorIndex),c=P(w=>w.setPluginCursorIndex),a=P(w=>w.setStep),l=P(w=>w.summaryActionIndex),u=P(w=>w.setSummaryActionIndex),g=P(w=>w.failedCount),v=P(w=>w.resetForRetry),d=P(w=>w.goBackToList),E=f(w=>w.setScreen),m=f(w=>w.setFocus),h=f(w=>w.focus),T=ue(w=>w.setJustAuthenticated),y=ue(w=>w.justAuthenticated),{loadStarterKits:L,installSelected:A}=ea(),J=useRef(false);useEffect(()=>{e==="bundleList"?(m("bundleList"),J.current||(J.current=true,et("bundle_selection"))):m(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,m]);let q=useCallback(async()=>{let w=P.getState().selectedStarterKit;if(w){let B=await O();B&&await Ze({...B,starterKit:w.slug});}b(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:tt()}).catch(()=>{});let{successCount:te}=P.getState();b(x.CLI_ONBOARDING_COMPLETED,{duration_ms:De(),tools_installed_count:te}).catch(()=>{}),T(false),m("list"),E("main");},[T,m,E]),Ee=useCallback(()=>{v(),A();},[v,A]),cn=useCallback(()=>{L();},[L]),H=useCallback(()=>{m("list"),E("main");},[m,E]);return useInput((w,te)=>{if(te.escape)br("esc"),H();else if(te.upArrow&&r>0)n(r-1);else if(te.downArrow&&r<t.length-1)n(r+1);else if(te.return&&t.length>0){let B=tt();o(t[r]),et("kit_display"),b(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:B}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((w,te)=>{let B=ta(w,te);if(B.cursorDelta!==0){let U=s+B.cursorDelta;U>=0&&U<i.length&&c(U);}if(B.confirm){let U=P.getState().selectedStarterKit;U&&(async()=>(await O())?.starterKit!==U.slug&&b(x.CLI_KIT_ACCEPTED,{bundle_slug:U.slug}).catch(()=>{}))();let un=tt();et("kit_confirmation"),b(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:un}).catch(()=>{});let pn=tt();et("tool_installation"),b(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:pn}).catch(()=>{}),a("installing"),A();}if(B.back){let U=P.getState().selectedStarterKit;U&&b(x.CLI_KIT_REJECTED,{bundle_slug:U.slug}).catch(()=>{}),d();}},{isActive:h==="bundleDetail"}),useInput((w,te)=>{if(g===0)return;let B=ra(w,te);if(B.cursorDelta!==0){let U=l+B.cursorDelta;U>=0&&U<=1&&u(U);}B.select&&(l===0?Ee():q());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Tr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!y&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(oa,{onRetry:cn}),e==="bundleDetail"&&jsx(aa,{}),(e==="installing"||e==="summary")&&jsx(ca,{onComplete:q,onRetry:Ee})]}),jsx(Ar,{})]})}var rp=S("app"),np={auth:mi,bundleSetup:ua,main:Zs};function ma(){f.getState().setScreen("auth"),f.getState().setFocus("auth");}async function ga(){let e=await O();if(!e){ma();return}try{await Oe();}catch(o){rp.debug(`Token validation failed: ${String(o)}`),ma();return}b(x.CLI_SESSION_STARTED,{cli_version:Ne,os:process.platform,node_version:process.version,duration_ms:De(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...r}=e;ue.getState().setCredentials(r),!e.starterKit||e.starterKit.trim()===""?(f.getState().setScreen("bundleSetup"),f.getState().setFocus("bundleList")):(f.getState().setScreen("main"),f.getState().setFocus("list"));}function ya(){let{columns:e,rows:t}=useWindowSize(),r=f(i=>i.screen),n=np[r],{pendingExit:o}=pi();return n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}var Pe=S("auth");function Sa(){W.clearFallbackFile(),hr();}var op=3,ha=3,wa=` \u2139 The data collected during setup is used solely to improve
27
+ [y/N] `))return qr.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:Co({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await le(r);return n?.stop(),o.exitCode!==0?(Qt(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(js(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Qt(t,{name:e,action:"remove",message:N(o)}),1}}function Hs({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=f(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Us(),v=async(y,L,$)=>{c(true,y),n();try{await L(),o(r.length),i($,"success");}catch(H){let W=H instanceof Error?H.message:"Something went wrong";s.error(`[withLoading] ${y} failed: ${W}`),i(W,"error");}finally{c(false);}};return {handleInstall:y=>{e&&t&&v(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&v(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";v(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,y),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let y=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${y}...`),n();try{await g(e.name),o(r.length),i(`\u2713 Updated ${e.name}${y}`,"success");}catch($){if($ instanceof He)i($.message,"info");else {let H=$ instanceof Error?$.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${H}`),i(H,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:y=>{e&&v(`Removing MCP ${e.name}...`,async()=>{let L=uo(e.name,y),$=await le(L);if($.exitCode!==0)throw new Error($.stderr||"MCP removal failed");j.getState().loadFromDisk();},"\u2713 MCP removed");}}}var er=["local","project","user"],Mu=new Set(["--transport","--scope","-s"]);function Vs(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(Mu.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function tr(e,t){return t?`${e}::${t}`:e}function po(e){return e===O?Lt:ar}function Gs(e){return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author.name?p(e.author.name):e.author.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??Lt}}function zs(e,t){let r=po(e.marketplace);return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author?.name?p(e.author.name):e.author?.name,status:e.status,scope:e.scope,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??r}}function qs(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return er.filter(r=>t.has(r)).map(r=>({scope:r,label:Rt[r].label,pathHint:Rt[r].pathHint,items:t.get(r)??[]}))}function Ws(e){let t=r=>{if(!r)return 1/0;let n=er.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Xs({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>tr(d.name,d.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(d=>d.type==="mcp").map(d=>d.name.toLowerCase())),[t]),c=useMemo(()=>{let d=new Map(e.map(E=>[tr(E.name,E.author.name),E]));return t.map(E=>{let m=d.get(tr(E.name,E.author?.name)),h=m?.version,T=!!h&&!!E.version&&Re(E.version,h);return {...E,updateAvailable:T,catalogItem:m}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(d=>{if(i.has(tr(d.name,d.author.name)))return false;if(d.type==="mcp"){let E=d.installCommand?Vs(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||E&&s.has(E))return false}return true}).map(d=>Gs(d)):c.map(d=>zs(d,d.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let E=d.type??"plugin";if(!n.types.has(E))return false;let m=d.origin??"internal";return n.origins.has(m)}),[a,n]),u=useMemo(()=>{let{types:d}=n;if(d.size===1){if(d.has("skill"))return "skills";if(d.has("mcp"))return "MCPs";if(d.has("plugin"))return "plugins"}return "items"},[n]),g=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),v=useMemo(()=>d=>d?e.find(E=>E.name===d.name&&E.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:v}}function Ys(){let[e,t]=useState([]),[r,n]=useState(true),[o,i]=useState(null),s=useRef(false),c=useCallback(async()=>{n(true),i(null);try{let a=await ve();t(a),s.current||(s.current=!0,b(x.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:a.length}).catch(()=>{}));}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c]),{catalog:e,isLoading:r,error:o,refetch:c}}function Zs(){return {items:j(t=>t.installedItems)}}var Uu=S("catalog");function Qs(){let e=f(_=>_.activeTab),t=f(_=>_.notification),r=f(_=>_.loading),n=f(_=>_.loadingMessage),o=f(_=>_.catalogError),i=f(_=>_.setCatalogError),s=f(_=>_.catalogFilters),c=Z(_=>_.query),{catalog:a,isLoading:l,error:u,refetch:g}=Ys(),{items:v}=Zs(),d=j(_=>_.loadFromDisk),{items:E,emptyMessage:m,getSelectedCatalogItem:h}=Xs({catalog:a,installedItems:v,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:T,closeMenu:y,selectedIndex:L,clampIndex:$,filteredItems:H}=Ps({listLength:E.length}),W=H(E),Ce=useMemo(()=>e!=="installed"?W:Ws(W),[e,W]),pn=useMemo(()=>e==="installed"?qs(Ce):[],[e,Ce]),V=Ce[L]??null,w=useMemo(()=>h(V),[h,V]),{notify:re}=Ts(),{handleInstall:J,handleUninstall:K,handleToggleStatus:dn,handleUpdate:mn,handleMcpConfigUninstall:_o}=Hs({selectedItem:V,selectedCatalogItem:w,items:E,closeMenu:y,clampIndex:$,notify:re});return useEffect(()=>{d();},[]),useEffect(()=>{$(Ce.length);},[Ce.length,$]),useEffect(()=>{u&&(Uu.error(`[catalog] ${u instanceof Error?u.message:String(u)}`),i("Failed to load catalog"));},[u]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Cr,{}),jsx(xi,{}),jsx(Fi,{filteredItems:Ce,groups:pn,emptyMessage:m}),(r||l)&&jsx(Rr,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(_r,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(Ki,{message:t.message,type:t.type}),T&&V&&(e==="discover"?jsx(Yi,{itemName:V.name,onInstall:J,onClose:y}):V.type==="mcp"?jsx(ns,{itemName:V.name,itemScope:V.scope??"user",onUninstall:_o,onClose:y}):jsx(es,{itemName:V.name,itemScope:V.scope??"user",itemStatus:V.status??"enabled",updateAvailable:V.updateAvailable??false,catalogVersion:w?.version,onUninstall:K,onToggleStatus:_=>dn(_),onUpdate:mn,onClose:y})),jsx(Lr,{})]})}var P=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(j.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let i=t().plugins.map(s=>s.name===r?{...s,status:n,error:o}:s);e({plugins:i});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var Ju=3;function ta(){let e=P(a=>a.setStarterKits),t=P(a=>a.setIsLoadingStarterKits),r=P(a=>a.setStarterKitsError),n=P(a=>a.setPluginStatus),o=P(a=>a.setStep),i=P(a=>a.computeSummary),s=useCallback(async()=>{t(true),r(null);try{let a=await Ur();e(a);}catch(a){r(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,r,e]);useEffect(()=>{j.getState().loadFromDisk(),s();},[s]);let c=useCallback(async()=>{let a=P.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){n(u.name,"installing");let g="",v=false;for(let d=1;d<=Ju;d++)try{await Pe(u.name),n(u.name,"success"),v=!0;break}catch(E){if(E instanceof be){n(u.name,"success"),v=true;break}g=E instanceof Error?E.message:"Unknown error";}v||(n(u.name,"failed",g),b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:g,interface:A().interfaceType}).catch(()=>{}));}let l=ot();nt("summary_review"),b(x.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),j.getState().loadFromDisk(),i(),o("summary");},[n,i,o]);return {loadStarterKits:s,installSelected:c}}var rr={cursorDelta:0,confirm:false,back:false};function ra(e,t){return t.upArrow?{...rr,cursorDelta:-1}:t.downArrow?{...rr,cursorDelta:1}:t.escape?{...rr,back:true}:t.return?{...rr,confirm:true}:rr}var Hu={cursorDelta:0,select:false};function na(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Hu}var oa=gc.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:p(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:p(t.description)})})]})});var wo=5;function ia({onRetry:e}){let t=P(u=>u.starterKits),r=P(u=>u.selectedStarterKitIndex),n=P(u=>u.isLoadingStarterKits),o=P(u=>u.starterKitsError);if(n)return jsx(Rr,{message:"Loading Starter Kits..."});if(o)return jsx(_r,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Pt,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor(wo/2)),s=Math.min(t.length,i+wo);s===t.length&&(i=Math.max(0,s-wo));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(oa,{starterKit:u,isSelected:i+g===r},u.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var aa=gc.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",p(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var bo=8;function la(){let e=P(u=>u.selectedStarterKit),t=P(u=>u.plugins),r=P(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(x.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,i=Math.max(0,r-Math.floor(bo/2)),s=Math.min(t.length,i+bo);s===t.length&&(i=Math.max(0,s-bo));let c=t.slice(i,s),a=i,l=t.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:p(e.name)}),jsx(Text,{dimColor:true,children:p(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),a>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",a," more above"]})}),c.map((u,g)=>jsx(aa,{plugin:u,isCursor:i+g===r},u.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var Qu=["Retry failed","Continue anyway"];function ca({name:e,status:t,error:r}){let n=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Lc,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",p(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function ua({onComplete:e,onRetry:t}){let r=P(l=>l.plugins),n=P(l=>l.step),o=P(l=>l.successCount),i=P(l=>l.failedCount),s=P(l=>l.summaryActionIndex),c=r.filter(l=>l.selected),a=useRef(false);return useEffect(()=>{if(n==="summary"&&i===0&&!a.current){a.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[n,i,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:c.map(l=>jsx(ca,{name:l.name,status:l.status,error:l.error},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:c.filter(l=>l.status==="failed").map(l=>jsx(ca,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Qu.map((l,u)=>jsx(Box,{children:jsxs(Text,{bold:u===s,color:u===s?"cyan":void 0,children:[u===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function pa(){let e=P(w=>w.step),t=P(w=>w.starterKits),r=P(w=>w.selectedStarterKitIndex),n=P(w=>w.setSelectedStarterKitIndex),o=P(w=>w.selectStarterKit),i=P(w=>w.plugins),s=P(w=>w.pluginCursorIndex),c=P(w=>w.setPluginCursorIndex),a=P(w=>w.setStep),l=P(w=>w.summaryActionIndex),u=P(w=>w.setSummaryActionIndex),g=P(w=>w.failedCount),v=P(w=>w.resetForRetry),d=P(w=>w.goBackToList),E=f(w=>w.setScreen),m=f(w=>w.setFocus),h=f(w=>w.focus),T=me(w=>w.setJustAuthenticated),y=me(w=>w.justAuthenticated),{loadStarterKits:L,installSelected:$}=ta(),H=useRef(false);useEffect(()=>{e==="bundleList"?(m("bundleList"),H.current||(H.current=true,nt("bundle_selection"))):m(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,m]);let W=useCallback(async()=>{let w=P.getState().selectedStarterKit;if(w){let J=await D();J&&await tt({...J,starterKit:w.slug});}b(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ot()}).catch(()=>{});let{successCount:re}=P.getState();b(x.CLI_ONBOARDING_COMPLETED,{duration_ms:Ue(),tools_installed_count:re}).catch(()=>{}),T(false),m("list"),E("main");},[T,m,E]),Ce=useCallback(()=>{v(),$();},[v,$]),pn=useCallback(()=>{L();},[L]),V=useCallback(()=>{m("list"),E("main");},[m,E]);return useInput((w,re)=>{if(re.escape)Pr("esc"),V();else if(re.upArrow&&r>0)n(r-1);else if(re.downArrow&&r<t.length-1)n(r+1);else if(re.return&&t.length>0){let J=ot();o(t[r]),nt("kit_display"),b(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:J}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((w,re)=>{let J=ra(w,re);if(J.cursorDelta!==0){let K=s+J.cursorDelta;K>=0&&K<i.length&&c(K);}if(J.confirm){let K=P.getState().selectedStarterKit;K&&(async()=>(await D())?.starterKit!==K.slug&&b(x.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let dn=ot();nt("kit_confirmation"),b(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:dn}).catch(()=>{});let mn=ot();nt("tool_installation"),b(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:mn}).catch(()=>{}),a("installing"),$();}if(J.back){let K=P.getState().selectedStarterKit;K&&b(x.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),d();}},{isActive:h==="bundleDetail"}),useInput((w,re)=>{if(g===0)return;let J=na(w,re);if(J.cursorDelta!==0){let K=l+J.cursorDelta;K>=0&&K<=1&&u(K);}J.select&&(l===0?Ce():W());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Cr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!y&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(ia,{onRetry:pn}),e==="bundleDetail"&&jsx(la,{}),(e==="installing"||e==="summary")&&jsx(ua,{onComplete:W,onRetry:Ce})]}),jsx(Lr,{})]})}var np=S("app"),op={auth:fi,bundleSetup:pa,main:Qs};function fa(){f.getState().setScreen("auth"),f.getState().setFocus("auth");}async function ya(){let e=await D();if(!e){fa();return}try{await Fe();}catch(o){np.debug(`Token validation failed: ${String(o)}`),fa();return}b(x.CLI_SESSION_STARTED,{cli_version:Ke,os:process.platform,node_version:process.version,duration_ms:Ue(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...r}=e;me.getState().setCredentials(r),!e.starterKit||e.starterKit.trim()===""?(f.getState().setScreen("bundleSetup"),f.getState().setFocus("bundleList")):(f.getState().setScreen("main"),f.getState().setFocus("list"));}function Sa(){let{columns:e,rows:t}=useWindowSize(),r=f(i=>i.screen),n=op[r],{pendingExit:o}=di();return n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}var ke=S("auth");function wa(){X.clearFallbackFile(),wr();}var ip=3,ha=3,xa=` \u2139 The data collected during setup is used solely to improve
26
28
  Flow's internal tools and will not be shared externally.
27
- `;function rr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:i=""}=t;process.stdout.write(e+i);let s=i,c=u=>{if(u===""){a(),n(new Error("SIGINT"));return}if(u==="\r"||u===`
29
+ `;function ir(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:i=""}=t;process.stdout.write(e+i);let s=i,c=u=>{if(u===""){a(),n(new Error("SIGINT"));return}if(u==="\r"||u===`
28
30
  `){a(),process.stdout.write(`
29
- `),r(s);return}if(u==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(s+=u,process.stdout.write(o?"*".repeat(u.length):u));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",c),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",c);})}async function xa(){for(let e=1;e<=ha;e++)try{return await Nr()}catch{if(e===ha)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Ia(){let e=await xa();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
31
+ `),r(s);return}if(u==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(s+=u,process.stdout.write(o?"*".repeat(u.length):u));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",c),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",c);})}async function Ia(){for(let e=1;e<=ha;e++)try{return await Ur()}catch{if(e===ha)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function ba(){let e=await Ia();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
30
32
  `+C.cyan(" ? ")+`Starter Kit:
31
33
  `),e.forEach((t,r)=>{process.stdout.write(` ${C.cyan(`${r+1})`)} ${p(t.name)}
32
34
  `);}),process.stdout.write(`
33
- `);;){let t=(await rr(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
34
- `));}}async function ba(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
35
+ `);;){let t=(await ir(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
36
+ `));}}async function va(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
35
37
  Starter kit '${p(e.name)}' has no plugins to install.
36
38
  `)),true;process.stdout.write(`
37
39
  Installing ${e.plugins.length} plugins from '${p(e.name)}'...
38
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(C.dim(` [${i}/${n}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=op;c++)try{await Ie(o),t++,s=!0;break}catch(a){if(a instanceof we){t++,s=true;break}}s?process.stdout.write(C.green(` done
40
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(C.dim(` [${i}/${n}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=ip;c++)try{await Pe(o),t++,s=!0;break}catch(a){if(a instanceof be){t++,s=true;break}}s?process.stdout.write(C.green(` done
39
41
  `)):(r++,process.stdout.write(C.red(` failed
40
42
  `)));}return r===0?process.stdout.write(C.green(` \u2713 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed successfully.
41
43
  `)):process.stdout.write(C.yellow(` \u26A0 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
42
- `)),r===0}async function ip(e){Sa(),process.stdout.write(`
43
- `+wa+`
44
- `),Pe.debug(`[${e.tenant}] Authenticating tenant`);try{await Qe(e);}catch(t){let r=p(t instanceof Error?t.message:"unknown error");return Pe.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${r}
45
- `)),1}try{let t;if(e.starterKit){let r=await xa(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(C.red(` \u2717 Starter kit '${p(e.starterKit)}' not found.
44
+ `)),r===0}async function sp(e){wa(),process.stdout.write(`
45
+ `+xa+`
46
+ `),ke.debug(`[${e.tenant}] Authenticating tenant`);try{await rt(e);}catch(t){let r=p(t instanceof Error?t.message:"unknown error");return ke.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${r}
47
+ `)),1}try{let t;if(e.starterKit){let r=await Ia(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(C.red(` \u2717 Starter kit '${p(e.starterKit)}' not found.
46
48
  `)),process.stderr.write(` Available starter kits:
47
49
  `);for(let o of r)process.stderr.write(` - ${p(o.slug)} (${p(o.name)})
48
- `);return 1}t=n;}else t=await Ia();return await Ze({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug}),await ba(t),Pe.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${e.tenant}
50
+ `);return 1}t=n;}else t=await ba();return await tt({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug}),await va(t),ke.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${e.tenant}
49
51
 
50
- `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=p(t instanceof Error?t.message:"unknown error");return Pe.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${r}
51
- `)),1}}async function sp(){Sa(),Pe.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
52
- `),process.stdout.write(wa+`
53
- `);let e=(await rr(C.cyan(" ? ")+"Client ID: ")).trim(),t=(await rr(C.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await rr(C.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return Pe.error("[auth] Validation failed: all fields are required"),process.stderr.write(C.red(` \u2717 All fields are required
54
- `)),1;Pe.debug(`[${r}] Authenticating tenant`);try{await Qe({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return Pe.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${i}
55
- `)),1}let n=await Ia();return await Ze({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug}),await ba(n),Pe.info(`[${r}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${r}
52
+ `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=p(t instanceof Error?t.message:"unknown error");return ke.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${r}
53
+ `)),1}}async function ap(){wa(),ke.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
54
+ `),process.stdout.write(xa+`
55
+ `);let e=(await ir(C.cyan(" ? ")+"Client ID: ")).trim(),t=(await ir(C.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await ir(C.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return ke.error("[auth] Validation failed: all fields are required"),process.stderr.write(C.red(` \u2717 All fields are required
56
+ `)),1;ke.debug(`[${r}] Authenticating tenant`);try{await rt({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return ke.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${i}
57
+ `)),1}let n=await ba();return await tt({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug}),await va(n),ke.info(`[${r}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${r}
56
58
 
57
- `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return Pe.error(`[auth] Unexpected error: ${t}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${t}
58
- `)),1}}async function Po(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return ip({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await sp()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
59
- `),130;throw t}}async function ap(){try{return process.stdout.write(`
60
- `),(await rr(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
59
+ `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return ke.error(`[auth] Unexpected error: ${t}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${t}
60
+ `)),1}}async function ko(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return sp({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await ap()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
61
+ `),130;throw t}}async function lp(){try{return process.stdout.write(`
62
+ `),(await ir(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
61
63
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
62
- `),130;throw e}}async function va(e){if(!await O())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
63
- `)),0;if(!e){let t=await ap();if(t!==null)return t}try{return await Xo(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
64
+ `),130;throw e}}async function Pa(e){if(!await D())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
65
+ `)),0;if(!e){let t=await lp();if(t!==null)return t}try{return await Yo(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
64
66
  `)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
65
- `)),1}}async function Pa(){let e=await O();return e?await ht()?(process.stdout.write(`
67
+ `)),1}}async function Ea(){let e=await D();return e?await xt()?(process.stdout.write(`
66
68
  `+C.bold(` Authenticated
67
69
  `)),process.stdout.write(C.dim(" Tenant: ")+p(e.tenant)+`
68
70
  `),process.stdout.write(C.dim(" Client ID: ")+p(e.clientId)+`
69
71
  `),process.stdout.write(C.dim(" Starter Kit: ")+p(e.starterKit??"not set")+`
70
- `),process.stdout.write(C.dim(" Config: ")+p(await Yo())+`
72
+ `),process.stdout.write(C.dim(" Config: ")+p(await Zo())+`
71
73
  `),process.stdout.write(`
72
- `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function lp(e){let t=be(),r;try{r=await xe();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(wt(r.map(o=>({...o,installed:n.has(o.name)}))),0):(vr(["","Name","Version","Category","Status"],r.map(o=>[n.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",n.has(o.name)?"installed":"available"])),0)}async function cp(e){let t=be(),r=await xe(),n=new Map(r.map(i=>[i.name,i])),o=t.map(i=>{let s=n.get(i.name);return s&&i.version&&s.version&&Ae(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(wt(o),0):(vr(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
74
+ `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function cp(e){let t=Ee(),r;try{r=await ve();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(bt(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Er(["","Name","Version","Category","Status"],r.map(o=>[n.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",n.has(o.name)?"installed":"available"])),0)}async function up(e){let t=Ee(),r=await ve(),n=new Map(r.map(i=>[i.name,i])),o=t.map(i=>{let s=n.get(i.name);return s&&i.version&&s.version&&Re(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(bt(o),0):(Er(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
73
75
  ${o.length} plugin(s) outdated.
74
- `),0)}async function up(e){let t=be();if(b(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return wt(t),0;let r=[];try{r=await xe();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=Yt.indexOf(i.scope??"user"),a=Yt.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return vr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=n.get(i.name),c=s?.type??"plugin",a=s?.origin??lo(i.marketplace);return [i.name??"",i.version??"n/a",dt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",Pr(i.installedAt??"")]})),process.stdout.write(`
76
+ `),0)}async function pp(e){let t=Ee();if(b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return bt(t),0;let r=[];try{r=await ve();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=er.indexOf(i.scope??"user"),a=er.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return Er(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=n.get(i.name),c=s?.type??"plugin",a=s?.origin??po(i.marketplace);return [i.name??"",i.version??"n/a",gt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",Tr(i.installedAt??"")]})),process.stdout.write(`
75
77
  ${t.length} plugin(s) installed.
76
- `),0}async function Ea(e){if(!await Q())return 1;try{return e.available?await lp(e):e.outdated?await cp(e):await up(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var M=S("manage");function Qr(e,t){return t?be().find(r=>r.name===e&&r.scope===t):be().find(r=>r.name===e)}function pp(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Eo({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function dp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=p(e),c=p(io(e,r.scope));if(!await Je(`${t}Install external plugin "${s}"?
78
+ `),0}async function Ta(e){if(!await ee())return 1;try{return e.available?await cp(e):e.outdated?await up(e):await pp(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var M=S("manage");function tn(e,t){return t?Ee().find(r=>r.name===e&&r.scope===t):Ee().find(r=>r.name===e)}function dp(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Co({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function mp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=p(e),c=p(lo(e,r.scope));if(!await Ge(`${t}Install external plugin "${s}"?
77
79
  This will run: ${c}
78
- [y/N] `))return M.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Eo({text:`${t}Installing ${e}...`}).start());}let i=o?pp(t,o):void 0;try{let s=await so(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?oe({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?X({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):V(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=D(s);return r.silent?oe({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function mp(e,t,r){let n=r.silent?void 0:Eo({text:`${t}Installing ${e}...`}).start();if(qt(e))return dp(e,t,r,n);try{let o=await Ie(e,r);return n?.stop(),r.silent?X({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):V(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof we)return r.silent?X({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let i=D(o);return r.silent?oe({status:"error",plugin:e,message:i}):k(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function fp(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
79
- Installation summary: ${t} succeeded, ${r} failed`);}async function Ta(e,t={}){if(!await Q())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await mp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?X({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):fp(r)),r.some(n=>!n.success)?1:0}async function ka(e,t){if(!await Q())return 1;if(M.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Qr(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;let n=p(r.name),o=r.version?p(r.version):void 0,i=t.scope?` (${t.scope})`:"";if(!await Je(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return M.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return M.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Ur(e,t.scope),M.info(`[${e}] Uninstalled successfully`),V("Plugin removed successfully"),0}catch(r){return M.error(`[${e}] Failed to uninstall: ${D(r)}`),k(D(r)),1}}async function Ca(e,t={}){if(!await Q())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=Qr(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return M.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return M.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await zt(e,"enabled",t.scope),M.info(`[${e}] Enabled successfully`),V(`${r.name} enabled successfully`),0}catch(n){return M.error(`[${e}] Failed to enable: ${D(n)}`),k(D(n)),1}}async function Aa(e,t={}){if(!await Q())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=Qr(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return M.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return M.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await zt(e,"disabled",t.scope),M.info(`[${e}] Disabled successfully`),V(`${r.name} disabled successfully`),0}catch(n){return M.error(`[${e}] Failed to disable: ${D(n)}`),k(D(n)),1}}async function $a(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await Br(e,r);return r.silent?X({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):V(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof je)return r.silent?X({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=D(n);return r.silent?oe({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function gp(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
80
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function yp(e,t,r){try{let n=await vt(e);Ae(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return k(D(n)),1}return 0}function hp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Sp(e,t,r){let n=t.get(e.name);return n?e.version&&Ae(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function wp(e,t){try{let r=await xe(),n=hp(r),o=0;for(let i of e)Sp(i,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return k(D(r)),1}return 0}async function xp(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await $a(e[n].name,o,t);r.push(i);}return t.silent?X({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):gp(r),r.some(n=>!n.success)?1:0}async function La(e,t={}){if(!await Q())return 1;if(e){let o=Qr(e,t.scope);return o?t.dryRun?yp(e,o.version??"",t):(await $a(e,"",t)).success?0:1:(t.silent?oe({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let n=be().filter(o=>o.marketplace===_);return n.length===0?(t.silent?X({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?wp(n,t):xp(n,t)}var Ra=S("marketplace");function bp(e){return `claude plugin marketplace add ${e}`}async function Ma(e,t){if(!await Q())return 1;let r;try{r=Jr(e);}catch(i){let s=D(i);return t.silent?oe({status:"error",source:e,message:s}):k(s),1}Ra.debug(`[marketplace] Adding marketplace source: ${r}`);let n=bp(r);if(!t.force){let i=p(r),s=p(n);if(!await Je(`Add marketplace "${i}"?
80
+ [y/N] `))return M.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Co({text:`${t}Installing ${e}...`}).start());}let i=o?dp(t,o):void 0;try{let s=await co(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?ie({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?Y({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):G(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=N(s);return r.silent?ie({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function fp(e,t,r){let n=r.silent?void 0:Co({text:`${t}Installing ${e}...`}).start();if(Yt(e))return mp(e,t,r,n);try{let o=await Pe(e,r);return n?.stop(),r.silent?Y({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):G(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof be)return r.silent?Y({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let i=N(o);return r.silent?ie({status:"error",plugin:e,message:i}):k(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function gp(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
81
+ Installation summary: ${t} succeeded, ${r} failed`);}async function ka(e,t={}){if(!await ee())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await fp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?Y({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):gp(r)),r.some(n=>!n.success)?1:0}async function Ca(e,t){if(!await ee())return 1;if(M.debug(`[${e}] Looking up installed plugin`),!t.force){let r=tn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;let n=p(r.name),o=r.version?p(r.version):void 0,i=t.scope?` (${t.scope})`:"";if(!await Ge(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return M.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return M.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await jr(e,t.scope),M.info(`[${e}] Uninstalled successfully`),G("Plugin removed successfully"),0}catch(r){return M.error(`[${e}] Failed to uninstall: ${N(r)}`),k(N(r)),1}}async function $a(e,t={}){if(!await ee())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=tn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return M.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return M.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Xt(e,"enabled",t.scope),M.info(`[${e}] Enabled successfully`),G(`${r.name} enabled successfully`),0}catch(n){return M.error(`[${e}] Failed to enable: ${N(n)}`),k(N(n)),1}}async function Aa(e,t={}){if(!await ee())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=tn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return M.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return M.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Xt(e,"disabled",t.scope),M.info(`[${e}] Disabled successfully`),G(`${r.name} disabled successfully`),0}catch(n){return M.error(`[${e}] Failed to disable: ${N(n)}`),k(N(n)),1}}async function La(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await Hr(e,r);return r.silent?Y({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):G(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof He)return r.silent?Y({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=N(n);return r.silent?ie({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function yp(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
82
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Sp(e,t,r){try{let n=await Tt(e);Re(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return k(N(n)),1}return 0}function hp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function wp(e,t,r){let n=t.get(e.name);return n?e.version&&Re(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function xp(e,t){try{let r=await ve(),n=hp(r),o=0;for(let i of e)wp(i,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return k(N(r)),1}return 0}async function Ip(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await La(e[n].name,o,t);r.push(i);}return t.silent?Y({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):yp(r),r.some(n=>!n.success)?1:0}async function Ra(e,t={}){if(!await ee())return 1;if(e){let o=tn(e,t.scope);return o?t.dryRun?Sp(e,o.version??"",t):(await La(e,"",t)).success?0:1:(t.silent?ie({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let n=Ee().filter(o=>o.marketplace===O);return n.length===0?(t.silent?Y({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?xp(n,t):Ip(n,t)}var _a=S("marketplace");function vp(e){return `claude plugin marketplace add ${e}`}async function Ma(e,t){if(!await ee())return 1;let r;try{r=Vr(e);}catch(i){let s=N(i);return t.silent?ie({status:"error",source:e,message:s}):k(s),1}_a.debug(`[marketplace] Adding marketplace source: ${r}`);let n=vp(r);if(!t.force){let i=p(r),s=p(n);if(!await Ge(`Add marketplace "${i}"?
81
83
  This will run: ${s}
82
- [y/N] `))return Ra.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:Eo({text:`Adding marketplace "${p(r)}"...`}).start();try{let i=await ae(n);return o?.stop(),i.exitCode!==0?(t.silent?oe({status:"error",source:r,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(k(`Failed to add marketplace "${r}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&I(`stdout: ${i.stdout}`)),1):(t.silent?X({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(V(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&I(i.stdout)),0)}catch(i){o?.stop();let s=D(i);return t.silent?oe({status:"error",source:r,message:s}):k(`Failed to add marketplace "${r}": ${s}`),1}}async function Tp(){return await O()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function kp(){let e=Date.now();try{await xe();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function Cp(){return await ht()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Ap(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function _a(){process.stdout.write(`
84
+ [y/N] `))return _a.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:Co({text:`Adding marketplace "${p(r)}"...`}).start();try{let i=await le(n);return o?.stop(),i.exitCode!==0?(t.silent?ie({status:"error",source:r,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(k(`Failed to add marketplace "${r}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&I(`stdout: ${i.stdout}`)),1):(t.silent?Y({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(G(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&I(i.stdout)),0)}catch(i){o?.stop();let s=N(i);return t.silent?ie({status:"error",source:r,message:s}):k(`Failed to add marketplace "${r}": ${s}`),1}}async function kp(){return await D()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Cp(){let e=Date.now();try{await ve();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function $p(){return await xt()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Ap(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Oa(){process.stdout.write(`
83
85
  `+C.bold(` FlowSetup CLI Diagnostics
84
86
 
85
- `));let e=[{name:"Credentials",fn:Tp},{name:"Prompt Manager",fn:kp},{name:"Valid Token",fn:Cp},{name:"Claude Code",fn:Ap}],t=true;for(let r of e){let n=await r.fn(),o="",i=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),i=C.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${p(n.message)}`;process.stdout.write(s+`
87
+ `));let e=[{name:"Credentials",fn:kp},{name:"Prompt Manager",fn:Cp},{name:"Valid Token",fn:$p},{name:"Claude Code",fn:Ap}],t=true;for(let r of e){let n=await r.fn(),o="",i=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),i=C.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${p(n.message)}`;process.stdout.write(s+`
86
88
  `);}return process.stdout.write(`
87
89
  `),t?(process.stdout.write(C.green(` \u2713 All checks passed!
88
90
 
89
91
  `)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
90
92
 
91
- `)),1)}var Rp=["github.com","www.github.com"],Mp=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,_p=/^([^@]+)@(.+)$/;function Op(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function To(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function Dp(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let i=t.slice(4).join("/");o.subpath=To(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=To(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function en(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Op(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&Rp.includes(r.hostname))return Dp(r);if(r.protocol==="https:"||r.protocol==="http:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}if(r.protocol==="git:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let r=t,n,o=t.indexOf("#");o!==-1&&(n=t.slice(o+1),r=t.slice(0,o));let i={type:"git",url:r};return n&&(i.ref=n),i}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let i=r.match(Mp);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(_p);u&&(c=u[1],l=u[2]),c.endsWith(".git")&&(c=c.slice(0,-4));let g={type:"github",url:`https://github.com/${s}/${c}.git`};if(n&&(g.ref=n),l&&(g.skillFilter=l),a){let v=a.replace(/^\//,"");v&&(g.subpath=To(v));}return g}}return {type:"git",url:t}}function tn(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}var jp=6e4,ze=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function rn(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:jp}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(i){await rm(r,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),c=s.includes("block timeout")||s.includes("timed out"),a=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw c?new ze("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new ze(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new ze(`Failed to clone ${e}: ${s}`,e,false,false)}}async function nn(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}function Ua(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var Co=new Set(["node_modules",".git","dist","build","__pycache__"]);function Tt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Ba(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Gp(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function ko(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function nr(e){try{let t=await readFile(e,"utf-8"),{data:r}=Ua(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function Ja(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([ko(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!Co.has(c.name)).map(c=>Ja(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function an(e,t){let r=[],n=new Set;if(t&&!Gp(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await ko(o)){let s=await nr(join(o,"SKILL.md"));if(s)return r.push(s),n.add(s.name),r}let i=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let s of i)try{let c=await readdir(s,{withFileTypes:!0});for(let a of c){if(!a.isDirectory())continue;let l=join(s,a.name);if(await ko(l)){let u=await nr(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await Ja(o);for(let c of s){let a=await nr(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function Ha(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(i=>i===o)})}var Ga=1;function Va(){return {version:Ga,skills:{}}}async function ln(e){let t=yn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Ga?Va():n}catch{return Va()}}function Yp(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function za(e,t){let r=yn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Yp(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
92
- `,"utf-8");}async function qa(e,t,r){let n=await ln(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await za(n,r);}async function Wa(e,t){let r=await ln(t);e in r.skills&&(delete r.skills[e],await za(r,t));}var Xa=S("skillInstaller");async function od(e,t,r,n){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:$().interfaceType});}catch(o){Xa.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function id(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:$().interfaceType});}catch(r){Xa.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function sd(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Co.has(basename(r))});}async function ad(e,t,r){let n=Tt(e.name),o=Mt(t),i=join(o,n);if(!Ba(o,i))return {skill:e.name,success:false,path:i,error:`Unsafe install path: "${i}" escapes skills directory`};try{await rm(i,{recursive:!0,force:!0}),await mkdir(i,{recursive:!0}),await sd(e.path,i);let c=tn(r)??r.url;return await qa(n,{source:c,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:i}}catch(s){return {skill:e.name,success:false,path:i,error:s instanceof Error?s.message:String(s)}}}async function Ya(e,t){let r=en(e),n;try{let o;if(r.type==="local"){if(!r.localPath||!existsSync(r.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=r.localPath;}else n=await rn(r.url,r.ref),o=n;let i=await an(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?Ha(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let g=Date.now(),v=await ad(u,t.scope,r);a.push(v);let d=Date.now()-g;v.success?await od(u.name,t.scope,l,d):await id(u.name,new Error(v.error??"Unknown error"));}return {source:e,results:a,discovered:i.length,installed:a.filter(u=>u.success).length,failed:a.filter(u=>!u.success).length}}finally{n&&await nn(n).catch(()=>{});}}var dd=S("skills");async function md(e){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:$().interfaceType});}catch(t){dd.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function fd(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${e} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function gd(e){let t=en(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${p(e)}...`),r=await rn(t.url,t.ref),n=r;let o=await an(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let s=tn(t)??p(e);I(`Found ${o.length} skill(s) in ${s}:
93
+ `)),1)}var _p=["github.com","www.github.com"],Mp=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Op=/^([^@]+)@(.+)$/;function Dp(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function $o(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function Np(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let i=t.slice(4).join("/");o.subpath=$o(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=$o(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function rn(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Dp(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&_p.includes(r.hostname))return Np(r);if(r.protocol==="https:"||r.protocol==="http:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}if(r.protocol==="git:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let r=t,n,o=t.indexOf("#");o!==-1&&(n=t.slice(o+1),r=t.slice(0,o));let i={type:"git",url:r};return n&&(i.ref=n),i}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let i=r.match(Mp);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(Op);u&&(c=u[1],l=u[2]),c.endsWith(".git")&&(c=c.slice(0,-4));let g={type:"github",url:`https://github.com/${s}/${c}.git`};if(n&&(g.ref=n),l&&(g.skillFilter=l),a){let v=a.replace(/^\//,"");v&&(g.subpath=$o(v));}return g}}return {type:"git",url:t}}function nn(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}var Bp=6e4,Xe=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function on(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Bp}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(i){await rm(r,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),c=s.includes("block timeout")||s.includes("timed out"),a=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw c?new Xe("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new Xe(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Xe(`Failed to clone ${e}: ${s}`,e,false,false)}}async function sn(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}function Ka(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var Lo=new Set(["node_modules",".git","dist","build","__pycache__"]);function $t(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Ja(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function zp(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Ao(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function sr(e){try{let t=await readFile(e,"utf-8"),{data:r}=Ka(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function Ha(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Ao(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!Lo.has(c.name)).map(c=>Ha(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function cn(e,t){let r=[],n=new Set;if(t&&!zp(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Ao(o)){let s=await sr(join(o,"SKILL.md"));if(s)return r.push(s),n.add(s.name),r}let i=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let s of i)try{let c=await readdir(s,{withFileTypes:!0});for(let a of c){if(!a.isDirectory())continue;let l=join(s,a.name);if(await Ao(l)){let u=await sr(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await Ha(o);for(let c of s){let a=await sr(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function Va(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(i=>i===o)})}var za=1;function Ga(){return {version:za,skills:{}}}async function un(e){let t=hn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<za?Ga():n}catch{return Ga()}}function Zp(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function qa(e,t){let r=hn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Zp(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
94
+ `,"utf-8");}async function Wa(e,t,r){let n=await un(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await qa(n,r);}async function Xa(e,t){let r=await un(t);e in r.skills&&(delete r.skills[e],await qa(r,t));}var Ya=S("skillInstaller");async function id(e,t,r,n){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:A().interfaceType});}catch(o){Ya.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function sd(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){Ya.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function ad(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Lo.has(basename(r))});}async function ld(e,t,r){let n=$t(e.name),o=Dt(t),i=join(o,n);if(!Ja(o,i))return {skill:e.name,success:false,path:i,error:`Unsafe install path: "${i}" escapes skills directory`};try{await rm(i,{recursive:!0,force:!0}),await mkdir(i,{recursive:!0}),await ad(e.path,i);let c=nn(r)??r.url;return await Wa(n,{source:c,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:i}}catch(s){return {skill:e.name,success:false,path:i,error:s instanceof Error?s.message:String(s)}}}async function Za(e,t){let r=rn(e),n;try{let o;if(r.type==="local"){if(!r.localPath||!existsSync(r.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=r.localPath;}else n=await on(r.url,r.ref),o=n;let i=await cn(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?Va(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let g=Date.now(),v=await ld(u,t.scope,r);a.push(v);let d=Date.now()-g;v.success?await id(u.name,t.scope,l,d):await sd(u.name,new Error(v.error??"Unknown error"));}return {source:e,results:a,discovered:i.length,installed:a.filter(u=>u.success).length,failed:a.filter(u=>!u.success).length}}finally{n&&await sn(n).catch(()=>{});}}var md=S("skills");async function fd(e){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:A().interfaceType});}catch(t){md.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function gd(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${e} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function yd(e){let t=rn(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${p(e)}...`),r=await on(t.url,t.ref),n=r;let o=await cn(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let s=nn(t)??p(e);I(`Found ${o.length} skill(s) in ${s}:
93
95
  `);for(let c of o){let a=p(c.name),l=p(c.description);process.stdout.write(` ${C.bold(a)} ${C.dim(l)}
94
96
  `);}return process.stdout.write(`
95
- `),0}catch(n){return n instanceof ze?k(n.message):k(n instanceof Error?n.message:String(n)),1}finally{r&&await nn(r).catch(()=>{});}}function yd(e){for(let r of e.results){let n=p(r.skill);if(r.success){let o=relative(process.cwd(),r.path);V(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else k(`${n}: ${p(r.error??"unknown error")}`);}process.stdout.write(`
96
- `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${p(t)}`),e.failed>0&&k(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Qa(e,t){if(t.list)return gd(e);let r=t.global?"global":"project";try{let n=await Ya(e,{scope:r,skillFilter:t.skill,yes:t.yes});return yd(n),n.failed>0?1:0}catch(n){return n instanceof ze?k(n.message):k(n instanceof Error?n.message:String(n)),1}}async function el(e){let t=Mt(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let i=join(t,o.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let c=await nr(s);c?r.push({name:c.name,description:c.description,path:i}):r.push({name:o.name,description:"(no metadata)",path:i});}}catch{}return r}async function tl(e){let t=e.global?"global":"project",r=await el(t),n=await ln(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[Tt(s.name)]?.source}));return wt(i),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
97
- `);for(let i of r){let s=n.skills[Tt(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?C.dim(` (${s})`):"";process.stdout.write(` ${C.bold(c)}${u}
97
+ `),0}catch(n){return n instanceof Xe?k(n.message):k(n instanceof Error?n.message:String(n)),1}finally{r&&await sn(r).catch(()=>{});}}function Sd(e){for(let r of e.results){let n=p(r.skill);if(r.success){let o=relative(process.cwd(),r.path);G(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else k(`${n}: ${p(r.error??"unknown error")}`);}process.stdout.write(`
98
+ `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${p(t)}`),e.failed>0&&k(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function el(e,t){if(t.list)return yd(e);let r=t.global?"global":"project";try{let n=await Za(e,{scope:r,skillFilter:t.skill,yes:t.yes});return Sd(n),n.failed>0?1:0}catch(n){return n instanceof Xe?k(n.message):k(n instanceof Error?n.message:String(n)),1}}async function tl(e){let t=Dt(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let i=join(t,o.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let c=await sr(s);c?r.push({name:c.name,description:c.description,path:i}):r.push({name:o.name,description:"(no metadata)",path:i});}}catch{}return r}async function rl(e){let t=e.global?"global":"project",r=await tl(t),n=await un(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[$t(s.name)]?.source}));return bt(i),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
99
+ `);for(let i of r){let s=n.skills[$t(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?C.dim(` (${s})`):"";process.stdout.write(` ${C.bold(c)}${u}
98
100
  `),process.stdout.write(` ${C.dim(l)}
99
101
 
100
- `);}return 0}async function rl(e,t){let r=t.global?"global":"project";if(!e){let s=await el(r);if(s.length===0)return I("No skills installed."),0;I("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
102
+ `);}return 0}async function nl(e,t){let r=t.global?"global":"project";if(!e){let s=await tl(r);if(s.length===0)return I("No skills installed."),0;I("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
101
103
  `);return process.stdout.write(`
102
- `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=Tt(e),o=Mt(r),i=join(o,n);try{await stat(i);}catch{return k(`Skill "${p(e)}" is not installed.`),1}if(!t.force&&!await fd(`Remove skill "${p(n)}"?`))return I("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await Wa(n,r),await md(n),V(`Skill "${p(n)}" removed.`),0}catch(s){return k(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function nl(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Ne}`,"-V, --version","Display the CLI version").addHelpText("after",`
104
+ `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=$t(e),o=Dt(r),i=join(o,n);try{await stat(i);}catch{return k(`Skill "${p(e)}" is not installed.`),1}if(!t.force&&!await gd(`Remove skill "${p(n)}"?`))return I("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await Xa(n,r),await fd(n),G(`Skill "${p(n)}" removed.`),0}catch(s){return k(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function ol(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Ke}`,"-V, --version","Display the CLI version").addHelpText("after",`
103
105
  Without arguments, opens the interactive interface (TUI).
104
106
  Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
105
107
  Examples:
106
- $ flow setup init`).action(async()=>{let a=await Po();process.exit(a);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
108
+ $ flow setup init`).action(async()=>{let a=await ko();process.exit(a);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
107
109
  Examples:
108
110
  $ flow plugin list
109
111
  $ flow plugin list --available
110
112
  $ flow plugin list --outdated
111
- $ flow plugin list --json`).action(async a=>{let l=await Ea(a);process.exit(l);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
113
+ $ flow plugin list --json`).action(async a=>{let l=await Ta(a);process.exit(l);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
112
114
  Examples:
113
115
  $ flow plugin install flow-adr-writer
114
116
  $ flow plugin install flow-adr-writer --scope project
@@ -116,11 +118,11 @@ Examples:
116
118
  $ flow plugin install flow-adr-writer --force
117
119
  $ flow plugin install flow-adr-writer --silent
118
120
  $ flow plugin install superpowers@claude-plugins-official
119
- $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(v=>v.trim());if(u.length===0){k("No valid plugin names provided"),process.exit(1);return}ne("cli",{verbose:l.verbose,silent:l.silent});let g=await Ta(u,l);process.exit(g);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
121
+ $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(v=>v.trim());if(u.length===0){k("No valid plugin names provided"),process.exit(1);return}oe("cli",{verbose:l.verbose,silent:l.silent});let g=await ka(u,l);process.exit(g);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
120
122
  Examples:
121
123
  $ flow plugin uninstall flow-adr-writer
122
124
  $ flow plugin uninstall flow-adr-writer --scope project
123
- $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await ka(a,l);process.exit(u);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
125
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await Ca(a,l);process.exit(u);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
124
126
  Examples:
125
127
  $ flow plugin update flow-adr-writer
126
128
  $ flow plugin update flow-adr-writer --scope project
@@ -129,49 +131,49 @@ Examples:
129
131
  $ flow plugin update flow-adr-writer --verbose
130
132
  $ flow plugin update flow-adr-writer --silent
131
133
  $ flow plugin update
132
- $ flow plugin update --dry-run`).action(async(a,l)=>{ne("cli",{verbose:l.verbose,silent:l.silent});let u=await La(a??null,l);process.exit(u);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
134
+ $ flow plugin update --dry-run`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Ra(a??null,l);process.exit(u);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
133
135
  Examples:
134
136
  $ flow plugin enable flow-adr-writer
135
- $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{ne("cli");let u=await Ca(a,l);process.exit(u);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
137
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{oe("cli");let u=await $a(a,l);process.exit(u);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
136
138
  Examples:
137
139
  $ flow plugin disable flow-adr-writer
138
- $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{ne("cli");let u=await Aa(a,l);process.exit(u);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
140
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{oe("cli");let u=await Aa(a,l);process.exit(u);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
139
141
  Examples:
140
142
  $ flow plugin marketplace add anthropics/claude-code
141
143
  $ flow plugin marketplace add https://github.com/owner/repo
142
144
  $ flow plugin marketplace add anthropics/claude-code --force
143
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{ne("cli",{verbose:l.verbose,silent:l.silent});let u=await Ma(a,l);process.exit(u);}),n.addCommand(o),t.addCommand(n);let i=new Command("mcp").description("Manage MCP servers from the Findr catalog");i.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
145
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Ma(a,l);process.exit(u);}),n.addCommand(o),t.addCommand(n);let i=new Command("mcp").description("Manage MCP servers from the Findr catalog");i.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
144
146
  Examples:
145
147
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
146
148
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
147
149
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
148
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{ne("cli",{verbose:u.verbose,silent:u.silent});let g=await js(a,l,u);process.exit(g);}),i.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
150
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{oe("cli",{verbose:u.verbose,silent:u.silent});let g=await Bs(a,l,u);process.exit(g);}),i.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
149
151
  Examples:
150
152
  $ flow mcp remove notion
151
153
  $ flow mcp remove notion --scope project
152
- $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{ne("cli",{verbose:l.verbose,silent:l.silent});let u=await Bs(a,l);process.exit(u);}),t.addCommand(i);let s=new Command("auth").description("Manage authentication credentials");s.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
154
+ $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Js(a,l);process.exit(u);}),t.addCommand(i);let s=new Command("auth").description("Manage authentication credentials");s.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
153
155
  Examples:
154
156
  $ flow auth login
155
157
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
156
158
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
157
- $ flow auth login --verbose`).action(async a=>{ne("cli",{verbose:a.verbose});let l=await Po(a);process.exit(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
159
+ $ flow auth login --verbose`).action(async a=>{oe("cli",{verbose:a.verbose});let l=await ko(a);process.exit(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
158
160
  Examples:
159
161
  $ flow auth logout
160
- $ flow auth logout --force`).action(async a=>{let l=await va(a.force);process.exit(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
162
+ $ flow auth logout --force`).action(async a=>{let l=await Pa(a.force);process.exit(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
161
163
  Examples:
162
- $ flow auth status`).action(async()=>{let a=await Pa();process.exit(a);}),t.addCommand(s);let c=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");return c.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
164
+ $ flow auth status`).action(async()=>{let a=await Ea();process.exit(a);}),t.addCommand(s);let c=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");return c.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
163
165
  Examples:
164
166
  $ flow skills add vercel-labs/agent-skills
165
167
  $ flow skills add owner/repo -g
166
168
  $ flow skills add owner/repo --skill pr-review commit
167
169
  $ flow skills add ./local/skills -y
168
- $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await Qa(a,l);process.exit(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
170
+ $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await el(a,l);process.exit(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
169
171
  Examples:
170
172
  $ flow skills list
171
173
  $ flow skills list -g
172
- $ flow skills list --json`).action(async a=>{let l=await tl(a);process.exit(l);}),c.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
174
+ $ flow skills list --json`).action(async a=>{let l=await rl(a);process.exit(l);}),c.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
173
175
  Examples:
174
176
  $ flow skills remove pr-review
175
- $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await rl(a,l);process.exit(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
177
+ $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await nl(a,l);process.exit(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
176
178
  Examples:
177
- $ flow health`).action(async()=>{let a=await _a();process.exit(a);}),t}var Sd=nl(async()=>{ne("tui"),si("tui"),ai(),process.on("SIGINT",()=>{Ot("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Ot("sigterm").finally(()=>process.exit(143));}),await ga(),render(jsx(ya,{}),{alternateScreen:true,exitOnCtrlC:false});});Sd.parse();
179
+ $ flow health`).action(async()=>{let a=await Oa();process.exit(a);}),t}var wd=ol(async()=>{oe("tui"),ai("tui"),li(),process.on("SIGINT",()=>{Ft("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Ft("sigterm").finally(()=>process.exit(143));}),await ya(),render(jsx(Sa,{}),{alternateScreen:true,exitOnCtrlC:false});});wd.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciandt-flow/cli",
3
- "version": "1.3.0-beta.152",
3
+ "version": "1.4.0-beta.162",
4
4
  "description": "TUI for browsing and installing Claude Code plugins from the Flow ecosystem",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -50,7 +50,7 @@
50
50
  "email": "flow@ciandt.com"
51
51
  },
52
52
  "dependencies": {
53
- "@tanstack/react-query": "5.100.6",
53
+ "@tanstack/react-query": "5.100.9",
54
54
  "boxen": "8.0.1",
55
55
  "chalk": "5.6.2",
56
56
  "commander": "11.1.0",
@@ -70,8 +70,8 @@
70
70
  "react-dom": "19.2.5",
71
71
  "semver": "7.7.4",
72
72
  "simple-git": "3.36.0",
73
- "yaml": "2.8.3",
74
- "yocto-spinner": "1.1.0",
73
+ "yaml": "2.8.4",
74
+ "yocto-spinner": "1.2.0",
75
75
  "zustand": "5.0.12"
76
76
  },
77
77
  "devDependencies": {