@ciandt-flow/cli 1.6.2 → 1.7.0-beta.213

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 +119 -117
  2. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import Kc,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import oc,{HTTPError}from'ky';import*as It from'crypto';import {randomUUID}from'crypto';import*as q from'fs';import q__default,{readFileSync,existsSync,realpathSync}from'fs';import*as B from'path';import B__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as Te from'os';import Te__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as yo from'readline';import {createInterface}from'readline';import Dn from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import E from'chalk';import Rc from'ink-big-text';import nu from'ink-spinner';import*as Ae from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp as cp$1}from'fs/promises';import du from'extract-zip';import mu from'proper-lockfile';import go from'semver';import {execa}from'execa';import Ko from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var zo="FLOW",D="flow-skills",bn="flow-cli",Ut="internal",gr="external",xt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},Wo={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Pn=new Set(["internal","external"]),Bt={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"}},z="flow-claude-md-setup",Be=5,nt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var qo=new Set(["skill","mcp","plugin"]),m=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(qo),origins:new Set(Pn)},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(qo)},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(Pn)},selectedIndex:0}))}));var yr="aes-256-gcm",Pl=16,Xo=16,Kt=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=It.randomBytes(Pl),n=It.createCipheriv(yr,this.key,r,{authTagLength:Xo}),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:yr}}decrypt(t){if(t.algorithm!==yr)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=It.createDecipheriv(yr,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Xo});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var vl=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,El=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Tl=/[A-Za-z0-9+/]{40,}={0,2}/g;function vn(e){return e.replace(vl,"Bearer ***").replace(El,"***").replace(Tl,"***")}var jt=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 Gt=".claude",Yo=".flow";function Zo(e,t){return B.join(Te.homedir(),Gt,"plugins","cache",D,e,t)}function En(e){return B.join(Te.homedir(),Gt,"plugins","marketplaces",D,"plugins","native",e)}function Sr(){return B.join(Te.homedir(),Gt,"plugins","marketplaces",D,".claude-plugin","marketplace.json")}function Qo(){return B.join(Te.homedir(),Gt,"plugins","known_marketplaces.json")}function ei(){return B.join(Te.homedir(),Gt,"plugins","marketplaces",D)}function ti(){return B.join(Te.homedir(),Yo,"cache","install.lock")}function ri(){return B.join(Te.homedir(),Yo,"logs","flowsetup.log")}function Ht(e){let t=e==="global"?Te.homedir():process.cwd();return B.join(t,".claude","skills")}function Tn(e){let t=e==="global"?Te.homedir():process.cwd();return B.join(t,".claude","skills-lock.json")}var Cl=5*1024*1024,kl=3,hr=class{filePath;constructor(){this.filePath=ri(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
- `;try{q.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=B.dirname(this.filePath);q.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(q.statSync(this.filePath).size>Cl){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);q.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=B.dirname(this.filePath),r=B.basename(this.filePath,".log"),n=q.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(kl))q.unlinkSync(B.join(t,o));}catch{}}};var wr=class{write(t){process.stdout.write(t.message+`
5
- `);}};var bt={debug:0,info:1,warn:2,error:3},it={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Al(){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 pe(e,t){if(e==="tui"){let r=Al();it={context:e,transports:[new jt("tui"),new hr],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?it={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?it={context:e,transports:[new jt("cli")],minLevel:"debug",debugModules:null}:it={context:e,transports:[new wr],minLevel:"info",debugModules:null};}function ni(){return it.transports}function oi(e,t){let{debugModules:r,minLevel:n}=it;return it.context==="tui"&&r&&r!=="all"?r.has(t)?bt[e]>=bt.debug:bt[e]>=bt.warn:bt[e]>=bt[n]}var ii=new Map;function xr(e,t,r){if(!oi(e,t))return;let n={level:e,module:t,message:vn(r),timestamp:new Date};for(let o of ni())o.write(n);}function S(e){let t=ii.get(e);if(t)return t;let r={debug:n=>xr("debug",e,n),info:n=>xr("info",e,n),warn:n=>xr("warn",e,n),error:n=>xr("error",e,n)};return ii.set(e,r),r}var Cn=S("encryption"),kn="__encrypted__";function $l(e){return typeof e=="object"&&e!==null&&kn in e&&e[kn]===true}function An(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[kn]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Cn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if($l(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Cn.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Cn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var $n=promisify(execFile),Ml=promisify(exec),Se=S("encryption:macos-keyvault"),Pt=class{static async isAvailable(){try{let{stdout:t}=await Ml("command -v security");return Se.debug(`security binary found at: ${t.trim()}`),!0}catch{return Se.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{Se.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await $n("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return Se.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return Se.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{Se.debug(`Storing secret: service=${t}, account=${r}`),await $n("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),Se.debug("security add-generic-password succeeded");}catch(o){let i=o;throw Se.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),o}}async deleteSecret(t,r){try{return Se.debug(`Deleting secret: service=${t}, account=${r}`),await $n("security",["delete-generic-password","-a",r,"-s",t]),Se.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return Se.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};var Ln=promisify(execFile),Rn=promisify(exec),Nl=[{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 Fl(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 Ul(e){let t=yo.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var Ke=class e{static async isAvailable(){try{let{stdout:t}=await Rn("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 Ln("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 Nl)try{return await Rn(`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 Ul(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return R.info(`Running: ${t.command}`),await Fl("Installing secret-tool...",()=>Rn(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 Ln("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 Ln("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 jl=promisify(execFile),he=S("encryption:windows-keyvault"),Mn=1,Gl=1,Hl=2,Jl=3;function _n(e,t){return `${e}:${t}`}var On=`
2
+ import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import fu,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import Cc,{HTTPError}from'ky';import*as At from'crypto';import {randomUUID}from'crypto';import*as re from'fs';import re__default,{readFileSync,existsSync,realpathSync}from'fs';import*as G from'path';import G__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as Le from'os';import Le__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as $o from'readline';import {createInterface}from'readline';import Wn from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Wc from'jsonwebtoken';import b from'chalk';import iu from'ink-big-text';import Ru from'ink-spinner';import*as _e from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp}from'fs/promises';import ju from'extract-zip';import Ku from'proper-lockfile';import Ao from'semver';import {execa}from'execa';import ni from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var wr="FLOW",B="flow-skills",Rn="flow-cli",Ht="internal",xr="external",kt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},ci={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Mn=new Set(["internal","external"]),Gt={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"}},ee="flow-claude-md-setup",He=5,lt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var ui=new Set(["skill","mcp","plugin"]),g=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,debugPanelOpen:false,catalogFilters:{types:new Set(ui),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(ui)},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})),setDebugPanelOpen:t=>e({debugPanelOpen:t})}));var br="aes-256-gcm",Vl=16,di=16,Vt=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=At.randomBytes(Vl),n=At.createCipheriv(br,this.key,r,{authTagLength:di}),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:br}}decrypt(t){if(t.algorithm!==br)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=At.createDecipheriv(br,this.key,Buffer.from(t.iv,"hex"),{authTagLength:di});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var zl=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Wl=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,ql=/[A-Za-z0-9+/]{40,}={0,2}/g;function _n(e){return e.replace(zl,"Bearer ***").replace(Wl,"***").replace(ql,"***")}var zt=".claude",pi=".flow";function mi(e,t){return G.join(Le.homedir(),zt,"plugins","cache",B,e,t)}function On(e){return G.join(Le.homedir(),zt,"plugins","marketplaces",B,"plugins","native",e)}function Ir(){return G.join(Le.homedir(),zt,"plugins","marketplaces",B,".claude-plugin","marketplace.json")}function fi(){return G.join(Le.homedir(),zt,"plugins","known_marketplaces.json")}function gi(){return G.join(Le.homedir(),zt,"plugins","marketplaces",B)}function yi(){return G.join(Le.homedir(),pi,"cache","install.lock")}function Si(){return G.join(Le.homedir(),pi,"logs","flowsetup.log")}function Wt(e){let t=e==="global"?Le.homedir():process.cwd();return G.join(t,".claude","skills")}function Dn(e){let t=e==="global"?Le.homedir():process.cwd();return G.join(t,".claude","skills-lock.json")}var Xl=5*1024*1024,Yl=3,vr=class{filePath;constructor(){this.filePath=Si(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{re.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=G.dirname(this.filePath);re.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(re.statSync(this.filePath).size>Xl){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);re.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=G.dirname(this.filePath),r=G.basename(this.filePath,".log"),n=re.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Yl))re.unlinkSync(G.join(t,o));}catch{}}};var Pr=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
+ `);}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 Er=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var Tr=[],Nn=new Set;function Fn(){return Tr}function hi(e){return Nn.add(e),()=>{Nn.delete(e);}}var Cr=class{write(t){Tr.push(t),Tr.length>100&&Tr.shift();for(let r of Nn)r();}};var $t={debug:0,info:1,warn:2,error:3},ut={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Zl(){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 ye(e,t){if(e==="tui"){let r=Zl();ut={context:e,transports:[new Cr,new vr],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?ut={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?ut={context:e,transports:[new Pr("cli")],minLevel:"debug",debugModules:null}:ut={context:e,transports:[new Er],minLevel:"info",debugModules:null};}function wi(){return ut.transports}function xi(e,t){let{debugModules:r,minLevel:n}=ut;return ut.context==="tui"&&r&&r!=="all"?r.has(t)?$t[e]>=$t.debug:$t[e]>=$t.warn:$t[e]>=$t[n]}var bi=new Map;function kr(e,t,r){if(!xi(e,t))return;let n={level:e,module:t,message:_n(r),timestamp:new Date};for(let o of wi())o.write(n);}function S(e){let t=bi.get(e);if(t)return t;let r={debug:n=>kr("debug",e,n),info:n=>kr("info",e,n),warn:n=>kr("warn",e,n),error:n=>kr("error",e,n)};return bi.set(e,r),r}var Un=S("encryption"),Bn="__encrypted__";function Ql(e){return typeof e=="object"&&e!==null&&Bn in e&&e[Bn]===true}function jn(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Bn]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Un.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Ql(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Un.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Un.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Kn=promisify(execFile),rc=promisify(exec),ve=S("encryption:macos-keyvault"),Lt=class{static async isAvailable(){try{let{stdout:t}=await rc("command -v security");return ve.debug(`security binary found at: ${t.trim()}`),!0}catch{return ve.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{ve.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Kn("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return ve.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ve.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{ve.debug(`Storing secret: service=${t}, account=${r}`),await Kn("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),ve.debug("security add-generic-password succeeded");}catch(o){let i=o;throw ve.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),o}}async deleteSecret(t,r){try{return ve.debug(`Deleting secret: service=${t}, account=${r}`),await Kn("security",["delete-generic-password","-a",r,"-s",t]),ve.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return ve.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};var Jn=promisify(execFile),Hn=promisify(exec),sc=[{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"}],D=S("encryption:linux-keyvault");async function ac(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 lc(e){let t=$o.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var Ge=class e{static async isAvailable(){try{let{stdout:t}=await Hn("command -v secret-tool");D.debug(`secret-tool found at: ${t.trim()}`);}catch{return D.debug("secret-tool binary not found in PATH"),false}try{return await Jn("secret-tool",["lookup","service","__flow_connectivity_check__"]),D.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(D.debug(`Secret Service D-Bus not available: ${n}`),false):(D.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of sc)try{return await Hn(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;D.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 D.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await lc(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return D.info(`Running: ${t.command}`),await ac("Installing secret-tool...",()=>Hn(t.command)),e.isAvailable()}catch{return D.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{D.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Jn("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return D.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return D.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){D.debug(`Storing secret: service=${t}, account=${r}`),D.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),D.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),D.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?(D.debug("secret-tool store succeeded"),o()):(D.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=>{D.error(`secret-tool store spawn error: ${a.message}`),i(a);});});}async deleteSecret(t,r){try{return D.debug(`Deleting secret: service=${t}, account=${r}`),await Jn("secret-tool",["clear","service",t,"account",r]),D.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return D.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var dc=promisify(execFile),Pe=S("encryption:windows-keyvault"),Gn=1,pc=1,mc=2,fc=3;function Vn(e,t){return `${e}:${t}`}var zn=`
6
6
  using System;
7
7
  using System.Runtime.InteropServices;
8
8
  using System.Text;
@@ -38,7 +38,7 @@ public class FlowCredManager {
38
38
 
39
39
  public static string Read(string target) {
40
40
  IntPtr credPtr;
41
- if (!CredRead(target, ${Mn}, 0, out credPtr)) return "";
41
+ if (!CredRead(target, ${Gn}, 0, out credPtr)) return "";
42
42
  try {
43
43
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
44
44
  if (cred.CredentialBlobSize <= 0) return "";
@@ -52,7 +52,7 @@ public class FlowCredManager {
52
52
  byte[] bytes = Encoding.UTF8.GetBytes(secret);
53
53
  IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
54
54
  IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
55
- int[] persistLevels = new int[] { ${Hl}, ${Jl}, ${Gl} };
55
+ int[] persistLevels = new int[] { ${mc}, ${fc}, ${pc} };
56
56
  int lastErr = 0;
57
57
  try {
58
58
  foreach (int persist in persistLevels) {
@@ -60,7 +60,7 @@ public class FlowCredManager {
60
60
  try {
61
61
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
62
62
  var cred = new CREDENTIAL();
63
- cred.Type = ${Mn};
63
+ cred.Type = ${Gn};
64
64
  cred.TargetName = targetPtr;
65
65
  cred.CredentialBlobSize = bytes.Length;
66
66
  cred.CredentialBlob = blobPtr;
@@ -78,143 +78,145 @@ public class FlowCredManager {
78
78
  }
79
79
 
80
80
  public static bool Delete(string target) {
81
- return CredDelete(target, ${Mn}, 0);
81
+ return CredDelete(target, ${Gn}, 0);
82
82
  }
83
83
  }
84
- `;function Jt(e){return e.replace(/'/g,"''")}function Ir(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Vl(e){return `Add-Type -TypeDefinition @'
85
- ${On}
84
+ `;function qt(e){return e.replace(/'/g,"''")}function Ar(e){return ["-NoProfile","-NonInteractive","-Command",e]}function gc(e){return `Add-Type -TypeDefinition @'
85
+ ${zn}
86
86
  '@
87
- [FlowCredManager]::Read('${Jt(e)}')`}function zl(e,t,r){return `Add-Type -TypeDefinition @'
88
- ${On}
87
+ [FlowCredManager]::Read('${qt(e)}')`}function yc(e,t,r){return `Add-Type -TypeDefinition @'
88
+ ${zn}
89
89
  '@
90
- [FlowCredManager]::Write('${Jt(e)}', '${Jt(t)}', '${Jt(r)}')`}function Wl(e){return `Add-Type -TypeDefinition @'
91
- ${On}
90
+ [FlowCredManager]::Write('${qt(e)}', '${qt(t)}', '${qt(r)}')`}function Sc(e){return `Add-Type -TypeDefinition @'
91
+ ${zn}
92
92
  '@
93
- [FlowCredManager]::Delete('${Jt(e)}')`}async function br(e){return jl("powershell.exe",e)}var vt=class{static async isAvailable(){try{let{stdout:t}=await br(Ir('Write-Output "ok"')),r=t.trim()==="ok";return he.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
94
- `)[0]:"unknown error";return he.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=_n(t,r);he.debug(`Looking up secret: target=${n}`);let o=Vl(n),{stdout:i}=await br(Ir(o)),s=i.trim();return he.debug(`CredRead result: ${s?"found":"empty"}`),s||null}catch(n){let o=n instanceof Error?n.message.split(`
95
- `)[0]:"unknown error";return he.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=_n(t,r);he.debug(`Storing secret: target=${o}`);let i=zl(o,n,r),{stdout:s}=await br(Ir(i)),c=s.trim();if(c.startsWith("OK:")){let l=c.split(":")[1];he.debug(`CredWrite succeeded (persist=${l})`);return}let a=c.startsWith("ERR:")?c.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${a}`)}catch(o){let i=o instanceof Error?o.message.split(`
96
- `)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${i}`;throw he.error(s),new Error(s)}}async deleteSecret(t,r){try{let n=_n(t,r);he.debug(`Deleting secret: target=${n}`);let o=Wl(n),{stdout:i}=await br(Ir(o)),s=i.trim()==="True";return he.debug(`CredDelete result: ${s}`),s}catch(n){let o=n instanceof Error?n.message.split(`
97
- `)[0]:"unknown error";return he.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var ql=32,Xl="flow-plugins-cli-fallback",Nn="flow-plugins-cli-fallback",Yl={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 Zl(){let e=`${Te.hostname()}${Te.userInfo().username}`;return It.scryptSync(e,Xl,ql)}function Ql(){let e=Zl(),t=new Kt(e),r=An(t);return new Dn({projectName:Nn,serialize:r.serialize,deserialize:r.deserialize})}var vr=null;function Pr(){return vr||(vr=Ql()),vr}var ee=class{warned=false;async getSecret(t,r){return Pr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Yl[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
93
+ [FlowCredManager]::Delete('${qt(e)}')`}async function $r(e){return dc("powershell.exe",e)}var Rt=class{static async isAvailable(){try{let{stdout:t}=await $r(Ar('Write-Output "ok"')),r=t.trim()==="ok";return Pe.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
94
+ `)[0]:"unknown error";return Pe.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Vn(t,r);Pe.debug(`Looking up secret: target=${n}`);let o=gc(n),{stdout:i}=await $r(Ar(o)),s=i.trim();return Pe.debug(`CredRead result: ${s?"found":"empty"}`),s||null}catch(n){let o=n instanceof Error?n.message.split(`
95
+ `)[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{let o=Vn(t,r);Pe.debug(`Storing secret: target=${o}`);let i=yc(o,n,r),{stdout:s}=await $r(Ar(i)),c=s.trim();if(c.startsWith("OK:")){let l=c.split(":")[1];Pe.debug(`CredWrite succeeded (persist=${l})`);return}let a=c.startsWith("ERR:")?c.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${a}`)}catch(o){let i=o instanceof Error?o.message.split(`
96
+ `)[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{let n=Vn(t,r);Pe.debug(`Deleting secret: target=${n}`);let o=Sc(n),{stdout:i}=await $r(Ar(o)),s=i.trim()==="True";return Pe.debug(`CredDelete result: ${s}`),s}catch(n){let o=n instanceof Error?n.message.split(`
97
+ `)[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 (PowerShell)"}};var hc=32,wc="flow-plugins-cli-fallback",qn="flow-plugins-cli-fallback",xc={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 bc(){let e=`${Le.hostname()}${Le.userInfo().username}`;return At.scryptSync(e,wc,hc)}function Ic(){let e=bc(),t=new Vt(e),r=jn(t);return new Wn({projectName:qn,serialize:r.serialize,deserialize:r.deserialize})}var Rr=null;function Lr(){return Rr||(Rr=Ic()),Rr}var se=class{warned=false;async getSecret(t,r){return Lr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=xc[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
98
98
  using a machine-derived key. For stronger security, ${o}.
99
- `),this.warned=true;}Pr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Pr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Pr().path}static hasExistingData(){try{let t=new Dn({projectName:Nn});return q.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Dn({projectName:Nn});q.rmSync(t.path,{force:!0});}catch{}vr=null;}};async function Fn(){if(ee.hasExistingData())return new ee;switch(process.platform){case "darwin":return await Pt.isAvailable()?new Pt:new ee;case "linux":return await Ke.isAvailable()?new Ke:await Ke.ensureInstalled()?new Ke:new ee;case "win32":return await vt.isAvailable()?new vt:new ee;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var ec=S("config:credentials"),_e="flow-plugins-cli",Un="credentials",Bn="token-cache",Kn="user-info",Cr=null;async function je(){return Cr||(Cr=Fn()),Cr}function kr(){Cr=null;}async function N(){let t=await(await je()).getSecret(_e,Un);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function st(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 ec.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await je()).setSecret(_e,Un,JSON.stringify(e));}async function ui(){let e=await je();await e.deleteSecret(_e,Un),await e.deleteSecret(_e,Bn),await e.deleteSecret(_e,Kn);}async function pi(){return (await je()).getStoragePath()}async function di(e){await(await je()).setSecret(_e,Bn,JSON.stringify(e));}async function Ar(){let t=await(await je()).getSecret(_e,Bn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function $r(e){await(await je()).setSecret(_e,Kn,JSON.stringify(e));}async function mi(){let t=await(await je()).getSecret(_e,Kn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Et(){let e=await Ar();return e?new Date(e.expiresAt)>new Date:false}function Lr(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 fi=[/^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 tc(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 rc(e){if(fi.some(r=>r.test(e)))return true;let t=tc(e);return !!(t&&fi.some(r=>r.test(t)))}function nc(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Tt(e,t){let r=nc(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&&rc(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var jn=S("api:auth");function sc(e){if(!nt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var gi={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 ac(e){if(e instanceof HTTPError){let t=e.response.status;jn.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&&gi[r]?new Error(gi[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?(jn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(jn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function at(e){let t=Tt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");sc(e.tenant);let r;try{r=await oc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await ac(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await st(e),await di({accessToken:r.access_token,expiresAt:n});let o=Lr(r.access_token);await $r({sub:o.sub,name:o.name,email:o.email});}var yi=S("lib:tokenProvider");async function Ge(){if(await Et()){let n=await Ar();if(n)return n.accessToken}yi.debug("Token expired or missing, re-authenticating...");let t=await N();if(!t)throw new Error("Not authenticated. Run: flow auth login");ee.clearFallbackFile(),kr(),await at(t);let r=await Ar();if(!r)throw new Error("Authentication succeeded but token was not persisted");return yi.debug("Token refreshed successfully"),r.accessToken}var Rr=S("api:metrics");function Si(){return Tt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function hi(e,t,r){return oc.post(e,{json:t,headers:r})}async function cc(e){let t=await mi();if(t)return t;let r=Lr(e),n={sub:r.sub,name:r.name,email:r.email};return await $r(n),n}async function I(e,t){let r=await Ge(),n=await cc(r),o=await N();if(!nt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:bn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await hi(Si(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Rr.debug(`Metrics event sent: ${e}`);}catch(s){throw Rr.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function wi(e,t,r){try{let n=r&&nt.test(r)?r:"unknown",o={action:e,booster:bn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await hi(Si(),o,{FlowTenant:n}),Rr.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Rr.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_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",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 uc={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},we={...uc};function xi(e){let t=Date.now();we={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function lt(e){we.currentStep=e,we.stepStart=Date.now();}function $(){return {...we}}function He(){return we.sessionStart===0?0:Date.now()-we.sessionStart}function ct(){return we.stepStart===0?0:Date.now()-we.stepStart}function Ii(){we.tuiSessionStart=Date.now();}function bi(){return we.tuiSessionStart===0?0:Date.now()-we.tuiSessionStart}var pc=3e3,dc=S("abandonment");async function Mr(e){let{currentStep:t,sessionStart:r}=$();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:He()};try{await Promise.race([I(x.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),pc))]);}catch(o){dc.warn(`Abandonment event failed: ${String(o)}`);}}function Pi(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var mc=3e3,fc=S("session-end");async function zt(e){let{activeTab:t,screen:r}=m.getState(),n=bi(),i=[I(x.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(Mr(e));try{await Pi(Promise.all(i).then(()=>{}),mc);}catch(s){fc.warn(`Session end event failed: ${String(s)}`);}}var hc=2e3;function Ei(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=m(s=>s.pendingExit),o=m(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),zt("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},hc);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var bc=16;function Ti({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(bc)}),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 xe=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 Tc=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Je=Tc.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 W(e){process.stdout.write(E.green(` \u2713 ${p(e)}
100
- `));}function k(e){process.stderr.write(E.red(` \u2717 ${p(e)}
101
- `));}function P(e){process.stdout.write(E.cyan(` \u2139 ${p(e)}
102
- `));}function _r(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(`
103
- `),process.stdout.write(` ${E.bold(s(e))}
104
- `),process.stdout.write(` ${E.dim(i)}
99
+ `),this.warned=true;}Lr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Lr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Lr().path}static hasExistingData(){try{let t=new Wn({projectName:qn});return re.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Wn({projectName:qn});re.rmSync(t.path,{force:!0});}catch{}Rr=null;}};async function Xn(){if(se.hasExistingData())return new se;switch(process.platform){case "darwin":return await Lt.isAvailable()?new Lt:new se;case "linux":return await Ge.isAvailable()?new Ge:await Ge.ensureInstalled()?new Ge:new se;case "win32":return await Rt.isAvailable()?new Rt:new se;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var vc=S("config:credentials"),Fe="flow-plugins-cli",Yn="credentials",Zn="token-cache",Qn="user-info",Or=null;async function Ve(){return Or||(Or=Xn()),Or}function Dr(){Or=null;}async function j(){let t=await(await Ve()).getSecret(Fe,Yn);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 vc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ve()).setSecret(Fe,Yn,JSON.stringify(e));}async function Ti(){let e=await Ve();await e.deleteSecret(Fe,Yn),await e.deleteSecret(Fe,Zn),await e.deleteSecret(Fe,Qn);}async function Ci(){return (await Ve()).getStoragePath()}async function ki(e){await(await Ve()).setSecret(Fe,Zn,JSON.stringify(e));}async function Nr(){let t=await(await Ve()).getSecret(Fe,Zn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Fr(e){await(await Ve()).setSecret(Fe,Qn,JSON.stringify(e));}async function Ai(){let t=await(await Ve()).getSecret(Fe,Qn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function We(){let e=await Nr();return e?new Date(e.expiresAt)>new Date:false}function Ur(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 $i=[/^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 Pc(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 Ec(e){if($i.some(r=>r.test(e)))return true;let t=Pc(e);return !!(t&&$i.some(r=>r.test(t)))}function Tc(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Mt(e,t){let r=Tc(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&&Ec(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var eo=S("api:auth");function Ac(e){if(!lt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Li={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 $c(e){if(e instanceof HTTPError){let t=e.response.status;eo.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&&Li[r]?new Error(Li[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?(eo.debug(`Non-HTTP error during authentication: ${e.message}`),e):(eo.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function dt(e){let t=Mt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ac(e.tenant);let r;try{r=await Cc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await $c(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await ze(e),await ki({accessToken:r.access_token,expiresAt:n});let o=Ur(r.access_token);await Fr({sub:o.sub,name:o.name,email:o.email});}var Ri=S("lib:tokenProvider");async function qe(){if(await We()){let n=await Nr();if(n)return n.accessToken}Ri.debug("Token expired or missing, re-authenticating...");let t=await j();if(!t)throw new Error("Not authenticated. Run: flow auth login");se.clearFallbackFile(),Dr(),await dt(t);let r=await Nr();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Ri.debug("Token refreshed successfully"),r.accessToken}var Br=S("api:metrics");function Mi(){return Mt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function _i(e,t,r){return Cc.post(e,{json:t,headers:r})}async function Rc(e){let t=await Ai();if(t)return t;let r=Ur(e),n={sub:r.sub,name:r.name,email:r.email};return await Fr(n),n}async function x(e,t){let r=await qe(),n=await Rc(r),o=await j();if(!lt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:Rn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await _i(Mi(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Br.debug(`Metrics event sent: ${e}`);}catch(s){throw Br.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function Oi(e,t,r){try{let n=r&&lt.test(r)?r:"unknown",o={action:e,booster:Rn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await _i(Mi(),o,{FlowTenant:n}),Br.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Br.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var w={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_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",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 Mc={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},Ee={...Mc};function Di(e){let t=Date.now();Ee={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function pt(e){Ee.currentStep=e,Ee.stepStart=Date.now();}function _(){return {...Ee}}function Xe(){return Ee.sessionStart===0?0:Date.now()-Ee.sessionStart}function mt(){return Ee.stepStart===0?0:Date.now()-Ee.stepStart}function Ni(){Ee.tuiSessionStart=Date.now();}function Fi(){return Ee.tuiSessionStart===0?0:Date.now()-Ee.tuiSessionStart}var _c=3e3,Oc=S("abandonment");async function jr(e){let{currentStep:t,sessionStart:r}=_();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Xe()};try{await Promise.race([x(w.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),_c))]);}catch(o){Oc.warn(`Abandonment event failed: ${String(o)}`);}}function Ui(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Dc=3e3,Nc=S("session-end");async function Yt(e){let{activeTab:t,screen:r}=g.getState(),n=Fi(),i=[x(w.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(jr(e));try{await Ui(Promise.all(i).then(()=>{}),Dc);}catch(s){Nc.warn(`Session end event failed: ${String(s)}`);}}var jc=2e3;function ji(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=g(s=>s.pendingExit),o=g(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Yt("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},jc);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var Gc=16;function Ki({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(Gc)}),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 Se=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})}));function ft(){return G__default.join(Le__default.homedir(),".claude","settings.json")}function no(){let e=ft();if(!re__default.existsSync(e))return {status:"missing"};let t=re__default.readFileSync(e,"utf-8");try{let r=JSON.parse(t);return r===null||typeof r!="object"||Array.isArray(r)?{status:"malformed",raw:t}:{status:"ok",settings:r}}catch{return {status:"malformed",raw:t}}}function Hi(e){let t=ft();re__default.mkdirSync(G__default.dirname(t),{recursive:true});let r=`${t}.tmp`;re__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),re__default.renameSync(r,t);}function Gi(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function oo(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var qc=3600,gt=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Xc(e){return Wc.sign({sub:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:qc})}function Kr(e,t={}){let r=no();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new gt;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?oo(r.settings):null,i=Xc(e),s=Gi(n,i);return {jwt:i,merged:s,previousToken:o,hadExistingFile:r.status!=="missing"}}function Jr(e){Hi(e.merged);}function Vi(){let e=no();return e.status!=="ok"?false:oo(e.settings)!==null}var Qc=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Ye=Qc.version;function d(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 te(e){process.stdout.write(b.green(` \u2713 ${d(e)}
100
+ `));}function T(e){process.stderr.write(b.red(` \u2717 ${d(e)}
101
+ `));}function v(e){process.stdout.write(b.cyan(` \u2139 ${d(e)}
102
+ `));}function Hr(e,t){let r=t.map(c=>c.map(d)),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(`
103
+ `),process.stdout.write(` ${b.bold(s(e))}
104
+ `),process.stdout.write(` ${b.dim(i)}
105
105
  `);for(let c of r)process.stdout.write(` ${s(c)}
106
106
  `);process.stdout.write(`
107
- `);}function Ct(e){process.stdout.write(JSON.stringify(e,null,2)+`
108
- `);}function te(e){process.stdout.write(JSON.stringify(e)+`
109
- `);}function de(e){process.stderr.write(JSON.stringify(e)+`
110
- `);}function F(e){return e instanceof Error?e.message:String(e)}function Or(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function Ac(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 ke=["clientId","clientSecret","tenant"],$c={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function Ci(){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:h}=xe(),{setFocus:d}=m();useInput((w,C)=>{if(!a){if(C.shift&&C.tab){let y=ke.indexOf(r);y>0&&n(ke[y-1]);}else if(C.tab){let y=ke.indexOf(r);y<ke.length-1&&n(ke[y+1]);}else if(C.return)if(r==="tenant")T();else {let y=ke.indexOf(r);n(ke[y+1]);}}},{isActive:true});let T=async()=>{let w={};for(let C of ke)e[C].trim()||(w[C]="This field is required");if(Object.keys(w).length>0){i(w);let C=ke.find(y=>w[y]);C&&n(C);return}l(true),c(null),u.current+=1;try{await at({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:C,...y}=e;g(y),h(!0),m.getState().setScreen("bundleSetup"),d("bundleList"),I(x.CLI_SESSION_STARTED,{cli_version:Je,os:process.platform,node_version:process.version,duration_ms:He(),interface:"tui"}).catch(()=>{});}catch(C){let y=C instanceof Error?C.message:"Authentication failed";c(y),wi(x.CLI_AUTH_FAILED,{error_code:Ac(C),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(C=>({...C,clientSecret:""}));}},f=w=>C=>{t(y=>({...y,[w]:C})),o[w]&&i(y=>({...y,[w]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[zo," \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:ke.map(w=>jsx(Box,{marginBottom:1,children:jsx(Ti,{label:$c[w],value:e[w],onChange:f(w),masked:w==="clientSecret",isActive:r===w&&!a,error:o[w]})},w))}),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 At(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Rc,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Je]})})]})}var Jn={discover:"Discover",installed:"Installed"},Mc=Object.keys(Jn);function Mi(){let e=m(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Mc.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${Jn[t]} `}):jsx(Text,{dimColor:true,children:` ${Jn[t]} `})},t))})}var re=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Oi(){let e=m(s=>s.focus),t=re(s=>s.query),r=re(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 Nc=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...xt[e]})),Fc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Wo[e]}));function Di(){let e=m(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"]})]}),Nc.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"]})]}),Fc.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 Ni({type:e}){let{label:t,color:r}=xt[e];return jsx(Text,{color:r,children:t})}function Bi({origin:e}){return e===Ut?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Fr=Kc.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(Ni,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Bi,{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 ",Or(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function $t({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Gi({items:e,emptyMessage:t}){let r=m(a=>a.selectedIndex);if(e.length===0)return jsx($t,{message:t});let n=Math.max(0,r-Math.floor(Be/2)),o=Math.min(e.length,n+Be);o===e.length&&(n=Math.max(0,o-Be));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(Fr,{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 Vi({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 Wi({groups:e,emptyMessage:t}){let r=m(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 T of d.items)n.push({kind:"item",item:T,itemIndex:o,key:`i-${d.scope}-${T.name}`}),o++;}if(o===0)return jsx($t,{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(Be/2)),l=Math.min(n.length,a+Be);l===n.length&&(a=Math.max(0,l-Be));let u=n.slice(a,l),g=a,h=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(Vi,{label:d.label,pathHint:d.pathHint},d.key):jsx(Fr,{item:d.item,isSelected:d.itemIndex===r},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})})]})}var Wc={discover:"Discover",installed:"Installed"};function Xi({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(Oi,{}),jsx(Di,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Wc[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(Wi,{groups:n,emptyMessage:r}):jsx(Gi,{items:e,emptyMessage:r})]})}function Yi({filteredItems:e,emptyMessage:t,groups:r}){let n=m(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Xi,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Xi,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Yc={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 Ur(){let e=m(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:Yc[e]})})}function Qi({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 Br({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nu,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Kr({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 gt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=m(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 eo=Object.entries(Bt),ss=[...eo.map(([,e])=>e.actionLabel),"Cancel"],as=Object.fromEntries(eo.map(([,e])=>[e.actionLabel,e.description]));function ls(e){let t=eo.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function us({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=ls(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(gt,{itemName:`${e} \u2014 Choose scope`,actions:ss,descriptions:as,onAction:i,onClose:s}):jsx(gt,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Gr({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=m(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 ms({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Gr({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",h=o&&p(o),d=h?`Update to v${h}`:"Update";return jsx(gt,{itemName:e,actions:n?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:w=>{w==="Uninstall"?u():w===g?s(t):w.startsWith("Update")?c?.():a();},onClose:a})}function ys({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Gr({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(gt,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function Ss(e,t){let r=B.resolve(t);await Ae.mkdir(r,{recursive:true});let n=B.join(B.dirname(r),`${randomUUID()}.zip`);try{await Ae.writeFile(n,e),await du(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=B.resolve(r,o.fileName);if(!s.startsWith(r+B.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(B.resolve(B.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 Ae.unlink(n);}catch{}}}async function ro(e){await Ae.rm(e,{recursive:true,force:true});}async function We(){let e=ti();await Ae.mkdir(B.dirname(e),{recursive:true});try{await Ae.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await mu.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var gu={user:"global",project:"project",local:"local"};function Vr(e){return e?gu[e]:"global"}var ne=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},qe=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 rr(){return oc.create({prefix:Tt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Ge();e.headers.set("Authorization",`Bearer ${t}`);let r=await N();r?.tenant&&nt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Su=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function hs(e){if(!e||!Su.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function $e(){try{let{plugins:e}=await rr().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 Rt(e){hs(e);try{return await rr().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 ws(e){hs(e);try{let t=await rr().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 zr(){try{let{profiles:e}=await rr().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 hu=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,wu=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Wr(e){if(!hu.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function xu(e){if(!wu.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 Xe=S("installer");function Iu(e,t){let r=`${e}@${D}`,o=De().plugins[r];if(o&&!t)throw new ne(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function bu(e,t,r){r&&await ro(t);try{Xe.debug(`[${t}] Extracting archive...`),await Ss(e,t);}catch(n){throw await ro(t),n}}function Pu(e,t,r,n,o){let i=De(),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],yt(i),no(e,true,n);}async function vu(e,t,r,n,o){try{await I(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:$().interfaceType});}catch(i){Xe.warn(`Failed to send install metrics: ${String(i)}`);}}async function Eu(e,t,r){try{await I(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){Xe.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function oe(e,t={}){let r=Date.now(),n=null;try{Xe.debug(`[${e}] Acquiring lock...`),n=await We();let{pluginKey:o,alreadyInstalled:i}=Iu(e,t.force);Xe.debug(`[${e}] Fetching manifest...`);let s=await Rt(e);Wr(s.name),xu(s.version),Xe.debug(`[${e}] Downloading archive...`);let c=await ws(e),a=t.scope??"user",l=Zo(s.name,s.version);await bu(c,l,!!i&&!!t.force),Pu(o,l,s.version,a,"internal"),xs(s,l);let u=Date.now()-r;Xe.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await vu(s.name,s.version,u,Vr(a),"internal"),g}catch(o){throw await Eu(e,o,"internal"),Xe.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}function Tu(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:D,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Ps(){let e=Sr();if(!q__default.existsSync(e))return null;try{return JSON.parse(q__default.readFileSync(e,"utf-8"))}catch{return null}}function Cu(){let e=Ps();if(e)return e;let t=Tu(),r=Sr();return q__default.mkdirSync(B__default.dirname(r),{recursive:true}),oo(t),t}function oo(e){let t=Sr(),r=`${t}.${randomUUID()}.tmp`;q__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),q__default.renameSync(r,t);}function ku(){let e=Qo(),t={};try{q__default.existsSync(e)&&(t=JSON.parse(q__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[D])return;t[D]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:ei(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;q__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),q__default.renameSync(r,e);}function xs(e,t){Wr(e.name),ku();let r=En(e.name);q__default.mkdirSync(B__default.dirname(r),{recursive:true});try{q__default.lstatSync(r),q__default.rmSync(r,{recursive:!0,force:!0});}catch{}q__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Cu();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}),oo(n));}function io(e){Wr(e);let t=En(e);try{q__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Ps();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&oo(r);}var $u=S("mcpConfigReader"),Lu=500,Ru=512;function Mu(){return B__default.join(Te__default.homedir(),".claude.json")}function _u(){return B__default.join(process.cwd(),".mcp.json")}function Es(e){if(!q__default.existsSync(e))return null;try{return JSON.parse(q__default.readFileSync(e,"utf-8"))}catch{return $u.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function nr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function so(e){if(!nr(e))return {};let t=e.mcpServers;return nr(t)?t:{}}function ao(e,t){return Object.keys(e).slice(0,Lu).map(n=>({name:p(n.slice(0,Ru)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Cs(){let e=[],t=Mu(),r=Es(t);if(nr(r)){let c=r,a=so(c);e.push(...ao(a,"user"));let l=process.cwd();if(nr(c.projects)){let u=c.projects[l];if(nr(u)){let g=so(u);e.push(...ao(g,"local"));}}}let n=_u(),o=Es(n),i=so(o);e.push(...ao(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 fe=S("storage");async function Du(e,t){try{await I(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:$().interfaceType});}catch(r){fe.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function Nu(e,t,r){let n=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;I(n,{tool_id:e,source:r,interface:$().interfaceType}).catch(o=>fe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function As(){return B__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function Fu(){return B__default.join(Te__default.homedir(),".claude","plugins")}function ks(e){let t=B__default.resolve(e),r=B__default.resolve(Fu()),n=B__default.resolve(B__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+B__default.sep)||t===r,i=t.startsWith(n+B__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function $s(e="user"){return e==="local"?B__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?B__default.join(process.cwd(),".claude","settings.json"):B__default.join(Te__default.homedir(),".claude","settings.json")}function De(){let e=As();if(!q__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(q__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function Uu(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ls(e,t){try{q__default.mkdirSync(B__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;q__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),q__default.renameSync(r,e);}catch(r){throw Uu(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function yt(e){Ls(As(),e);}function or(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Bu(e,t){let r=B__default.join(e,".claude-plugin"),n=B__default.join(r,"plugin.json");if(q__default.existsSync(n))try{return JSON.parse(q__default.readFileSync(n,"utf-8"))}catch{return null}let o=B__default.join(r,"marketplace.json");if(q__default.existsSync(o))try{let i=JSON.parse(q__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function po(e="user"){let t=$s(e);if(!q__default.existsSync(t))return {};try{return JSON.parse(q__default.readFileSync(t,"utf-8"))}catch{return {}}}function Rs(e,t="user"){Ls($s(t),e);}function Ku(e,t){let{name:r,marketplace:n}=or(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>or(s).name===r)[0],!o)throw fe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function ju(e,t){let{name:r,marketplace:n}=or(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>or(s).name===r)[0],o?{key:o,name:r}:null}function lo(e="user"){return po(e).enabledPlugins??{}}function co(e,t="user"){let r=po(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,Rs(r,t);}function no(e,t,r="user"){let n=po(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Rs(n,r);}function Gu(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 Le(){let e=De(),t=lo(),r=lo("project"),n=lo("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:h}=or(l),d=u.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return Gu(d).map(f=>{let w=Bu(f.installPath,g),y=(o[f.scope]??t)[l];return {name:g,marketplace:h,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,description:w?.description,author:w?.author,status:y===false?"disabled":"enabled"}})}),s=Cs(),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 qr(e,t){fe.debug(`[${e}] Acquiring lock to uninstall`);let r=await We();try{let n=De(),o=ju(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`);fe.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),ks(a.installPath);let l=B__default.dirname(a.installPath);fe.debug(`[${s}] Removing directory: ${l}`),q__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(g=>g.scope!==t);if(u.length===0){let{[i]:g,...h}=n.plugins;yt({...n,plugins:h}),co(i,t),io(s);}else n.plugins[i]=u,yt(n),co(i,t);}else {fe.debug(`[${s}] Resolved key: ${i}`);for(let u of c){ks(u.installPath);let g=B__default.dirname(u.installPath);fe.debug(`[${s}] Removing directory: ${g}`),q__default.rmSync(g,{recursive:!0,force:!0}),co(i,u.scope);}io(s);let{[i]:a,...l}=n.plugins;yt({...n,plugins:l});}await Du(s,c[0].origin??"internal"),fe.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function ir(e,t,r){fe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await We();try{let o=De(),{key:i,name:s}=Ku(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";fe.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),no(i,t==="enabled",a),Nu(s,t,l),fe.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var j=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Le()})}));var U=["discover","installed"];function Ms(e,t,r){if(t.rightArrow||t.tab){let n=U.indexOf(r.activeTab);return [{type:"setTab",tab:U[(n+1)%U.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let n=U.indexOf(r.activeTab);return [{type:"setTab",tab:U[(n-1+U.length)%U.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function _s(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=U.indexOf(r.activeTab);return [{type:"setTab",tab:U[(o-1+U.length)%U.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=U.indexOf(r.activeTab);return [{type:"setTab",tab:U[(o+1)%U.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=U.indexOf(r.activeTab);return [{type:"setTab",tab:U[(o+1)%U.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 Os(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Ds(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 Yr(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=m.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}=re.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?m.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?m.getState().selectAllTypes():i.type==="toggleOriginFilter"?m.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&m.getState().selectAllOrigins();}function Ns({listLength:e}){let t=m(f=>f.focus),r=m(f=>f.selectedIndex),n=m(f=>f.actionMenuOpen),o=m(f=>f.setFocus),i=m(f=>f.setActionMenuOpen),s=re(f=>f.query),c=re(f=>f.setQuery),a=re(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:f,setCursorPosition:w}=re.getState();w(f.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let f=setTimeout(()=>g(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,w)=>{let{activeTab:C,selectedIndex:y,actionMenuOpen:L}=m.getState();Yr(Ms(f,w,{activeTab:C}));},{isActive:t==="tabs"}),useInput((f,w)=>{let{activeTab:C,selectedIndex:y,actionMenuOpen:L}=m.getState();Yr(_s(f,w,{activeTab:C,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((f,w)=>{Yr(Os(f,w));},{isActive:t==="actionMenu"}),useInput((f,w)=>{let C=Ds(f,w,re.getState().query),y=C.queryUpdate;if(Yr(C.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:A,setCursorPosition:J}=re.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 h=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(f=>{let{setSelectedIndex:w,selectedIndex:C}=m.getState();f===0?w(0):C>=f&&w(f-1);},[]),T=useCallback(f=>{if(!u)return l.current=f.length,f;let w=u.toLowerCase(),C=f.filter(y=>y.name.toLowerCase().includes(w)||y.description?.toLowerCase().includes(w));return l.current=C.length,C},[u]);return {actionMenuOpen:n,closeMenu:h,selectedIndex:r,clampIndex:d,filteredItems:T}}function Us(){let e=m(c=>c.notification),t=m(c=>c.showNotification),r=m(c=>c.clearNotification),n=xe(c=>c.justAuthenticated),o=xe(c=>c.credentials),i=xe(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 Ne(e,t,r=false){return r?true:!go.valid(e)||!go.valid(t)?false:go.gt(t,e)}var Fe=S("updater");async function zu(e,t,r,n,o){try{await I(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){Fe.warn(`Failed to send update metrics: ${String(i)}`);}}function Wu(e){let t=De(),r=`${e}@${D}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Zr(e,t={}){let r=Date.now(),n=null;try{Fe.debug(`[${e}] Acquiring lock...`),n=await We();let o=Wu(e);if(!o)throw Fe.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;Fe.debug(`[${e}] Fetching manifest...`);let l=(await Rt(e)).version;if(!s||!Ne(s,l,t.force))throw Fe.debug(`[${e}] Already up to date (v${s??"n/a"})`),new qe(e,s??"unknown");Fe.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await oe(e,{force:!0,skipMetrics:!0}),g=Date.now()-r;return await zu(u.name,s,u.version,g,i.origin??"internal"),Fe.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){Fe.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await We();let g=De(),h=`${e}@${D}`;throw g.plugins[h]&&(g.plugins[h][0].version=s,g.plugins[h][0].installPath=c,yt(g),Fe.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var qu=S("commands:helpers");async function se(){let e=await N();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Ge();}catch(t){return qu.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 Ye(e){let t=yo.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 Bs(e){let t=yo.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(n.trim());});})}var Xu=/^[^@]+@[^@]+$/;function sr(e){return Xu.test(e)}function Mt(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Yu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Ks(e){if(!Yu.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 Zu=/^[\w./:@?&=+#%-]+$/;function Qr(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Zu.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var ar=S("claudeProxy"),wo="claude ",js="flow ",So=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ho=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";}},Qu=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,ep=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,tp=/^(flow|claude)\s+auth\s+login(\s|$)/;function rp(e){Hs(e);let t=e.slice(wo.length);if(!Qu.test(t))throw new ho(e)}var en=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function Hs(e){if(!e||!/^claude /.test(e))throw new So(e)}async function ge(e){Hs(e);let t=e.slice(wo.length).split(/\s+/).filter(Boolean),r=np(t);ar.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 ar.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 Js(o)?new en:o}}function np(e){return e.length>=3?e[2]:e.join(" ")}function Js(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function op(e){return e.startsWith(js)?wo+e.slice(js.length):e}function ip(e){return ep.test(e)||tp.test(e)}function sp(e){let t=0;for(;t<e.length&&ip(e[t]);)t++;return e.slice(t)}var ap=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function lp(e,t){return !t||e.includes("--scope")||!ap.test(e)?e:`${e} --scope ${t}`}async function Vs(e,t){let r=e.split("&&").map(s=>s.trim()).filter(Boolean),o=sp(r).map(s=>op(s)).map(s=>lp(s,t));if(o.length===0)throw new Error("Empty install command");for(let s of o)rp(s);ar.debug(`[installCommand] Executing ${o.length} command(s)`);let i=await ge(o[0]);if(i.exitCode!==0)return i;for(let s=1;s<o.length;s++)if(i=await ge(o[s]),i.exitCode!==0)return i;return i}async function zs(e,t,r){let n=Mt(e),o=t?.trim();if(!o&&(o=(await Bs(`Plugin "${n}" could not be installed.
111
- 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=Qr(o),r?.(),ar.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"}`);ar.debug(`[${n}] Marketplace added successfully`);}catch(i){throw Js(i)?new en:i}}var Ze=S("installDispatcher");async function Ws(e,t,r){try{await I(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Vr(r),version:"unknown",duration_ms:t,interface:$().interfaceType});}catch(n){Ze.warn(`Failed to send external install metrics: ${String(n)}`);}}async function qs(e,t){try{await I(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){Ze.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function xo(e,t){let r=Mt(e);Ks(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function Io(e,t,r,n){let o=xo(e,n),i=Mt(e);r?.onStatus?.(`Installing ${i}...`),Ze.debug(`[${e}] Attempting install: ${o}`);let s=await ge(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 zs(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),Ze.debug(`[${e}] Retrying install after marketplace add`),ge(o))}async function Xs(e,t){if(e.origin===gr&&e.installCommand){Ze.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await Vs(e.installCommand,t?.scope);return r.exitCode===0?await Ws(e.name,r.duration_ms,t?.scope):await qs(e.name,new Error(r.stderr||"Install failed")),r}if(sr(e.name)){Ze.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await Io(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await Ws(e.name,r.duration_ms,t?.scope):await qs(e.name,new Error(r.stderr||"Install failed")),r}return Ze.debug(`[${e.name}] Routing to internal installer`),oe(e.name,t)}function Ys(e){return "exitCode"in e}function Zs(){let e=j(s=>s.installedItems),t=j(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await Xs(s,c);if(Ys(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");j.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await qr(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 ir(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Zr(s),j.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var rn=S("mcp");function lr(e,t){e.silent?de({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 ea(e,t){e.silent?te({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(W(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&P(t.stdout));}function cp(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 bo(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function ta(e,t,r){if(!await se())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return lr(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}rn.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=cp(e,t,r.transport,r.scope);if(!r.force){let i=p(e),s=p(n);if(!await Ye(`Install external MCP "${i}"?
107
+ `);}function _t(e){process.stdout.write(JSON.stringify(e,null,2)+`
108
+ `);}function ae(e){process.stdout.write(JSON.stringify(e)+`
109
+ `);}function he(e){process.stderr.write(JSON.stringify(e)+`
110
+ `);}function K(e){return e instanceof Error?e.message:String(e)}function Gr(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function ru(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 Me=["clientId","clientSecret","tenant"],nu={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function zi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),[u,m]=useState("fields"),[y,p]=useState(null),E=useRef(0),{setCredentials:f,setJustAuthenticated:C}=Se(),M=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),I=()=>{m("fields"),p(null),t($=>({...$,clientSecret:""})),n("clientSecret");},R=async $=>{let A=M();try{Jr($),await ze(A);}catch(Z){c(Z instanceof Error?Z.message:"Failed to persist credentials"),I();return}let{clientSecret:k,...h}=A;f(h),C(true),x(w.CLI_SESSION_STARTED,{cli_version:Ye,os:process.platform,node_version:process.version,duration_ms:Xe(),interface:"tui"}).catch(()=>{}),Vr({starterKit:h.starterKit});},L=$=>{try{return Kr(M(),{allowOverwriteMalformed:$})}catch(A){return A instanceof gt?(m("malformedConfirm"),null):(c(A instanceof Error?A.message:"Failed to read settings.json"),m("fields"),null)}};useInput(($,A)=>{if(!a){if(u==="preview"){A.return&&y?R(y):A.escape&&I();return}if(u==="malformedConfirm"){if(A.return){let k=L(true);k&&(p(k),R(k));}else A.escape&&I();return}if(A.shift&&A.tab){let k=Me.indexOf(r);k>0&&n(Me[k-1]);}else if(A.tab){let k=Me.indexOf(r);k<Me.length-1&&n(Me[k+1]);}else if(A.return)if(r==="tenant")V();else {let k=Me.indexOf(r);n(Me[k+1]);}}},{isActive:true});let V=async()=>{let $={};for(let A of Me)e[A].trim()||($[A]="This field is required");if(Object.keys($).length>0){i($);let A=Me.find(k=>$[k]);A&&n(A);return}l(true),c(null),E.current+=1;try{await dt(M());let A=L(!1);A&&(p(A),m("preview"));}catch(A){let k=A instanceof Error?A.message:"Authentication failed";c(k),Oi(w.CLI_AUTH_FAILED,{error_code:ru(A),attempt:E.current},e.tenant.trim()).catch(()=>{}),t(h=>({...h,clientSecret:""}));}finally{l(false);}},Y=$=>A=>{t(k=>({...k,[$]:A})),o[$]&&i(k=>({...k,[$]:void 0}));};return u==="preview"&&y?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:y.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),y.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm \xB7 Esc cancel"})})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[wr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \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:Me.map($=>jsx(Box,{marginBottom:1,children:jsx(Ki,{label:nu[$],value:e[$],onChange:Y($),masked:$==="clientSecret",isActive:r===$&&!a,error:o[$]})},$))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",d(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Ot(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(iu,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Ye]})})]})}var io={discover:"Discover",installed:"Installed"},su=Object.keys(io);function Qi(){let e=g(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:su.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${io[t]} `}):jsx(Text,{dimColor:true,children:` ${io[t]} `})},t))})}var le=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function ts(){let e=g(s=>s.focus),t=le(s=>s.query),r=le(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 uu=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...kt[e]})),du=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...ci[e]}));function rs(){let e=g(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"]})]}),uu.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"]})]}),du.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 ns({type:e}){let{label:t,color:r}=kt[e];return jsx(Text,{color:r,children:t})}function ss({origin:e}){return e===Ht?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Wr=fu.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(ns,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(ss,{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 ",Gr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Dt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function cs({items:e,emptyMessage:t}){let r=g(a=>a.selectedIndex);if(e.length===0)return jsx(Dt,{message:t});let n=Math.max(0,r-Math.floor(He/2)),o=Math.min(e.length,n+He);o===e.length&&(n=Math.max(0,o-He));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(Wr,{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 ps({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 fs({groups:e,emptyMessage:t}){let r=g(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let E of p.items)n.push({kind:"item",item:E,itemIndex:o,key:`i-${p.scope}-${E.name}`}),o++;}if(o===0)return jsx(Dt,{message:t});let s=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),c=s>=0?s:0,a=Math.max(0,c-Math.floor(He/2)),l=Math.min(n.length,a+He);l===n.length&&(a=Math.max(0,l-He));let u=n.slice(a,l),m=a,y=n.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2191 ${m} more above`:" "})}),u.map(p=>p.kind==="header"?jsx(ps,{label:p.label,pathHint:p.pathHint},p.key):jsx(Wr,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:y>0?`\u2193 ${y} more below`:" "})})]})}var bu={discover:"Discover",installed:"Installed"};function ys({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(ts,{}),jsx(rs,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:bu[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(fs,{groups:n,emptyMessage:r}):jsx(cs,{items:e,emptyMessage:r})]})}function Ss({filteredItems:e,emptyMessage:t,groups:r}){let n=g(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(ys,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(ys,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Pu={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 qr(){let e=g(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Pu[e],t?" | Ctrl+D: debug log":""]})})}function hs({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"," ",d(e)]})}):null}function Xr({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ru,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Yr({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 It({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=g(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 go=Object.entries(Gt),Es=[...go.map(([,e])=>e.actionLabel),"Cancel"],Ts=Object.fromEntries(go.map(([,e])=>[e.actionLabel,e.description]));function Cs(e){let t=go.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function As({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=Cs(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(It,{itemName:`${e} \u2014 Choose scope`,actions:Es,descriptions:Ts,onAction:i,onClose:s}):jsx(It,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Qr({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=g(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 Rs({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Qr({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 m=r==="enabled"?"Disable":"Enable",y=o&&d(o),p=y?`Update to v${y}`:"Update";return jsx(It,{itemName:e,actions:n?["Uninstall",m,p,"Cancel"]:["Uninstall",m,"Cancel"],onAction:C=>{C==="Uninstall"?u():C===m?s(t):C.startsWith("Update")?c?.():a();},onClose:a})}function Os({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Qr({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(It,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function Ds(e,t){let r=G.resolve(t);await _e.mkdir(r,{recursive:true});let n=G.join(G.dirname(r),`${randomUUID()}.zip`);try{await _e.writeFile(n,e),await ju(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=G.resolve(r,o.fileName);if(!s.startsWith(r+G.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(G.resolve(G.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 _e.unlink(n);}catch{}}}async function So(e){await _e.rm(e,{recursive:true,force:true});}async function Qe(){let e=yi();await _e.mkdir(G.dirname(e),{recursive:true});try{await _e.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Ku.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var Hu={user:"global",project:"project",local:"local"};function rn(e){return e?Hu[e]:"global"}var ce=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},et=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 sr(){return Cc.create({prefix:Mt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await qe();e.headers.set("Authorization",`Bearer ${t}`);let r=await j();r?.tenant&&lt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Vu=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Ns(e){if(!e||!Vu.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function Oe(){try{let{plugins:e}=await sr().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 Ft(e){Ns(e);try{return await sr().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 Fs(e){Ns(e);try{let t=await sr().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 nn(){try{let{profiles:e}=await sr().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 zu=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Wu=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function on(e){if(!zu.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function qu(e){if(!Wu.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 tt=S("installer");function Xu(e,t){let r=`${e}@${B}`,o=Be().plugins[r];if(o&&!t)throw new ce(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Yu(e,t,r){r&&await So(t);try{tt.debug(`[${t}] Extracting archive...`),await Ds(e,t);}catch(n){throw await So(t),n}}function Zu(e,t,r,n,o){let i=Be(),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],vt(i),ho(e,true,n);}async function Qu(e,t,r,n,o){try{await x(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:_().interfaceType});}catch(i){tt.warn(`Failed to send install metrics: ${String(i)}`);}}async function ed(e,t,r){try{await x(w.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){tt.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function ue(e,t={}){let r=Date.now(),n=null;try{tt.debug(`[${e}] Acquiring lock...`),n=await Qe();let{pluginKey:o,alreadyInstalled:i}=Xu(e,t.force);tt.debug(`[${e}] Fetching manifest...`);let s=await Ft(e);on(s.name),qu(s.version),tt.debug(`[${e}] Downloading archive...`);let c=await Fs(e),a=t.scope??"user",l=mi(s.name,s.version);await Yu(c,l,!!i&&!!t.force),Zu(o,l,s.version,a,"internal"),Us(s,l);let u=Date.now()-r;tt.debug(`[${e}] Installed successfully in ${u}ms`);let m={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await Qu(s.name,s.version,u,rn(a),"internal"),m}catch(o){throw await ed(e,o,"internal"),tt.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}function td(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:B,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Ks(){let e=Ir();if(!re__default.existsSync(e))return null;try{return JSON.parse(re__default.readFileSync(e,"utf-8"))}catch{return null}}function rd(){let e=Ks();if(e)return e;let t=td(),r=Ir();return re__default.mkdirSync(G__default.dirname(r),{recursive:true}),wo(t),t}function wo(e){let t=Ir(),r=`${t}.${randomUUID()}.tmp`;re__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),re__default.renameSync(r,t);}function nd(){let e=fi(),t={};try{re__default.existsSync(e)&&(t=JSON.parse(re__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[B])return;t[B]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:gi(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;re__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),re__default.renameSync(r,e);}function Us(e,t){on(e.name),nd();let r=On(e.name);re__default.mkdirSync(G__default.dirname(r),{recursive:true});try{re__default.lstatSync(r),re__default.rmSync(r,{recursive:!0,force:!0});}catch{}re__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=rd();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}),wo(n));}function xo(e){on(e);let t=On(e);try{re__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Ks();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&wo(r);}var id=S("mcpConfigReader"),sd=500,ad=512;function ld(){return G__default.join(Le__default.homedir(),".claude.json")}function cd(){return G__default.join(process.cwd(),".mcp.json")}function Hs(e){if(!re__default.existsSync(e))return null;try{return JSON.parse(re__default.readFileSync(e,"utf-8"))}catch{return id.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bo(e){if(!ar(e))return {};let t=e.mcpServers;return ar(t)?t:{}}function Io(e,t){return Object.keys(e).slice(0,sd).map(n=>({name:d(n.slice(0,ad)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Vs(){let e=[],t=ld(),r=Hs(t);if(ar(r)){let c=r,a=bo(c);e.push(...Io(a,"user"));let l=process.cwd();if(ar(c.projects)){let u=c.projects[l];if(ar(u)){let m=bo(u);e.push(...Io(m,"local"));}}}let n=cd(),o=Hs(n),i=bo(o);e.push(...Io(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 xe=S("storage");async function dd(e,t){try{await x(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:_().interfaceType});}catch(r){xe.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function pd(e,t,r){let n=t==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;x(n,{tool_id:e,source:r,interface:_().interfaceType}).catch(o=>xe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ws(){return G__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function md(){return G__default.join(Le__default.homedir(),".claude","plugins")}function zs(e){let t=G__default.resolve(e),r=G__default.resolve(md()),n=G__default.resolve(G__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+G__default.sep)||t===r,i=t.startsWith(n+G__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function qs(e="user"){return e==="local"?G__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?G__default.join(process.cwd(),".claude","settings.json"):G__default.join(Le__default.homedir(),".claude","settings.json")}function Be(){let e=Ws();if(!re__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(re__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function fd(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Xs(e,t){try{re__default.mkdirSync(G__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;re__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),re__default.renameSync(r,e);}catch(r){throw fd(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function vt(e){Xs(Ws(),e);}function lr(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function gd(e,t){let r=G__default.join(e,".claude-plugin"),n=G__default.join(r,"plugin.json");if(re__default.existsSync(n))try{return JSON.parse(re__default.readFileSync(n,"utf-8"))}catch{return null}let o=G__default.join(r,"marketplace.json");if(re__default.existsSync(o))try{let i=JSON.parse(re__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function To(e="user"){let t=qs(e);if(!re__default.existsSync(t))return {};try{return JSON.parse(re__default.readFileSync(t,"utf-8"))}catch{return {}}}function Ys(e,t="user"){Xs(qs(t),e);}function yd(e,t){let{name:r,marketplace:n}=lr(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>lr(s).name===r)[0],!o)throw xe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Sd(e,t){let{name:r,marketplace:n}=lr(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>lr(s).name===r)[0],o?{key:o,name:r}:null}function vo(e="user"){return To(e).enabledPlugins??{}}function Po(e,t="user"){let r=To(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,Ys(r,t);}function ho(e,t,r="user"){let n=To(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Ys(n,r);}function hd(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 De(){let e=Be(),t=vo(),r=vo("project"),n=vo("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:m,marketplace:y}=lr(l),p=u.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return hd(p).map(f=>{let C=gd(f.installPath,m),I=(o[f.scope]??t)[l];return {name:m,marketplace:y,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,description:C?.description,author:C?.author,status:I===false?"disabled":"enabled"}})}),s=Vs(),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 sn(e,t){xe.debug(`[${e}] Acquiring lock to uninstall`);let r=await Qe();try{let n=Be(),o=Sd(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(m=>m.scope===t);if(!a)throw new Error(`Plugin '${s}' is not installed in ${t} scope`);xe.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),zs(a.installPath);let l=G__default.dirname(a.installPath);xe.debug(`[${s}] Removing directory: ${l}`),re__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(m=>m.scope!==t);if(u.length===0){let{[i]:m,...y}=n.plugins;vt({...n,plugins:y}),Po(i,t),xo(s);}else n.plugins[i]=u,vt(n),Po(i,t);}else {xe.debug(`[${s}] Resolved key: ${i}`);for(let u of c){zs(u.installPath);let m=G__default.dirname(u.installPath);xe.debug(`[${s}] Removing directory: ${m}`),re__default.rmSync(m,{recursive:!0,force:!0}),Po(i,u.scope);}xo(s);let{[i]:a,...l}=n.plugins;vt({...n,plugins:l});}await dd(s,c[0].origin??"internal"),xe.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function cr(e,t,r){xe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Qe();try{let o=Be(),{key:i,name:s}=yd(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";xe.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),ho(i,t==="enabled",a),pd(s,t,l),xe.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var q=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:De()})}));var J=["discover","installed"];function Zs(e,t,r){if(t.rightArrow||t.tab){let n=J.indexOf(r.activeTab);return [{type:"setTab",tab:J[(n+1)%J.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let n=J.indexOf(r.activeTab);return [{type:"setTab",tab:J[(n-1+J.length)%J.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function Qs(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=J.indexOf(r.activeTab);return [{type:"setTab",tab:J[(o-1+J.length)%J.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=J.indexOf(r.activeTab);return [{type:"setTab",tab:J[(o+1)%J.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=J.indexOf(r.activeTab);return [{type:"setTab",tab:J[(o+1)%J.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 ea(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function ta(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 ln(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=g.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}=le.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?g.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?g.getState().selectAllTypes():i.type==="toggleOriginFilter"?g.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&g.getState().selectAllOrigins();}function ra({listLength:e}){let t=g(f=>f.focus),r=g(f=>f.selectedIndex),n=g(f=>f.actionMenuOpen),o=g(f=>f.setFocus),i=g(f=>f.setActionMenuOpen),s=le(f=>f.query),c=le(f=>f.setQuery),a=le(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:f,setCursorPosition:C}=le.getState();C(f.length);}},[t]);let[u,m]=useState("");useEffect(()=>{let f=setTimeout(()=>m(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,C)=>{let{activeTab:M,selectedIndex:I,actionMenuOpen:R}=g.getState();ln(Zs(f,C,{activeTab:M}));},{isActive:t==="tabs"}),useInput((f,C)=>{let{activeTab:M,selectedIndex:I,actionMenuOpen:R}=g.getState();ln(Qs(f,C,{activeTab:M,selectedIndex:I},l.current));},{isActive:t==="list"}),useInput((f,C)=>{ln(ea(f,C));},{isActive:t==="actionMenu"}),useInput((f,C)=>{let M=ta(f,C,le.getState().query),I=M.queryUpdate;if(ln(M.actions),I==="reset")a(),m("");else if(I!==null){let{query:R,cursorPosition:L,setCursorPosition:V}=le.getState();if("backspace"in I)L>0&&(c(R.slice(0,L-1)+R.slice(L)),V(L-1));else if("append"in I)c(R.slice(0,L)+I.append+R.slice(L)),V(L+I.append.length);else if("cursorMove"in I){let Y=L+I.cursorMove;Y>=0&&Y<=R.length&&V(Y);}}},{isActive:t==="search"});let y=useCallback(()=>{i(false),o("list");},[i,o]),p=useCallback(f=>{let{setSelectedIndex:C,selectedIndex:M}=g.getState();f===0?C(0):M>=f&&C(f-1);},[]),E=useCallback(f=>{if(!u)return l.current=f.length,f;let C=u.toLowerCase(),M=f.filter(I=>I.name.toLowerCase().includes(C)||I.description?.toLowerCase().includes(C));return l.current=M.length,M},[u]);return {actionMenuOpen:n,closeMenu:y,selectedIndex:r,clampIndex:p,filteredItems:E}}function oa(){let e=g(c=>c.notification),t=g(c=>c.showNotification),r=g(c=>c.clearNotification),n=Se(c=>c.justAuthenticated),o=Se(c=>c.credentials),i=Se(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 je(e,t,r=false){return r?true:!Ao.valid(e)||!Ao.valid(t)?false:Ao.gt(t,e)}var Ke=S("updater");async function Id(e,t,r,n,o){try{await x(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:_().interfaceType});}catch(i){Ke.warn(`Failed to send update metrics: ${String(i)}`);}}function vd(e){let t=Be(),r=`${e}@${B}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function cn(e,t={}){let r=Date.now(),n=null;try{Ke.debug(`[${e}] Acquiring lock...`),n=await Qe();let o=vd(e);if(!o)throw Ke.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;Ke.debug(`[${e}] Fetching manifest...`);let l=(await Ft(e)).version;if(!s||!je(s,l,t.force))throw Ke.debug(`[${e}] Already up to date (v${s??"n/a"})`),new et(e,s??"unknown");Ke.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await ue(e,{force:!0,skipMetrics:!0}),m=Date.now()-r;return await Id(u.name,s,u.version,m,i.origin??"internal"),Ke.debug(`[${e}] Updated successfully in ${m}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:m}}catch(u){Ke.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await Qe();let m=Be(),y=`${e}@${B}`;throw m.plugins[y]&&(m.plugins[y][0].version=s,m.plugins[y][0].installPath=c,vt(m),Ke.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var Pd=S("commands:helpers");async function pe(){let e=await j();if(!e)return T("Not authenticated. Run: flow auth login"),false;try{await qe();}catch(t){return Pd.debug(`Token validation failed: ${String(t)}`),T("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(T("Starter kit not set. Run: flow auth login"),false):true}async function rt(e){let t=$o.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(d(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function ia(e){let t=$o.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(d(e),n=>{t.close(),r(n.trim());});})}var Ed=/^[^@]+@[^@]+$/;function ur(e){return Ed.test(e)}function Ut(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Td=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function sa(e){if(!Td.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 Cd=/^[\w./:@?&=+#%-]+$/;function un(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Cd.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var dr=S("claudeProxy"),Mo="claude ",aa="flow ",Lo=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Ro=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";}},kd=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ad=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,$d=/^(flow|claude)\s+auth\s+login(\s|$)/;function Ld(e){ca(e);let t=e.slice(Mo.length);if(!kd.test(t))throw new Ro(e)}var dn=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function ca(e){if(!e||!/^claude /.test(e))throw new Lo(e)}async function be(e){ca(e);let t=e.slice(Mo.length).split(/\s+/).filter(Boolean),r=Rd(t);dr.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 dr.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 ua(o)?new dn:o}}function Rd(e){return e.length>=3?e[2]:e.join(" ")}function ua(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Md(e){return e.startsWith(aa)?Mo+e.slice(aa.length):e}function _d(e){return Ad.test(e)||$d.test(e)}function Od(e){let t=0;for(;t<e.length&&_d(e[t]);)t++;return e.slice(t)}var Dd=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Nd(e,t){return !t||e.includes("--scope")||!Dd.test(e)?e:`${e} --scope ${t}`}async function da(e,t){let r=e.split("&&").map(s=>s.trim()).filter(Boolean),o=Od(r).map(s=>Md(s)).map(s=>Nd(s,t));if(o.length===0)throw new Error("Empty install command");for(let s of o)Ld(s);dr.debug(`[installCommand] Executing ${o.length} command(s)`);let i=await be(o[0]);if(i.exitCode!==0)return i;for(let s=1;s<o.length;s++)if(i=await be(o[s]),i.exitCode!==0)return i;return i}async function pa(e,t,r){let n=Ut(e),o=t?.trim();if(!o&&(o=(await ia(`Plugin "${n}" could not be installed.
111
+ 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=un(o),r?.(),dr.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"}`);dr.debug(`[${n}] Marketplace added successfully`);}catch(i){throw ua(i)?new dn:i}}var nt=S("installDispatcher");async function ma(e,t,r){try{await x(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:rn(r),version:"unknown",duration_ms:t,interface:_().interfaceType});}catch(n){nt.warn(`Failed to send external install metrics: ${String(n)}`);}}async function fa(e,t){try{await x(w.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){nt.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function _o(e,t){let r=Ut(e);sa(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function Oo(e,t,r,n){let o=_o(e,n),i=Ut(e);r?.onStatus?.(`Installing ${i}...`),nt.debug(`[${e}] Attempting install: ${o}`);let s=await be(o);return s.exitCode===0?s:(nt.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 pa(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),nt.debug(`[${e}] Retrying install after marketplace add`),be(o))}async function ga(e,t){if(e.origin===xr&&e.installCommand){nt.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await da(e.installCommand,t?.scope);return r.exitCode===0?await ma(e.name,r.duration_ms,t?.scope):await fa(e.name,new Error(r.stderr||"Install failed")),r}if(ur(e.name)){nt.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await Oo(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await ma(e.name,r.duration_ms,t?.scope):await fa(e.name,new Error(r.stderr||"Install failed")),r}return nt.debug(`[${e.name}] Routing to internal installer`),ue(e.name,t)}function ya(e){return "exitCode"in e}function Sa(){let e=q(s=>s.installedItems),t=q(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await ga(s,c);if(ya(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");q.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await sn(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 cr(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await cn(s),q.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var mn=S("mcp");function pr(e,t){e.silent?he({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):T(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function wa(e,t){e.silent?ae({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(te(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&v(t.stdout));}function Fd(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 Do(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function xa(e,t,r){if(!await pe())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return pr(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}mn.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Fd(e,t,r.transport,r.scope);if(!r.force){let i=d(e),s=d(n);if(!await rt(`Install external MCP "${i}"?
112
112
  This will run: ${s}
113
- [y/N] `))return rn.debug(`[${e}] Installation cancelled by user`),P("Operation cancelled."),0}let o=r.silent?void 0:Ko({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await ge(n);return o?.stop(),i.exitCode!==0?(lr(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&P(`stdout: ${i.stdout}`),1):(ea(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),lr(r,{name:e,action:"add",message:F(i)}),1}}async function ra(e,t){if(!await se())return 1;rn.debug(`[${e}] Starting MCP remove`);let r=bo(e,t.scope);if(!t.force){let o=p(e),i=p(r);if(!await Ye(`Remove MCP "${o}"?
113
+ [y/N] `))return mn.debug(`[${e}] Installation cancelled by user`),v("Operation cancelled."),0}let o=r.silent?void 0:ni({text:`Adding MCP "${d(e)}"...`}).start();try{let i=await be(n);return o?.stop(),i.exitCode!==0?(pr(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&v(`stdout: ${i.stdout}`),1):(wa(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),pr(r,{name:e,action:"add",message:K(i)}),1}}async function ba(e,t){if(!await pe())return 1;mn.debug(`[${e}] Starting MCP remove`);let r=Do(e,t.scope);if(!t.force){let o=d(e),i=d(r);if(!await rt(`Remove MCP "${o}"?
114
114
  This will run: ${i}
115
- [y/N] `))return rn.debug(`[${e}] Removal cancelled by user`),P("Operation cancelled."),0}let n=t.silent?void 0:Ko({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await ge(r);return n?.stop(),o.exitCode!==0?(lr(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&P(`stdout: ${o.stdout}`),1):(ea(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),lr(t,{name:e,action:"remove",message:F(o)}),1}}function na({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=m(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Zs(),h=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&&h(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&h(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";h(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 qe)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&&h(`Removing MCP ${e.name}...`,async()=>{let L=bo(e.name,y),A=await ge(L);if(A.exitCode!==0)throw new Error(A.stderr||"MCP removal failed");j.getState().loadFromDisk();},"\u2713 MCP removed");}}}var cr=["local","project","user"],up=new Set(["--transport","--scope","-s"]);function oa(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(up.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function ur(e,t){return t?`${e}::${t}`:e}function Po(e){return e===D?Ut:gr}function ia(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??Ut}}function sa(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 aa(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 cr.filter(r=>t.has(r)).map(r=>({scope:r,label:Bt[r].label,pathHint:Bt[r].pathHint,items:t.get(r)??[]}))}function la(e){let t=r=>{if(!r)return 1/0;let n=cr.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function ca({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>ur(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(T=>[ur(T.name,T.author.name),T]));return t.map(T=>{let f=d.get(ur(T.name,T.author?.name)),w=f?.version,C=!!w&&!!T.version&&Ne(T.version,w);return {...T,updateAvailable:C,catalogItem:f}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(d=>{if(i.has(ur(d.name,d.author.name)))return false;if(d.type==="mcp"){let T=d.installCommand?oa(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||T&&s.has(T))return false}return true}).map(d=>ia(d)):c.map(d=>sa(d,d.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let T=d.type??"plugin";if(!n.types.has(T))return false;let f=d.origin??"internal";return n.origins.has(f)}),[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]),h=useMemo(()=>d=>d?e.find(T=>T.name===d.name&&T.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:h}}function ua(){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 $e();t(a),s.current||(s.current=!0,I(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 pa(){return {items:j(t=>t.installedItems)}}var gp=S("catalog");function da(){let e=m(M=>M.activeTab),t=m(M=>M.notification),r=m(M=>M.loading),n=m(M=>M.loadingMessage),o=m(M=>M.catalogError),i=m(M=>M.setCatalogError),s=m(M=>M.catalogFilters),c=re(M=>M.query),{catalog:a,isLoading:l,error:u,refetch:g}=ua(),{items:h}=pa(),d=j(M=>M.loadFromDisk),{items:T,emptyMessage:f,getSelectedCatalogItem:w}=ca({catalog:a,installedItems:h,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:C,closeMenu:y,selectedIndex:L,clampIndex:A,filteredItems:J}=Ns({listLength:T.length}),Q=J(T),Me=useMemo(()=>e!=="installed"?Q:la(Q),[e,Q]),wn=useMemo(()=>e==="installed"?aa(Me):[],[e,Me]),V=Me[L]??null,b=useMemo(()=>w(V),[w,V]),{notify:ce}=Us(),{handleInstall:H,handleUninstall:K,handleToggleStatus:xn,handleUpdate:In,handleMcpConfigUninstall:Vo}=na({selectedItem:V,selectedCatalogItem:b,items:T,closeMenu:y,clampIndex:A,notify:ce});return useEffect(()=>{d();},[]),useEffect(()=>{A(Me.length);},[Me.length,A]),useEffect(()=>{u&&(gp.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(At,{}),jsx(Mi,{}),jsx(Yi,{filteredItems:Me,groups:wn,emptyMessage:f}),(r||l)&&jsx(Br,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Kr,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(Qi,{message:t.message,type:t.type}),C&&V&&(e==="discover"?jsx(us,{itemName:V.name,onInstall:H,onClose:y}):V.type==="mcp"?jsx(ys,{itemName:V.name,itemScope:V.scope??"user",onUninstall:Vo,onClose:y}):jsx(ms,{itemName:V.name,itemScope:V.scope??"user",itemStatus:V.status??"enabled",updateAvailable:V.updateAvailable??false,catalogVersion:b?.version,onUninstall:K,onToggleStatus:M=>xn(M),onUpdate:In,onClose:y})),jsx(Ur,{})]})}var v=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 wp=3;function fa(){let e=v(a=>a.setStarterKits),t=v(a=>a.setIsLoadingStarterKits),r=v(a=>a.setStarterKitsError),n=v(a=>a.setPluginStatus),o=v(a=>a.setStep),i=v(a=>a.computeSummary),s=useCallback(async()=>{t(true),r(null);try{let a=await zr();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=v.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){n(u.name,"installing");let g="",h=false;for(let d=1;d<=wp;d++)try{await oe(u.name),n(u.name,"success"),h=!0;break}catch(T){if(T instanceof ne){n(u.name,"success"),h=true;break}g=T instanceof Error?T.message:"Unknown error";}h||(n(u.name,"failed",g),I(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=ct();lt("summary_review"),I(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 pr={cursorDelta:0,confirm:false,back:false};function ga(e,t){return t.upArrow?{...pr,cursorDelta:-1}:t.downArrow?{...pr,cursorDelta:1}:t.escape?{...pr,back:true}:t.return?{...pr,confirm:true}:pr}var xp={cursorDelta:0,select:false};function ya(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:xp}var Sa=Kc.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 $o=5;function ha({onRetry:e}){let t=v(u=>u.starterKits),r=v(u=>u.selectedStarterKitIndex),n=v(u=>u.isLoadingStarterKits),o=v(u=>u.starterKitsError);if(n)return jsx(Br,{message:"Loading Starter Kits..."});if(o)return jsx(Kr,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx($t,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor($o/2)),s=Math.min(t.length,i+$o);s===t.length&&(i=Math.max(0,s-$o));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(Sa,{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 xa=Kc.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 Mo=8;function Ia(){let e=v(u=>u.selectedStarterKit),t=v(u=>u.plugins),r=v(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,I(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(Mo/2)),s=Math.min(t.length,i+Mo);s===t.length&&(i=Math.max(0,s-Mo));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(xa,{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 Ap=["Retry failed","Continue anyway"];function ba({name:e,status:t,error:r}){let n=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nu,{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 Pa({onComplete:e,onRetry:t}){let r=v(l=>l.plugins),n=v(l=>l.step),o=v(l=>l.successCount),i=v(l=>l.failedCount),s=v(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(ba,{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(ba,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Ap.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 va(){let e=v(b=>b.step),t=v(b=>b.starterKits),r=v(b=>b.selectedStarterKitIndex),n=v(b=>b.setSelectedStarterKitIndex),o=v(b=>b.selectStarterKit),i=v(b=>b.plugins),s=v(b=>b.pluginCursorIndex),c=v(b=>b.setPluginCursorIndex),a=v(b=>b.setStep),l=v(b=>b.summaryActionIndex),u=v(b=>b.setSummaryActionIndex),g=v(b=>b.failedCount),h=v(b=>b.resetForRetry),d=v(b=>b.goBackToList),T=m(b=>b.setScreen),f=m(b=>b.setFocus),w=m(b=>b.focus),C=xe(b=>b.setJustAuthenticated),y=xe(b=>b.justAuthenticated),{loadStarterKits:L,installSelected:A}=fa(),J=useRef(false);useEffect(()=>{e==="bundleList"?(f("bundleList"),J.current||(J.current=true,lt("bundle_selection"))):f(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,f]);let Q=useCallback(async()=>{let b=v.getState().selectedStarterKit;if(b){let H=await N();H&&await st({...H,starterKit:b.slug});}I(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ct()}).catch(()=>{});let{successCount:ce}=v.getState();I(x.CLI_ONBOARDING_COMPLETED,{duration_ms:He(),tools_installed_count:ce}).catch(()=>{}),C(false),f("list"),T("claudeMdSuggestion");},[C,f,T]),Me=useCallback(()=>{h(),A();},[h,A]),wn=useCallback(()=>{L();},[L]),V=useCallback(()=>{f("list"),T("claudeMdSuggestion");},[f,T]);return useInput((b,ce)=>{if(ce.escape)Mr("esc"),V();else if(ce.upArrow&&r>0)n(r-1);else if(ce.downArrow&&r<t.length-1)n(r+1);else if(ce.return&&t.length>0){let H=ct();o(t[r]),lt("kit_display"),I(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:H}).catch(()=>{});}},{isActive:w==="bundleList"}),useInput((b,ce)=>{let H=ga(b,ce);if(H.cursorDelta!==0){let K=s+H.cursorDelta;K>=0&&K<i.length&&c(K);}if(H.confirm){let K=v.getState().selectedStarterKit;K&&(async()=>(await N())?.starterKit!==K.slug&&I(x.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let xn=ct();lt("kit_confirmation"),I(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:xn}).catch(()=>{});let In=ct();lt("tool_installation"),I(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:In}).catch(()=>{}),a("installing"),A();}if(H.back){let K=v.getState().selectedStarterKit;K&&I(x.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),d();}},{isActive:w==="bundleDetail"}),useInput((b,ce)=>{if(g===0)return;let H=ya(b,ce);if(H.cursorDelta!==0){let K=l+H.cursorDelta;K>=0&&K<=1&&u(K);}H.select&&(l===0?Me():Q());},{isActive:w==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(At,{}),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(ha,{onRetry:wn}),e==="bundleDetail"&&jsx(Ia,{}),(e==="installing"||e==="summary")&&jsx(Pa,{onComplete:Q,onRetry:Me})]}),jsx(Ur,{})]})}var Op=S("ClaudeMdSuggestion"),Dp=[`Install ${z}`,"Skip for now"],Np=["Retry","Skip for now"];function Ca(){let e=m(h=>h.setScreen),t=m(h=>h.setFocus),r=v(h=>h.successCount),[n,o]=useState("prompt"),[i,s]=useState(0),c=useRef(0),a=useCallback(()=>{t("list"),e("main");},[t,e]),l=useCallback(()=>{I(x.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),a();},[a]),u=useCallback(async()=>{c.current+=1,I(x.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:c.current}).catch(()=>{}),o("installing");try{await oe(z),o("installed");}catch(h){if(h instanceof ne){o("installed");return}Op.warn(`Failed to install ${z}: ${h instanceof Error?h.message:h}`),o("error");}},[]),g=n==="error"?Np:Dp;return useInput((h,d)=>{if(d.escape){n==="prompt"||n==="error"?l():n==="installed"&&a();return}if(n==="prompt"||n==="error"){d.upArrow&&i>0?s(i-1):d.downArrow&&i<g.length-1?s(i+1):d.return&&(i===0?(s(0),u()):l());return}n==="installed"&&d.return&&a();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(At,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Ta,{options:g,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",z,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",z," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",z]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",z]}),jsx(Ta,{options:g,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Ta({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var Up=S("app"),Bp={auth:Ci,bundleSetup:va,claudeMdSuggestion:Ca,main:da};function $a(){m.getState().setScreen("auth"),m.getState().setFocus("auth");}async function Ra(){let e=await N();if(!e){$a();return}try{await Ge();}catch(o){Up.debug(`Token validation failed: ${String(o)}`),$a();return}I(x.CLI_SESSION_STARTED,{cli_version:Je,os:process.platform,node_version:process.version,duration_ms:He(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...r}=e;xe.getState().setCredentials(r),!e.starterKit||e.starterKit.trim()===""?(m.getState().setScreen("bundleSetup"),m.getState().setFocus("bundleList")):(m.getState().setScreen("main"),m.getState().setFocus("list"));}function Ma(){let{columns:e,rows:t}=useWindowSize(),r=m(i=>i.screen),n=Bp[r],{pendingExit:o}=Ei();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 ve=S("auth");function Oa(){ee.clearFallbackFile(),kr();}var Kp=3,_a=3,Da=` \u2139 The data collected during setup is used solely to improve
115
+ [y/N] `))return mn.debug(`[${e}] Removal cancelled by user`),v("Operation cancelled."),0}let n=t.silent?void 0:ni({text:`Removing MCP "${d(e)}"...`}).start();try{let o=await be(r);return n?.stop(),o.exitCode!==0?(pr(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&v(`stdout: ${o.stdout}`),1):(wa(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),pr(t,{name:e,action:"remove",message:K(o)}),1}}function Ia({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=g(I=>I.setLoading),{install:a,uninstall:l,toggle:u,update:m}=Sa(),y=async(I,R,L)=>{c(true,I),n();try{await R(),o(r.length),i(L,"success");}catch(V){let Y=V instanceof Error?V.message:"Something went wrong";s.error(`[withLoading] ${I} failed: ${Y}`),i(Y,"error");}finally{c(false);}};return {handleInstall:I=>{e&&t&&y(`Installing ${e.name}...`,()=>a(t,{scope:I}),"\u2713 Installed successfully");},handleUninstall:I=>{e&&y(`Uninstalling ${e.name}...`,()=>l(e.name,I),"\u2713 Uninstalled");},handleToggleStatus:I=>{if(!e)return;let R=e.status==="enabled";y(R?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,I),R?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let I=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${I}...`),n();try{await m(e.name),o(r.length),i(`\u2713 Updated ${e.name}${I}`,"success");}catch(L){if(L instanceof et)i(L.message,"info");else {let V=L instanceof Error?L.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${V}`),i(V,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:I=>{e&&y(`Removing MCP ${e.name}...`,async()=>{let R=Do(e.name,I),L=await be(R);if(L.exitCode!==0)throw new Error(L.stderr||"MCP removal failed");q.getState().loadFromDisk();},"\u2713 MCP removed");}}}var mr=["local","project","user"],Ud=new Set(["--transport","--scope","-s"]);function va(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(Ud.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function fr(e,t){return t?`${e}::${t}`:e}function No(e){return e===B?Ht:xr}function Pa(e){return {name:d(e.name),version:e.version?d(e.version):e.version,description:e.description?d(e.description):e.description,authorName:e.author.name?d(e.author.name):e.author.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??Ht}}function Ea(e,t){let r=No(e.marketplace);return {name:d(e.name),version:e.version?d(e.version):e.version,description:e.description?d(e.description):e.description,authorName:e.author?.name?d(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 Ta(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 mr.filter(r=>t.has(r)).map(r=>({scope:r,label:Gt[r].label,pathHint:Gt[r].pathHint,items:t.get(r)??[]}))}function Ca(e){let t=r=>{if(!r)return 1/0;let n=mr.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function ka({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(p=>fr(p.name,p.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(p=>p.type==="mcp").map(p=>p.name.toLowerCase())),[t]),c=useMemo(()=>{let p=new Map(e.map(E=>[fr(E.name,E.author.name),E]));return t.map(E=>{let f=p.get(fr(E.name,E.author?.name)),C=f?.version,M=!!C&&!!E.version&&je(E.version,C);return {...E,updateAvailable:M,catalogItem:f}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(p=>{if(i.has(fr(p.name,p.author.name)))return false;if(p.type==="mcp"){let E=p.installCommand?va(p.installCommand)?.toLowerCase():null;if(s.has(p.name.toLowerCase())||E&&s.has(E))return false}return true}).map(p=>Pa(p)):c.map(p=>Ea(p,p.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(p=>{let E=p.type??"plugin";if(!n.types.has(E))return false;let f=p.origin??"internal";return n.origins.has(f)}),[a,n]),u=useMemo(()=>{let{types:p}=n;if(p.size===1){if(p.has("skill"))return "skills";if(p.has("mcp"))return "MCPs";if(p.has("plugin"))return "plugins"}return "items"},[n]),m=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]),y=useMemo(()=>p=>p?e.find(E=>E.name===p.name&&E.author.name===p.authorName)??null:null,[e]);return {items:l,emptyMessage:m,getSelectedCatalogItem:y}}function Aa(){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 Oe();t(a),s.current||(s.current=!0,x(w.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 $a(){return {items:q(t=>t.installedItems)}}var Hd=S("catalog");function La(){let e=g(N=>N.activeTab),t=g(N=>N.notification),r=g(N=>N.loading),n=g(N=>N.loadingMessage),o=g(N=>N.catalogError),i=g(N=>N.setCatalogError),s=g(N=>N.catalogFilters),c=le(N=>N.query),{catalog:a,isLoading:l,error:u,refetch:m}=Aa(),{items:y}=$a(),p=q(N=>N.loadFromDisk),{items:E,emptyMessage:f,getSelectedCatalogItem:C}=ka({catalog:a,installedItems:y,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:M,closeMenu:I,selectedIndex:R,clampIndex:L,filteredItems:V}=ra({listLength:E.length}),Y=V(E),$=useMemo(()=>e!=="installed"?Y:Ca(Y),[e,Y]),A=useMemo(()=>e==="installed"?Ta($):[],[e,$]),k=$[R]??null,h=useMemo(()=>C(k),[C,k]),{notify:Z}=oa(),{handleInstall:Q,handleUninstall:z,handleToggleStatus:$n,handleUpdate:Ln,handleMcpConfigUninstall:li}=Ia({selectedItem:k,selectedCatalogItem:h,items:E,closeMenu:I,clampIndex:L,notify:Z});return useEffect(()=>{p();},[]),useEffect(()=>{L($.length);},[$.length,L]),useEffect(()=>{u&&(Hd.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(Ot,{}),jsx(Qi,{}),jsx(Ss,{filteredItems:$,groups:A,emptyMessage:f}),(r||l)&&jsx(Xr,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Yr,{message:o,onRetry:()=>{i(null),m();},onBack:()=>i(null)}),t&&jsx(hs,{message:t.message,type:t.type}),M&&k&&(e==="discover"?jsx(As,{itemName:k.name,onInstall:Q,onClose:I}):k.type==="mcp"?jsx(Os,{itemName:k.name,itemScope:k.scope??"user",onUninstall:li,onClose:I}):jsx(Rs,{itemName:k.name,itemScope:k.scope??"user",itemStatus:k.status??"enabled",updateAvailable:k.updateAvailable??false,catalogVersion:h?.version,onUninstall:z,onToggleStatus:N=>$n(N),onUpdate:Ln,onClose:I})),jsx(qr,{})]})}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(q.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 Wd=3;function Ma(){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 nn();e(a);}catch(a){r(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,r,e]);useEffect(()=>{q.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 m="",y=false;for(let p=1;p<=Wd;p++)try{await ue(u.name),n(u.name,"success"),y=!0;break}catch(E){if(E instanceof ce){n(u.name,"success"),y=true;break}m=E instanceof Error?E.message:"Unknown error";}y||(n(u.name,"failed",m),x(w.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:m,interface:_().interfaceType}).catch(()=>{}));}let l=mt();pt("summary_review"),x(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),q.getState().loadFromDisk(),i(),o("summary");},[n,i,o]);return {loadStarterKits:s,installSelected:c}}var gr={cursorDelta:0,confirm:false,back:false};function _a(e,t){return t.upArrow?{...gr,cursorDelta:-1}:t.downArrow?{...gr,cursorDelta:1}:t.escape?{...gr,back:true}:t.return?{...gr,confirm:true}:gr}var qd={cursorDelta:0,select:false};function Oa(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:qd}var Da=fu.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:d(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:d(t.description)})})]})});var Ho=5;function Na({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(Xr,{message:"Loading Starter Kits..."});if(o)return jsx(Yr,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Dt,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor(Ho/2)),s=Math.min(t.length,i+Ho);s===t.length&&(i=Math.max(0,s-Ho));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,m)=>jsx(Da,{starterKit:u,isSelected:i+m===r},u.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var Ua=fu.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:[" ",d(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var zo=8;function Ba(){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,x(w.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(zo/2)),s=Math.min(t.length,i+zo);s===t.length&&(i=Math.max(0,s-zo));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:d(e.name)}),jsx(Text,{dimColor:true,children:d(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,m)=>jsx(Ua,{plugin:u,isCursor:i+m===r},u.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}var op=["Retry failed","Continue anyway"];function ja({name:e,status:t,error:r}){let n=d(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ru,{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 ",d(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function Ka({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(ja,{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(ja,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:op.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 Ja(){let e=P(h=>h.step),t=P(h=>h.starterKits),r=P(h=>h.selectedStarterKitIndex),n=P(h=>h.setSelectedStarterKitIndex),o=P(h=>h.selectStarterKit),i=P(h=>h.plugins),s=P(h=>h.pluginCursorIndex),c=P(h=>h.setPluginCursorIndex),a=P(h=>h.setStep),l=P(h=>h.summaryActionIndex),u=P(h=>h.setSummaryActionIndex),m=P(h=>h.failedCount),y=P(h=>h.resetForRetry),p=P(h=>h.goBackToList),E=g(h=>h.setScreen),f=g(h=>h.setFocus),C=g(h=>h.focus),M=Se(h=>h.setJustAuthenticated),I=Se(h=>h.justAuthenticated),{loadStarterKits:R,installSelected:L}=Ma(),V=useRef(false);useEffect(()=>{e==="bundleList"?(f("bundleList"),V.current||(V.current=true,pt("bundle_selection"))):f(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,f]);let Y=useCallback(async()=>{let h=P.getState().selectedStarterKit;if(h){let Q=await j();Q&&await ze({...Q,starterKit:h.slug});}x(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:mt()}).catch(()=>{});let{successCount:Z}=P.getState();x(w.CLI_ONBOARDING_COMPLETED,{duration_ms:Xe(),tools_installed_count:Z}).catch(()=>{}),M(false),f("list"),E("claudeMdSuggestion");},[M,f,E]),$=useCallback(()=>{y(),L();},[y,L]),A=useCallback(()=>{R();},[R]),k=useCallback(()=>{f("list"),E("claudeMdSuggestion");},[f,E]);return useInput((h,Z)=>{if(Z.escape)jr("esc"),k();else if(Z.upArrow&&r>0)n(r-1);else if(Z.downArrow&&r<t.length-1)n(r+1);else if(Z.return&&t.length>0){let Q=mt();o(t[r]),pt("kit_display"),x(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:Q}).catch(()=>{});}},{isActive:C==="bundleList"}),useInput((h,Z)=>{let Q=_a(h,Z);if(Q.cursorDelta!==0){let z=s+Q.cursorDelta;z>=0&&z<i.length&&c(z);}if(Q.confirm){let z=P.getState().selectedStarterKit;z&&(async()=>(await j())?.starterKit!==z.slug&&x(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let $n=mt();pt("kit_confirmation"),x(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:$n}).catch(()=>{});let Ln=mt();pt("tool_installation"),x(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Ln}).catch(()=>{}),a("installing"),L();}if(Q.back){let z=P.getState().selectedStarterKit;z&&x(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),p();}},{isActive:C==="bundleDetail"}),useInput((h,Z)=>{if(m===0)return;let Q=Oa(h,Z);if(Q.cursorDelta!==0){let z=l+Q.cursorDelta;z>=0&&z<=1&&u(z);}Q.select&&(l===0?$():Y());},{isActive:C==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ot,{}),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."}),!I&&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(Na,{onRetry:A}),e==="bundleDetail"&&jsx(Ba,{}),(e==="installing"||e==="summary")&&jsx(Ka,{onComplete:Y,onRetry:$})]}),jsx(qr,{})]})}var up=S("ClaudeMdSuggestion"),dp=[`Install ${ee}`,"Skip for now"],pp=["Retry","Skip for now"];function Va(){let e=g(y=>y.setScreen),t=g(y=>y.setFocus),r=P(y=>y.successCount),[n,o]=useState("prompt"),[i,s]=useState(0),c=useRef(0),a=useCallback(()=>{t("list"),e("main");},[t,e]),l=useCallback(()=>{x(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),a();},[a]),u=useCallback(async()=>{c.current+=1,x(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:c.current}).catch(()=>{}),o("installing");try{await ue(ee),o("installed");}catch(y){if(y instanceof ce){o("installed");return}up.warn(`Failed to install ${ee}: ${y instanceof Error?y.message:y}`),o("error");}},[]),m=n==="error"?pp:dp;return useInput((y,p)=>{if(p.escape){n==="prompt"||n==="error"?l():n==="installed"&&a();return}if(n==="prompt"||n==="error"){p.upArrow&&i>0?s(i-1):p.downArrow&&i<m.length-1?s(i+1):p.return&&(i===0?(s(0),u()):l());return}n==="installed"&&p.return&&a();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ot,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Ga,{options:m,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ru,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ee,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ee," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",ee]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ee]}),jsx(Ga,{options:m,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Ga({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var yp={debug:"gray",info:"cyan",warn:"yellow",error:"red"},za=10;function Wa(){let[e,t]=useState(Fn());useEffect(()=>hi(()=>{t([...Fn()]);}),[]);let r=e.slice(-za);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",za,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:yp[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var xp=S("app"),bp={auth:zi,bundleSetup:Ja,claudeMdSuggestion:Va,main:La};function Ya(){let{setScreen:e,setFocus:t}=g.getState();e("auth"),t("auth");}function Vr(e){let{setScreen:t,setFocus:r}=g.getState();!e.starterKit||e.starterKit.trim()===""?(t("bundleSetup"),r("bundleList")):(t("main"),r("list"));}function Za(){x(w.CLI_SESSION_STARTED,{cli_version:Ye,os:process.platform,node_version:process.version,duration_ms:Xe(),interface:"tui"}).catch(()=>{});}async function el(){let e=await j();if(e&&Vi()&&await We()){let{clientSecret:n,...o}=e;Se.getState().setCredentials(o),Za(),Vr(e);return}if(!e){Ya();return}try{await qe();}catch(n){xp.debug(`Token validation failed: ${String(n)}`),Ya();return}Za();let{clientSecret:t,...r}=e;Se.getState().setCredentials(r),Vr(e);}function tl(){let{columns:e,rows:t}=useWindowSize(),r=g(c=>c.screen),n=bp[r],{pendingExit:o}=ji(),i=g(c=>c.debugPanelOpen),s=!!process.env.DEBUG;return useInput((c,a)=>{if(s&&a.ctrl&&c==="d"){let l=g.getState().debugPanelOpen;g.getState().setDebugPanelOpen(!l);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),s&&i&&jsx(Wa,{}),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]})}async function ti(e,t={}){let r=Kr({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Jr(r),await ze(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var Ae=S("auth");function nl(){se.clearFallbackFile(),Dr();}var Ip=3,rl=3,ol=` \u2139 The data collected during setup is used solely to improve
116
116
  Flow's internal tools and will not be shared externally.
117
- `;function Dt(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===`
117
+ `;function Et(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===`
118
118
  `){a(),process.stdout.write(`
119
- `),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 Na(){for(let e=1;e<=_a;e++)try{return await zr()}catch{if(e===_a)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Fa(){let e=await Na();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
120
- `+E.cyan(" ? ")+`Starter Kit:
121
- `),e.forEach((t,r)=>{process.stdout.write(` ${E.cyan(`${r+1})`)} ${p(t.name)}
119
+ `),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 vp(){let e=ft();return process.stdout.write(`
120
+ `+b.yellow(" \u26A0 ")+`${d(e)} contains invalid JSON.
121
+ `),(await Et(b.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function il(e,t){try{await ti(e);return}catch(r){if(!(r instanceof gt))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${ft()} and retry.`);if(!await vp())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await ti(e,{allowOverwriteMalformed:true});}}async function sl(){for(let e=1;e<=rl;e++)try{return await nn()}catch{if(e===rl)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function al(){let e=await sl();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
122
+ `+b.cyan(" ? ")+`Starter Kit:
123
+ `),e.forEach((t,r)=>{process.stdout.write(` ${b.cyan(`${r+1})`)} ${d(t.name)}
122
124
  `);}),process.stdout.write(`
123
- `);;){let t=(await Dt(E.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(E.yellow(` \u26A0 Invalid selection. Please try again.
124
- `));}}async function Ua(e){if(e.plugins.length===0)return process.stdout.write(E.dim(`
125
- Starter kit '${p(e.name)}' has no plugins to install.
125
+ `);;){let t=(await Et(b.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(b.yellow(` \u26A0 Invalid selection. Please try again.
126
+ `));}}async function ll(e){if(e.plugins.length===0)return process.stdout.write(b.dim(`
127
+ Starter kit '${d(e.name)}' has no plugins to install.
126
128
  `)),true;process.stdout.write(`
127
- Installing ${e.plugins.length} plugins from '${p(e.name)}'...
128
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(E.dim(` [${i}/${n}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=Kp;c++)try{await oe(o),t++,s=!0;break}catch(a){if(a instanceof ne){t++,s=true;break}}s?process.stdout.write(E.green(` done
129
- `)):(r++,process.stdout.write(E.red(` failed
130
- `)));}return r===0?process.stdout.write(E.green(` \u2713 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed successfully.
131
- `)):process.stdout.write(E.yellow(` \u26A0 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
132
- `)),r===0}async function Ba(){process.stdout.write(`
133
- `),process.stdout.write(E.bold(` Personalize your Claude Code
134
- `)),process.stdout.write(E.dim(` This plugin helps Claude understand your preferences and work style.
129
+ Installing ${e.plugins.length} plugins from '${d(e.name)}'...
130
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(b.dim(` [${i}/${n}] Installing ${d(o)}...`));let s=false;for(let c=1;c<=Ip;c++)try{await ue(o),t++,s=!0;break}catch(a){if(a instanceof ce){t++,s=true;break}}s?process.stdout.write(b.green(` done
131
+ `)):(r++,process.stdout.write(b.red(` failed
132
+ `)));}return r===0?process.stdout.write(b.green(` \u2713 Starter kit '${d(e.name)}' selected. ${t}/${n} plugins installed successfully.
133
+ `)):process.stdout.write(b.yellow(` \u26A0 Starter kit '${d(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
134
+ `)),r===0}async function cl(){process.stdout.write(`
135
+ `),process.stdout.write(b.bold(` Personalize your Claude Code
136
+ `)),process.stdout.write(b.dim(` This plugin helps Claude understand your preferences and work style.
135
137
 
136
- `));let e=(await Dt(E.cyan(" ? ")+`Install ${z}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){I(x.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(E.dim(`
138
+ `));let e=(await Et(b.cyan(" ? ")+`Install ${ee}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){x(w.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(b.dim(`
137
139
  You can always install it later from the catalog.
138
- `));return}I(x.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(E.dim(` Installing ${z}...`));try{await oe(z),process.stdout.write(E.green(` done
139
- `));}catch(t){if(t instanceof ne)process.stdout.write(E.green(` already installed
140
- `));else {ve.warn(`Failed to install ${z}: ${t instanceof Error?t.message:t}`),process.stdout.write(E.red(` failed
141
- `)),process.stdout.write(E.dim(` You can install it later from the catalog.
140
+ `));return}x(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(b.dim(` Installing ${ee}...`));try{await ue(ee),process.stdout.write(b.green(` done
141
+ `));}catch(t){if(t instanceof ce)process.stdout.write(b.green(` already installed
142
+ `));else {Ae.warn(`Failed to install ${ee}: ${t instanceof Error?t.message:t}`),process.stdout.write(b.red(` failed
143
+ `)),process.stdout.write(b.dim(` You can install it later from the catalog.
142
144
  `));return}}process.stdout.write(`
143
145
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
144
- `),process.stdout.write(E.cyan.bold(` /${z}
146
+ `),process.stdout.write(b.cyan.bold(` /${ee}
145
147
  `)),process.stdout.write(` Claude will guide you through the rest.
146
- `);}async function jp(e){Oa(),process.stdout.write(`
147
- `+Da+`
148
- `),ve.debug(`[${e.tenant}] Authenticating tenant`);try{await at(e);}catch(t){let r=p(t instanceof Error?t.message:"unknown error");return ve.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(E.red(` \u2717 Authentication failed: ${r}
149
- `)),1}try{let t;if(e.starterKit){let r=await Na(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(E.red(` \u2717 Starter kit '${p(e.starterKit)}' not found.
148
+ `);}async function Pp(e){nl(),process.stdout.write(`
149
+ `+ol+`
150
+ `),Ae.debug(`[${e.tenant}] Authenticating tenant`);try{await dt(e);}catch(t){let r=d(t instanceof Error?t.message:"unknown error");return Ae.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(b.red(` \u2717 Authentication failed: ${r}
151
+ `)),1}try{let t;if(e.starterKit){let r=await sl(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(b.red(` \u2717 Starter kit '${d(e.starterKit)}' not found.
150
152
  `)),process.stderr.write(` Available starter kits:
151
- `);for(let o of r)process.stderr.write(` - ${p(o.slug)} (${p(o.name)})
152
- `);return 1}t=n;}else t=await Fa();return await st({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug}),await Ua(t),await Ba(),ve.info(`[${e.tenant}] Authentication successful`),process.stdout.write(E.green(`
153
- \u2713 Setup complete. Tenant: ${e.tenant}
153
+ `);for(let o of r)process.stderr.write(` - ${d(o.slug)} (${d(o.name)})
154
+ `);return 1}t=n;}else t=await al();return await il({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug},!1),await ll(t),await cl(),Ae.info(`[${e.tenant}] Authentication successful`),process.stdout.write(b.green(`
155
+ \u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${ft()}.
154
156
 
155
- `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=p(t instanceof Error?t.message:"unknown error");return ve.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(E.red(` \u2717 Starter kit setup failed: ${r}
156
- `)),1}}async function Gp(){Oa(),ve.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
157
- `),process.stdout.write(Da+`
158
- `);let e=(await Dt(E.cyan(" ? ")+"Client ID: ")).trim(),t=(await Dt(E.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await Dt(E.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return ve.error("[auth] Validation failed: all fields are required"),process.stderr.write(E.red(` \u2717 All fields are required
159
- `)),1;ve.debug(`[${r}] Authenticating tenant`);try{await at({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return ve.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(E.red(` \u2717 Authentication failed: ${i}
160
- `)),1}let n=await Fa();return await st({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug}),await Ua(n),await Ba(),ve.info(`[${r}] Authentication successful`),process.stdout.write(E.green(`
161
- \u2713 Setup complete. Tenant: ${r}
157
+ `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=d(t instanceof Error?t.message:"unknown error");return Ae.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(b.red(` \u2717 Starter kit setup failed: ${r}
158
+ `)),1}}async function Ep(){nl(),Ae.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
159
+ `),process.stdout.write(ol+`
160
+ `);let e=(await Et(b.cyan(" ? ")+"Client ID: ")).trim(),t=(await Et(b.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await Et(b.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return Ae.error("[auth] Validation failed: all fields are required"),process.stderr.write(b.red(` \u2717 All fields are required
161
+ `)),1;Ae.debug(`[${r}] Authenticating tenant`);try{await dt({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=d(o instanceof Error?o.message:"unknown error");return Ae.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(b.red(` \u2717 Authentication failed: ${i}
162
+ `)),1}let n=await al();return await il({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug},!0),await ll(n),await cl(),Ae.info(`[${r}] Authentication successful`),process.stdout.write(b.green(`
163
+ \u2713 Setup complete. Tenant: ${r}. JWT written to ${ft()}.
162
164
 
163
- `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return ve.error(`[auth] Unexpected error: ${t}`),process.stderr.write(E.red(` \u2717 Unexpected error: ${t}
164
- `)),1}}async function Bo(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return jp({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await Gp()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
165
- `),130;throw t}}async function Hp(){try{return process.stdout.write(`
166
- `),(await Dt(E.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(E.yellow(` \u26A0 Logout cancelled
165
+ `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=d(e instanceof Error?e.message:"unknown error");return Ae.error(`[auth] Unexpected error: ${t}`),process.stderr.write(b.red(` \u2717 Unexpected error: ${t}
166
+ `)),1}}async function ri(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return Pp({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await Ep()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
167
+ `),130;throw t}}async function Tp(){try{return process.stdout.write(`
168
+ `),(await Et(b.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(b.yellow(` \u26A0 Logout cancelled
167
169
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
168
- `),130;throw e}}async function Ka(e){if(!await N())return process.stdout.write(E.yellow(` \u26A0 You are not authenticated
169
- `)),0;if(!e){let t=await Hp();if(t!==null)return t}try{return await ui(),process.stdout.write(E.green(` \u2713 Credentials removed successfully
170
- `)),0}catch{return process.stderr.write(E.red(` \u2717 Error removing credentials
171
- `)),1}}async function ja(){let e=await N();return e?await Et()?(process.stdout.write(`
172
- `+E.bold(` Authenticated
173
- `)),process.stdout.write(E.dim(" Tenant: ")+p(e.tenant)+`
174
- `),process.stdout.write(E.dim(" Client ID: ")+p(e.clientId)+`
175
- `),process.stdout.write(E.dim(" Starter Kit: ")+p(e.starterKit??"not set")+`
176
- `),process.stdout.write(E.dim(" Config: ")+p(await pi())+`
170
+ `),130;throw e}}async function ul(e){if(!await j())return process.stdout.write(b.yellow(` \u26A0 You are not authenticated
171
+ `)),0;if(!e){let t=await Tp();if(t!==null)return t}try{return await Ti(),process.stdout.write(b.green(` \u2713 Credentials removed successfully
172
+ `)),0}catch{return process.stderr.write(b.red(` \u2717 Error removing credentials
173
+ `)),1}}async function dl(){let e=await j();return e?await We()?(process.stdout.write(`
174
+ `+b.bold(` Authenticated
175
+ `)),process.stdout.write(b.dim(" Tenant: ")+d(e.tenant)+`
176
+ `),process.stdout.write(b.dim(" Client ID: ")+d(e.clientId)+`
177
+ `),process.stdout.write(b.dim(" Starter Kit: ")+d(e.starterKit??"not set")+`
178
+ `),process.stdout.write(b.dim(" Config: ")+d(await Ci())+`
177
179
  `),process.stdout.write(`
178
- `),0):(process.stdout.write(E.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(E.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function Jp(e){let t=Le(),r;try{r=await $e();}catch{r=[];}let n=new Set(t.map(o=>o.name));return I(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(Ct(r.map(o=>({...o,installed:n.has(o.name)}))),0):(_r(["","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 Vp(e){let t=Le(),r=await $e(),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&&Ne(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return I(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(P("All plugins are up to date."),0):e.json?(Ct(o),0):(_r(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
180
+ `),0):(process.stdout.write(b.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(b.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function Cp(e){let t=De(),r;try{r=await Oe();}catch{r=[];}let n=new Set(t.map(o=>o.name));return x(w.CLI_CATALOG_VIEWED,{interface:_().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(_t(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Hr(["","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 kp(e){let t=De(),r=await Oe(),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&&je(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return x(w.CLI_CATALOG_VIEWED,{interface:_().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(v("All plugins are up to date."),0):e.json?(_t(o),0):(Hr(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
179
181
  ${o.length} plugin(s) outdated.
180
- `),0)}async function zp(e){let t=Le();if(I(x.CLI_CATALOG_VIEWED,{interface:$().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return P("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return Ct(t),0;let r=[];try{r=await $e();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=cr.indexOf(i.scope??"user"),a=cr.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return _r(["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",xt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",Or(i.installedAt??"")]})),process.stdout.write(`
182
+ `),0)}async function Ap(e){let t=De();if(x(w.CLI_CATALOG_VIEWED,{interface:_().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return v("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return _t(t),0;let r=[];try{r=await Oe();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=mr.indexOf(i.scope??"user"),a=mr.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return Hr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=n.get(i.name),c=s?.type??"plugin",a=s?.origin??No(i.marketplace);return [i.name??"",i.version??"n/a",kt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",Gr(i.installedAt??"")]})),process.stdout.write(`
181
183
  ${t.length} plugin(s) installed.
182
- `),0}async function Ga(e){if(!await se())return 1;try{return e.available?await Jp(e):e.outdated?await Vp(e):await zp(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var _=S("manage");function un(e,t){return t?Le().find(r=>r.name===e&&r.scope===t):Le().find(r=>r.name===e)}function Wp(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,P(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Ko({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function qp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=p(e),c=p(xo(e,r.scope));if(!await Ye(`${t}Install external plugin "${s}"?
184
+ `),0}async function pl(e){if(!await pe())return 1;try{return e.available?await Cp(e):e.outdated?await kp(e):await Ap(e)}catch(t){return T(t instanceof Error?t.message:"Failed to list plugins."),1}}var F=S("manage");function bn(e,t){return t?De().find(r=>r.name===e&&r.scope===t):De().find(r=>r.name===e)}function $p(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,v(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=ni({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Lp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=d(e),c=d(_o(e,r.scope));if(!await rt(`${t}Install external plugin "${s}"?
183
185
  This will run: ${c}
184
- [y/N] `))return _.debug(`[${e}] Installation cancelled by user`),r.silent||P(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Ko({text:`${t}Installing ${e}...`}).start());}let i=o?Wp(t,o):void 0;try{let s=await Io(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?de({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?te({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):W(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=F(s);return r.silent?de({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function Xp(e,t,r){let n=r.silent?void 0:Ko({text:`${t}Installing ${e}...`}).start();if(sr(e))return qp(e,t,r,n);try{let o=await oe(e,r);return n?.stop(),r.silent?te({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):W(`${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 ne)return r.silent?te({status:"already_installed",plugin:e,message:o.message}):P(`${t}${o.message}`),{name:e,success:true};let i=F(o);return r.silent?de({status:"error",plugin:e,message:i}):k(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function Yp(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;P(`
185
- Installation summary: ${t} succeeded, ${r} failed`);}async function Ha(e,t={}){if(!await se())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await Xp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?te({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}:{}}))}):Yp(r)),r.some(n=>!n.success)?1:0}async function Ja(e,t){if(!await se())return 1;if(_.debug(`[${e}] Looking up installed plugin`),!t.force){let r=un(e,t.scope);if(!r)return _.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 Ye(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return _.debug(`[${e}] Uninstall cancelled by user`),P("Operation cancelled."),0}try{return _.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await qr(e,t.scope),_.info(`[${e}] Uninstalled successfully`),W("Plugin removed successfully"),0}catch(r){return _.error(`[${e}] Failed to uninstall: ${F(r)}`),k(F(r)),1}}async function Va(e,t={}){if(!await se())return 1;_.debug(`[${e}] Looking up installed plugin`);let r=un(e,t.scope);if(!r)return _.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return _.debug(`[${e}] Already enabled, skipping`),P(`${r.name} is already enabled`),0;try{return _.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await ir(e,"enabled",t.scope),_.info(`[${e}] Enabled successfully`),W(`${r.name} enabled successfully`),0}catch(n){return _.error(`[${e}] Failed to enable: ${F(n)}`),k(F(n)),1}}async function za(e,t={}){if(!await se())return 1;_.debug(`[${e}] Looking up installed plugin`);let r=un(e,t.scope);if(!r)return _.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return _.debug(`[${e}] Already disabled, skipping`),P(`${r.name} is already disabled`),0;try{return _.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await ir(e,"disabled",t.scope),_.info(`[${e}] Disabled successfully`),W(`${r.name} disabled successfully`),0}catch(n){return _.error(`[${e}] Failed to disable: ${F(n)}`),k(F(n)),1}}async function Wa(e,t,r){r.silent||P(`${t}Updating ${e}...`);try{let n=await Zr(e,r);return r.silent?te({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):W(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof qe)return r.silent?te({status:"up_to_date",plugin:e,message:n.message}):P(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=F(n);return r.silent?de({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Zp(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;P(`
186
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Qp(e,t,r){try{let n=await Rt(e);Ne(t,n.version,r.force)?P(`Would update ${e}: v${t} \u2192 v${n.version}`):P(`${e} is already up to date (v${t})`);}catch(n){return k(F(n)),1}return 0}function ed(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function td(e,t,r){let n=t.get(e.name);return n?e.version&&Ne(e.version,n,r)?(P(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(P(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(P(`Skipping ${e.name}: not found in catalog`),false)}async function rd(e,t){try{let r=await $e(),n=ed(r),o=0;for(let i of e)td(i,n,t.force)&&o++;o===0&&P("All plugins are up to date");}catch(r){return k(F(r)),1}return 0}async function nd(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await Wa(e[n].name,o,t);r.push(i);}return t.silent?te({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}:{}}))}):Zp(r),r.some(n=>!n.success)?1:0}async function qa(e,t={}){if(!await se())return 1;if(e){let o=un(e,t.scope);return o?t.dryRun?Qp(e,o.version??"",t):(await Wa(e,"",t)).success?0:1:(t.silent?de({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let n=Le().filter(o=>o.marketplace===D);return n.length===0?(t.silent?te({status:"empty",message:"No plugins installed"}):P("No plugins installed"),0):t.dryRun?rd(n,t):nd(n,t)}var Xa=S("marketplace");function id(e){return `claude plugin marketplace add ${e}`}async function Ya(e,t){if(!await se())return 1;let r;try{r=Qr(e);}catch(i){let s=F(i);return t.silent?de({status:"error",source:e,message:s}):k(s),1}Xa.debug(`[marketplace] Adding marketplace source: ${r}`);let n=id(r);if(!t.force){let i=p(r),s=p(n);if(!await Ye(`Add marketplace "${i}"?
186
+ [y/N] `))return F.debug(`[${e}] Installation cancelled by user`),r.silent||v(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=ni({text:`${t}Installing ${e}...`}).start());}let i=o?$p(t,o):void 0;try{let s=await Oo(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?he({status:"error",plugin:e,message:c}):T(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?ae({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):te(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=K(s);return r.silent?he({status:"error",plugin:e,message:c}):T(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function Rp(e,t,r){let n=r.silent?void 0:ni({text:`${t}Installing ${e}...`}).start();if(ur(e))return Lp(e,t,r,n);try{let o=await ue(e,r);return n?.stop(),r.silent?ae({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):te(`${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 ce)return r.silent?ae({status:"already_installed",plugin:e,message:o.message}):v(`${t}${o.message}`),{name:e,success:true};let i=K(o);return r.silent?he({status:"error",plugin:e,message:i}):T(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function Mp(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;v(`
187
+ Installation summary: ${t} succeeded, ${r} failed`);}async function ml(e,t={}){if(!await pe())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await Rp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?ae({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}:{}}))}):Mp(r)),r.some(n=>!n.success)?1:0}async function fl(e,t){if(!await pe())return 1;if(F.debug(`[${e}] Looking up installed plugin`),!t.force){let r=bn(e,t.scope);if(!r)return F.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;let n=d(r.name),o=r.version?d(r.version):void 0,i=t.scope?` (${t.scope})`:"";if(!await rt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return F.debug(`[${e}] Uninstall cancelled by user`),v("Operation cancelled."),0}try{return F.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await sn(e,t.scope),F.info(`[${e}] Uninstalled successfully`),te("Plugin removed successfully"),0}catch(r){return F.error(`[${e}] Failed to uninstall: ${K(r)}`),T(K(r)),1}}async function gl(e,t={}){if(!await pe())return 1;F.debug(`[${e}] Looking up installed plugin`);let r=bn(e,t.scope);if(!r)return F.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return F.debug(`[${e}] Already enabled, skipping`),v(`${r.name} is already enabled`),0;try{return F.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await cr(e,"enabled",t.scope),F.info(`[${e}] Enabled successfully`),te(`${r.name} enabled successfully`),0}catch(n){return F.error(`[${e}] Failed to enable: ${K(n)}`),T(K(n)),1}}async function yl(e,t={}){if(!await pe())return 1;F.debug(`[${e}] Looking up installed plugin`);let r=bn(e,t.scope);if(!r)return F.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return F.debug(`[${e}] Already disabled, skipping`),v(`${r.name} is already disabled`),0;try{return F.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await cr(e,"disabled",t.scope),F.info(`[${e}] Disabled successfully`),te(`${r.name} disabled successfully`),0}catch(n){return F.error(`[${e}] Failed to disable: ${K(n)}`),T(K(n)),1}}async function Sl(e,t,r){r.silent||v(`${t}Updating ${e}...`);try{let n=await cn(e,r);return r.silent?ae({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):te(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof et)return r.silent?ae({status:"up_to_date",plugin:e,message:n.message}):v(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=K(n);return r.silent?he({status:"error",plugin:e,message:o}):T(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function _p(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;v(`
188
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Op(e,t,r){try{let n=await Ft(e);je(t,n.version,r.force)?v(`Would update ${e}: v${t} \u2192 v${n.version}`):v(`${e} is already up to date (v${t})`);}catch(n){return T(K(n)),1}return 0}function Dp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Np(e,t,r){let n=t.get(e.name);return n?e.version&&je(e.version,n,r)?(v(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(v(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(v(`Skipping ${e.name}: not found in catalog`),false)}async function Fp(e,t){try{let r=await Oe(),n=Dp(r),o=0;for(let i of e)Np(i,n,t.force)&&o++;o===0&&v("All plugins are up to date");}catch(r){return T(K(r)),1}return 0}async function Up(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await Sl(e[n].name,o,t);r.push(i);}return t.silent?ae({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}:{}}))}):_p(r),r.some(n=>!n.success)?1:0}async function hl(e,t={}){if(!await pe())return 1;if(e){let o=bn(e,t.scope);return o?t.dryRun?Op(e,o.version??"",t):(await Sl(e,"",t)).success?0:1:(t.silent?he({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):T(`Plugin "${e}" is not installed`),1)}let n=De().filter(o=>o.marketplace===B);return n.length===0?(t.silent?ae({status:"empty",message:"No plugins installed"}):v("No plugins installed"),0):t.dryRun?Fp(n,t):Up(n,t)}var wl=S("marketplace");function jp(e){return `claude plugin marketplace add ${e}`}async function xl(e,t){if(!await pe())return 1;let r;try{r=un(e);}catch(i){let s=K(i);return t.silent?he({status:"error",source:e,message:s}):T(s),1}wl.debug(`[marketplace] Adding marketplace source: ${r}`);let n=jp(r);if(!t.force){let i=d(r),s=d(n);if(!await rt(`Add marketplace "${i}"?
187
189
  This will run: ${s}
188
- [y/N] `))return Xa.debug("[marketplace] Operation cancelled by user"),P("Operation cancelled."),0}let o=t.silent?void 0:Ko({text:`Adding marketplace "${p(r)}"...`}).start();try{let i=await ge(n);return o?.stop(),i.exitCode!==0?(t.silent?de({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&&P(`stdout: ${i.stdout}`)),1):(t.silent?te({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(W(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&P(i.stdout)),0)}catch(i){o?.stop();let s=F(i);return t.silent?de({status:"error",source:r,message:s}):k(`Failed to add marketplace "${r}": ${s}`),1}}async function cd(){return await N()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function ud(){let e=Date.now();try{await $e();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 pd(){return await Et()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function dd(){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 Za(){process.stdout.write(`
189
- `+E.bold(` FlowSetup CLI Diagnostics
190
+ [y/N] `))return wl.debug("[marketplace] Operation cancelled by user"),v("Operation cancelled."),0}let o=t.silent?void 0:ni({text:`Adding marketplace "${d(r)}"...`}).start();try{let i=await be(n);return o?.stop(),i.exitCode!==0?(t.silent?he({status:"error",source:r,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(T(`Failed to add marketplace "${r}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&v(`stdout: ${i.stdout}`)),1):(t.silent?ae({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(te(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&v(i.stdout)),0)}catch(i){o?.stop();let s=K(i);return t.silent?he({status:"error",source:r,message:s}):T(`Failed to add marketplace "${r}": ${s}`),1}}async function Gp(){return await j()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Vp(){let e=Date.now();try{await Oe();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 zp(){return await We()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Wp(){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 bl(){process.stdout.write(`
191
+ `+b.bold(` FlowSetup CLI Diagnostics
190
192
 
191
- `));let e=[{name:"Credentials",fn:cd},{name:"Prompt Manager",fn:ud},{name:"Valid Token",fn:pd},{name:"Claude Code",fn:dd}],t=true;for(let r of e){let n=await r.fn(),o="",i=E.green;n.passed?o=E.green("[OK] "):(o=E.red("[FAIL]"),i=E.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${p(n.message)}`;process.stdout.write(s+`
193
+ `));let e=[{name:"Credentials",fn:Gp},{name:"Prompt Manager",fn:Vp},{name:"Valid Token",fn:zp},{name:"Claude Code",fn:Wp}],t=true;for(let r of e){let n=await r.fn(),o="",i=b.green;n.passed?o=b.green("[OK] "):(o=b.red("[FAIL]"),i=b.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${d(n.message)}`;process.stdout.write(s+`
192
194
  `);}return process.stdout.write(`
193
- `),t?(process.stdout.write(E.green(` \u2713 All checks passed!
195
+ `),t?(process.stdout.write(b.green(` \u2713 All checks passed!
194
196
 
195
- `)),0):(process.stdout.write(E.red(` \u2717 Some checks failed \u2014 verify your configuration
197
+ `)),0):(process.stdout.write(b.red(` \u2717 Some checks failed \u2014 verify your configuration
196
198
 
197
- `)),1)}var gd=["github.com","www.github.com"],yd=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Sd=/^([^@]+)@(.+)$/;function hd(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function jo(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 wd(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=jo(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=jo(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function pn(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(hd(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:")&&gd.includes(r.hostname))return wd(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(yd);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(Sd);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 h=a.replace(/^\//,"");h&&(g.subpath=jo(h));}return g}}return {type:"git",url:t}}function dn(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 vd=6e4,tt=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 mn(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:vd}}).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 tt("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new tt(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new tt(`Failed to clone ${e}: ${s}`,e,false,false)}}async function fn(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 nl(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 Ho=new Set(["node_modules",".git","dist","build","__pycache__"]);function Nt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function sl(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Ad(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Go(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function fr(e){try{let t=await readFile(e,"utf-8"),{data:r}=nl(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 al(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Go(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!Ho.has(c.name)).map(c=>al(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function Sn(e,t){let r=[],n=new Set;if(t&&!Ad(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Go(o)){let s=await fr(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 Go(l)){let u=await fr(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await al(o);for(let c of s){let a=await fr(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function ll(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 ul=1;function cl(){return {version:ul,skills:{}}}async function hn(e){let t=Tn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<ul?cl():n}catch{return cl()}}function _d(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function pl(e,t){let r=Tn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:_d(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
198
- `,"utf-8");}async function dl(e,t,r){let n=await hn(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await pl(n,r);}async function ml(e,t){let r=await hn(t);e in r.skills&&(delete r.skills[e],await pl(r,t));}var fl=S("skillInstaller");async function Kd(e,t,r,n){try{await I(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:$().interfaceType});}catch(o){fl.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function jd(e,t){try{await I(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){fl.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function Gd(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Ho.has(basename(r))});}async function Hd(e,t,r){let n=Nt(e.name),o=Ht(t),i=join(o,n);if(!sl(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 Gd(e.path,i);let c=dn(r)??r.url;return await dl(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 gl(e,t){let r=pn(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 mn(r.url,r.ref),o=n;let i=await Sn(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?ll(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let g=Date.now(),h=await Hd(u,t.scope,r);a.push(h);let d=Date.now()-g;h.success?await Kd(u.name,t.scope,l,d):await jd(u.name,new Error(h.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 fn(n).catch(()=>{});}}var qd=S("skills");async function Xd(e){try{await I(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:$().interfaceType});}catch(t){qd.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function Yd(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 Zd(e){let t=pn(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;n=t.localPath;}else P(`Fetching skills from ${p(e)}...`),r=await mn(t.url,t.ref),n=r;let o=await Sn(n,t.subpath);if(o.length===0)return P("No skills found in this source."),0;let s=dn(t)??p(e);P(`Found ${o.length} skill(s) in ${s}:
199
- `);for(let c of o){let a=p(c.name),l=p(c.description);process.stdout.write(` ${E.bold(a)} ${E.dim(l)}
199
+ `)),1)}var Yp=["github.com","www.github.com"],Zp=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Qp=/^([^@]+)@(.+)$/;function em(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function oi(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 tm(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=oi(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=oi(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function In(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(em(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:")&&Yp.includes(r.hostname))return tm(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(Zp);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(Qp);u&&(c=u[1],l=u[2]),c.endsWith(".git")&&(c=c.slice(0,-4));let m={type:"github",url:`https://github.com/${s}/${c}.git`};if(n&&(m.ref=n),l&&(m.skillFilter=l),a){let y=a.replace(/^\//,"");y&&(m.subpath=oi(y));}return m}}return {type:"git",url:t}}function vn(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 sm=6e4,st=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 Pn(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:sm}}).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 st("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new st(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new st(`Failed to clone ${e}: ${s}`,e,false,false)}}async function En(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 Tl(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 si=new Set(["node_modules",".git","dist","build","__pycache__"]);function Kt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Al(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function dm(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function ii(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function hr(e){try{let t=await readFile(e,"utf-8"),{data:r}=Tl(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 $l(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([ii(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!si.has(c.name)).map(c=>$l(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function kn(e,t){let r=[],n=new Set;if(t&&!dm(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await ii(o)){let s=await hr(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 ii(l)){let u=await hr(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await $l(o);for(let c of s){let a=await hr(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function Ll(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 Ml=1;function Rl(){return {version:Ml,skills:{}}}async function An(e){let t=Dn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Ml?Rl():n}catch{return Rl()}}function ym(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function _l(e,t){let r=Dn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:ym(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
200
+ `,"utf-8");}async function Ol(e,t,r){let n=await An(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await _l(n,r);}async function Dl(e,t){let r=await An(t);e in r.skills&&(delete r.skills[e],await _l(r,t));}var Nl=S("skillInstaller");async function vm(e,t,r,n){try{await x(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:_().interfaceType});}catch(o){Nl.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function Pm(e,t){try{await x(w.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){Nl.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function Em(e,t){await cp(e,t,{recursive:true,dereference:true,filter:r=>!si.has(basename(r))});}async function Tm(e,t,r){let n=Kt(e.name),o=Wt(t),i=join(o,n);if(!Al(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 Em(e.path,i);let c=vn(r)??r.url;return await Ol(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 Fl(e,t){let r=In(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 Pn(r.url,r.ref),o=n;let i=await kn(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?Ll(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let m=Date.now(),y=await Tm(u,t.scope,r);a.push(y);let p=Date.now()-m;y.success?await vm(u.name,t.scope,l,p):await Pm(u.name,new Error(y.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 En(n).catch(()=>{});}}var Lm=S("skills");async function Rm(e){try{await x(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:_().interfaceType});}catch(t){Lm.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function Mm(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 _m(e){let t=In(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return T("Invalid local path."),1;n=t.localPath;}else v(`Fetching skills from ${d(e)}...`),r=await Pn(t.url,t.ref),n=r;let o=await kn(n,t.subpath);if(o.length===0)return v("No skills found in this source."),0;let s=vn(t)??d(e);v(`Found ${o.length} skill(s) in ${s}:
201
+ `);for(let c of o){let a=d(c.name),l=d(c.description);process.stdout.write(` ${b.bold(a)} ${b.dim(l)}
200
202
  `);}return process.stdout.write(`
201
- `),0}catch(n){return n instanceof tt?k(n.message):k(n instanceof Error?n.message:String(n)),1}finally{r&&await fn(r).catch(()=>{});}}function Qd(e){for(let r of e.results){let n=p(r.skill);if(r.success){let o=relative(process.cwd(),r.path);W(`${n} installed ${E.dim(`\u2192 ${o}/`)}`);}else k(`${n}: ${p(r.error??"unknown error")}`);}process.stdout.write(`
202
- `);let t=e.source;e.installed>0&&P(`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?P("No skills found in this source."):e.results.length===0&&e.discovered>0&&P(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Sl(e,t){if(t.list)return Zd(e);let r=t.global?"global":"project";try{let n=await gl(e,{scope:r,skillFilter:t.skill,yes:t.yes});return Qd(n),n.failed>0?1:0}catch(n){return n instanceof tt?k(n.message):k(n instanceof Error?n.message:String(n)),1}}async function hl(e){let t=Ht(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 fr(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 wl(e){let t=e.global?"global":"project",r=await hl(t),n=await hn(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[Nt(s.name)]?.source}));return Ct(i),0}if(r.length===0)return P(`No skills installed (${t==="global"?"global":"project"} scope).`),0;P(`${t==="global"?"Global":"Project"} skills (${r.length}):
203
- `);for(let i of r){let s=n.skills[Nt(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?E.dim(` (${s})`):"";process.stdout.write(` ${E.bold(c)}${u}
204
- `),process.stdout.write(` ${E.dim(l)}
203
+ `),0}catch(n){return n instanceof st?T(n.message):T(n instanceof Error?n.message:String(n)),1}finally{r&&await En(r).catch(()=>{});}}function Om(e){for(let r of e.results){let n=d(r.skill);if(r.success){let o=relative(process.cwd(),r.path);te(`${n} installed ${b.dim(`\u2192 ${o}/`)}`);}else T(`${n}: ${d(r.error??"unknown error")}`);}process.stdout.write(`
204
+ `);let t=e.source;e.installed>0&&v(`Installed ${e.installed} of ${e.discovered} skill(s) from ${d(t)}`),e.failed>0&&T(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?v("No skills found in this source."):e.results.length===0&&e.discovered>0&&v(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Bl(e,t){if(t.list)return _m(e);let r=t.global?"global":"project";try{let n=await Fl(e,{scope:r,skillFilter:t.skill,yes:t.yes});return Om(n),n.failed>0?1:0}catch(n){return n instanceof st?T(n.message):T(n instanceof Error?n.message:String(n)),1}}async function jl(e){let t=Wt(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 hr(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 Kl(e){let t=e.global?"global":"project",r=await jl(t),n=await An(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[Kt(s.name)]?.source}));return _t(i),0}if(r.length===0)return v(`No skills installed (${t==="global"?"global":"project"} scope).`),0;v(`${t==="global"?"Global":"Project"} skills (${r.length}):
205
+ `);for(let i of r){let s=n.skills[Kt(i.name)]?.source,c=d(i.name),a=d(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?b.dim(` (${s})`):"";process.stdout.write(` ${b.bold(c)}${u}
206
+ `),process.stdout.write(` ${b.dim(l)}
205
207
 
206
- `);}return 0}async function xl(e,t){let r=t.global?"global":"project";if(!e){let s=await hl(r);if(s.length===0)return P("No skills installed."),0;P("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
208
+ `);}return 0}async function Jl(e,t){let r=t.global?"global":"project";if(!e){let s=await jl(r);if(s.length===0)return v("No skills installed."),0;v("Installed skills:");for(let c of s)process.stdout.write(` - ${d(c.name)}
207
209
  `);return process.stdout.write(`
208
- `),P("Specify a skill name to remove: flow skills remove <name>"),1}let n=Nt(e),o=Ht(r),i=join(o,n);try{await stat(i);}catch{return k(`Skill "${p(e)}" is not installed.`),1}if(!t.force&&!await Yd(`Remove skill "${p(n)}"?`))return P("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await ml(n,r),await Xd(n),W(`Skill "${p(n)}" removed.`),0}catch(s){return k(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function O(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}function Il(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Je}`,"-V, --version","Display the CLI version").addHelpText("after",`
210
+ `),v("Specify a skill name to remove: flow skills remove <name>"),1}let n=Kt(e),o=Wt(r),i=join(o,n);try{await stat(i);}catch{return T(`Skill "${d(e)}" is not installed.`),1}if(!t.force&&!await Mm(`Remove skill "${d(n)}"?`))return v("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await Dl(n,r),await Rm(n),te(`Skill "${d(n)}" removed.`),0}catch(s){return T(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function U(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}function Hl(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Ye}`,"-V, --version","Display the CLI version").addHelpText("after",`
209
211
  Without arguments, opens the interactive interface (TUI).
210
212
  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",`
211
213
  Examples:
212
- $ flow setup init`).action(async()=>{let a=await Bo();O(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",`
214
+ $ flow setup init`).action(async()=>{let a=await ri();U(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",`
213
215
  Examples:
214
216
  $ flow plugin list
215
217
  $ flow plugin list --available
216
218
  $ flow plugin list --outdated
217
- $ flow plugin list --json`).action(async a=>{let l=await Ga(a);O(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",`
219
+ $ flow plugin list --json`).action(async a=>{let l=await pl(a);U(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",`
218
220
  Examples:
219
221
  $ flow plugin install flow-adr-writer
220
222
  $ flow plugin install flow-adr-writer --scope project
@@ -222,11 +224,11 @@ Examples:
222
224
  $ flow plugin install flow-adr-writer --force
223
225
  $ flow plugin install flow-adr-writer --silent
224
226
  $ flow plugin install superpowers@claude-plugins-official
225
- $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(h=>h.trim());if(u.length===0){k("No valid plugin names provided"),O(1);return}pe("cli",{verbose:l.verbose,silent:l.silent});let g=await Ha(u,l);O(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",`
227
+ $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(y=>y.trim());if(u.length===0){T("No valid plugin names provided"),U(1);return}ye("cli",{verbose:l.verbose,silent:l.silent});let m=await ml(u,l);U(m);}),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",`
226
228
  Examples:
227
229
  $ flow plugin uninstall flow-adr-writer
228
230
  $ flow plugin uninstall flow-adr-writer --scope project
229
- $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await Ja(a,l);O(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",`
231
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await fl(a,l);U(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",`
230
232
  Examples:
231
233
  $ flow plugin update flow-adr-writer
232
234
  $ flow plugin update flow-adr-writer --scope project
@@ -235,49 +237,49 @@ Examples:
235
237
  $ flow plugin update flow-adr-writer --verbose
236
238
  $ flow plugin update flow-adr-writer --silent
237
239
  $ flow plugin update
238
- $ flow plugin update --dry-run`).action(async(a,l)=>{pe("cli",{verbose:l.verbose,silent:l.silent});let u=await qa(a??null,l);O(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",`
240
+ $ flow plugin update --dry-run`).action(async(a,l)=>{ye("cli",{verbose:l.verbose,silent:l.silent});let u=await hl(a??null,l);U(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",`
239
241
  Examples:
240
242
  $ flow plugin enable flow-adr-writer
241
- $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{pe("cli");let u=await Va(a,l);O(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",`
243
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{ye("cli");let u=await gl(a,l);U(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",`
242
244
  Examples:
243
245
  $ flow plugin disable flow-adr-writer
244
- $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{pe("cli");let u=await za(a,l);O(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",`
246
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{ye("cli");let u=await yl(a,l);U(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",`
245
247
  Examples:
246
248
  $ flow plugin marketplace add anthropics/claude-code
247
249
  $ flow plugin marketplace add https://github.com/owner/repo
248
250
  $ flow plugin marketplace add anthropics/claude-code --force
249
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{pe("cli",{verbose:l.verbose,silent:l.silent});let u=await Ya(a,l);O(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",`
251
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{ye("cli",{verbose:l.verbose,silent:l.silent});let u=await xl(a,l);U(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",`
250
252
  Examples:
251
253
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
252
254
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
253
255
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
254
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{pe("cli",{verbose:u.verbose,silent:u.silent});let g=await ta(a,l,u);O(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",`
256
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{ye("cli",{verbose:u.verbose,silent:u.silent});let m=await xa(a,l,u);U(m);}),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",`
255
257
  Examples:
256
258
  $ flow mcp remove notion
257
259
  $ flow mcp remove notion --scope project
258
- $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{pe("cli",{verbose:l.verbose,silent:l.silent});let u=await ra(a,l);O(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",`
260
+ $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{ye("cli",{verbose:l.verbose,silent:l.silent});let u=await ba(a,l);U(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",`
259
261
  Examples:
260
262
  $ flow auth login
261
263
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
262
264
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
263
- $ flow auth login --verbose`).action(async a=>{pe("cli",{verbose:a.verbose});let l=await Bo(a);O(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
265
+ $ flow auth login --verbose`).action(async a=>{ye("cli",{verbose:a.verbose});let l=await ri(a);U(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
264
266
  Examples:
265
267
  $ flow auth logout
266
- $ flow auth logout --force`).action(async a=>{let l=await Ka(a.force);O(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
268
+ $ flow auth logout --force`).action(async a=>{let l=await ul(a.force);U(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
267
269
  Examples:
268
- $ flow auth status`).action(async()=>{let a=await ja();O(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",`
270
+ $ flow auth status`).action(async()=>{let a=await dl();U(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",`
269
271
  Examples:
270
272
  $ flow skills add vercel-labs/agent-skills
271
273
  $ flow skills add owner/repo -g
272
274
  $ flow skills add owner/repo --skill pr-review commit
273
275
  $ flow skills add ./local/skills -y
274
- $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await Sl(a,l);O(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
276
+ $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await Bl(a,l);U(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
275
277
  Examples:
276
278
  $ flow skills list
277
279
  $ flow skills list -g
278
- $ flow skills list --json`).action(async a=>{let l=await wl(a);O(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",`
280
+ $ flow skills list --json`).action(async a=>{let l=await Kl(a);U(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",`
279
281
  Examples:
280
282
  $ flow skills remove pr-review
281
- $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await xl(a,l);O(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
283
+ $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await Jl(a,l);U(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
282
284
  Examples:
283
- $ flow health`).action(async()=>{let a=await Za();O(a);}),t}var tm=Il(async()=>{pe("tui"),xi("tui"),Ii(),process.on("SIGINT",()=>{zt("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{zt("sigterm").finally(()=>process.exit(143));}),await Ra(),render(jsx(Ma,{}),{alternateScreen:true,exitOnCtrlC:false});});tm.parse();
285
+ $ flow health`).action(async()=>{let a=await bl();U(a);}),t}var Nm=Hl(async()=>{ye("tui"),Di("tui"),Ni(),process.on("SIGINT",()=>{Yt("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Yt("sigterm").finally(()=>process.exit(143));}),await el(),render(jsx(tl,{}),{alternateScreen:true,exitOnCtrlC:false});});Nm.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciandt-flow/cli",
3
- "version": "1.6.2",
3
+ "version": "1.7.0-beta.213",
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",
@@ -63,6 +63,7 @@
63
63
  "ink-big-text": "2.0.0",
64
64
  "ink-gradient": "4.0.0",
65
65
  "ink-spinner": "5.0.0",
66
+ "jsonwebtoken": "^9.0.3",
66
67
  "ky": "2.0.2",
67
68
  "proper-lockfile": "4.1.2",
68
69
  "react": "19.2.5",
@@ -77,6 +78,7 @@
77
78
  "@changesets/changelog-github": "^0.7.0",
78
79
  "@changesets/cli": "^2.30.0",
79
80
  "@eslint/js": "^9.39.2",
81
+ "@types/jsonwebtoken": "^9.0.10",
80
82
  "@types/node": "^20.10.6",
81
83
  "@types/proper-lockfile": "^4.1.4",
82
84
  "@types/react": "^19.0.0",