@ciandt-flow/cli 1.4.1-beta.174 → 1.4.1-beta.176

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 +156 -70
  2. package/package.json +1 -2
package/dist/index.js CHANGED
@@ -1,116 +1,202 @@
1
1
  #!/usr/bin/env node
2
- import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import yc,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import _l,{HTTPError}from'ky';import*as St from'crypto';import {randomUUID}from'crypto';import*as q from'fs';import q__default,{readFileSync,existsSync,realpathSync}from'fs';import*as K from'path';import K__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as we from'os';import we__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as io from'readline';import {createInterface}from'readline';import fr from'keytar';import Tn from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import C from'chalk';import ac from'ink-big-text';import Rc from'ink-spinner';import*as be from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp as cp$1}from'fs/promises';import jc from'extract-zip';import Bc from'proper-lockfile';import oo from'semver';import {execa}from'execa';import $o from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var Oo="FLOW",D="flow-skills",gn="flow-cli",Rt="internal",lr="external",yt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},Do={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},yn=new Set(["internal","external"]),_t={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"}},De=5,Qe=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var No=new Set(["skill","mcp","plugin"]),f=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,catalogFilters:{types:new Set(No),origins:new Set(yn)},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(No)},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(yn)},selectedIndex:0}))}));var cr="aes-256-gcm",al=16,Fo=16,Mt=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=St.randomBytes(al),n=St.createCipheriv(cr,this.key,r,{authTagLength:Fo}),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:cr}}decrypt(t){if(t.algorithm!==cr)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=St.createDecipheriv(cr,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Fo});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var ll=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,cl=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,ul=/[A-Za-z0-9+/]{40,}={0,2}/g;function Sn(e){return e.replace(ll,"Bearer ***").replace(cl,"***").replace(ul,"***")}var Ot=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 Dt=".claude",Uo=".flow";function Ko(e,t){return K.join(we.homedir(),Dt,"plugins","cache",D,e,t)}function hn(e){return K.join(we.homedir(),Dt,"plugins","marketplaces",D,"plugins","native",e)}function ur(){return K.join(we.homedir(),Dt,"plugins","marketplaces",D,".claude-plugin","marketplace.json")}function jo(){return K.join(we.homedir(),Dt,"plugins","known_marketplaces.json")}function Bo(){return K.join(we.homedir(),Dt,"plugins","marketplaces",D)}function Jo(){return K.join(we.homedir(),Uo,"cache","install.lock")}function Ho(){return K.join(we.homedir(),Uo,"logs","flowsetup.log")}function Nt(e){let t=e==="global"?we.homedir():process.cwd();return K.join(t,".claude","skills")}function wn(e){let t=e==="global"?we.homedir():process.cwd();return K.join(t,".claude","skills-lock.json")}var pl=5*1024*1024,dl=3,pr=class{filePath;constructor(){this.filePath=Ho(),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=K.dirname(this.filePath);q.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(q.statSync(this.filePath).size>pl){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=K.dirname(this.filePath),r=K.basename(this.filePath,".log"),n=q.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(dl))q.unlinkSync(K.join(t,o));}catch{}}};var dr=class{write(t){process.stdout.write(t.message+`
5
- `);}};var ht={debug:0,info:1,warn:2,error:3},tt={context:"cli",transports:[],minLevel:"warn",debugModules:null};function ml(){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 ie(e,t){if(e==="tui"){let r=ml();tt={context:e,transports:[new Ot("tui"),new pr],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?tt={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?tt={context:e,transports:[new Ot("cli")],minLevel:"debug",debugModules:null}:tt={context:e,transports:[new dr],minLevel:"info",debugModules:null};}function Vo(){return tt.transports}function Go(e,t){let{debugModules:r,minLevel:n}=tt;return tt.context==="tui"&&r&&r!=="all"?r.has(t)?ht[e]>=ht.debug:ht[e]>=ht.warn:ht[e]>=ht[n]}var zo=new Map;function mr(e,t,r){if(!Go(e,t))return;let n={level:e,module:t,message:Sn(r),timestamp:new Date};for(let o of Vo())o.write(n);}function S(e){let t=zo.get(e);if(t)return t;let r={debug:n=>mr("debug",e,n),info:n=>mr("info",e,n),warn:n=>mr("warn",e,n),error:n=>mr("error",e,n)};return zo.set(e,r),r}var xn=S("encryption"),In="__encrypted__";function fl(e){return typeof e=="object"&&e!==null&&In in e&&e[In]===true}function bn(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[In]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return xn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(fl(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return xn.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return xn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var vn=promisify(execFile),Sl=promisify(exec),pe=S("encryption:macos-keyvault"),wt=class{static async isAvailable(){try{let{stdout:t}=await Sl("command -v security");return pe.debug(`security binary found at: ${t.trim()}`),!0}catch{return pe.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{pe.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await vn("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return pe.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return pe.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{pe.debug(`Storing secret: service=${t}, account=${r}`),await vn("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),pe.debug("security add-generic-password succeeded");}catch(o){let i=o;throw pe.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),o}}async deleteSecret(t,r){try{return pe.debug(`Deleting secret: service=${t}, account=${r}`),await vn("security",["delete-generic-password","-a",r,"-s",t]),pe.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return pe.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};var Pn=promisify(execFile),En=promisify(exec),Il=[{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 bl(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 vl(e){let t=io.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var Ne=class e{static async isAvailable(){try{let{stdout:t}=await En("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 Pn("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 Il)try{return await En(`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 vl(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return R.info(`Running: ${t.command}`),await bl("Installing secret-tool...",()=>En(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 Pn("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 Pn("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 de=S("encryption:windows-keyvault"),xt=class{static async isAvailable(){try{return await fr.getPassword("__flow_probe__","__flow_probe__"),de.debug("Windows Credential Manager is available (keytar probe succeeded)"),!0}catch(t){let r=t instanceof Error?t.message.split(`
6
- `)[0]:"unknown error";return de.debug(`Windows Credential Manager not available: ${r}`),false}}async getSecret(t,r){try{de.debug(`Looking up secret: service=${t}, account=${r}`);let n=await fr.getPassword(t,r);return de.debug(`keytar getPassword result: ${n?"found":"empty"}`),n}catch(n){let o=n instanceof Error?n.message.split(`
7
- `)[0]:"unknown error";return de.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{de.debug(`Storing secret: service=${t}, account=${r}`),await fr.setPassword(t,r,n),de.debug("keytar setPassword succeeded");}catch(o){let i=o instanceof Error?o.message.split(`
8
- `)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${i}`;throw de.error(s),new Error(s)}}async deleteSecret(t,r){try{de.debug(`Deleting secret: service=${t}, account=${r}`);let n=await fr.deletePassword(t,r);return de.debug(`keytar deletePassword result: ${n}`),n}catch(n){let o=n instanceof Error?n.message.split(`
9
- `)[0]:"unknown error";return de.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (keytar)"}};var Pl=32,El="flow-plugins-cli-fallback",kn="flow-plugins-cli-fallback",Tl={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 kl(){let e=`${we.hostname()}${we.userInfo().username}`;return St.scryptSync(e,El,Pl)}function Cl(){let e=kl(),t=new Mt(e),r=bn(t);return new Tn({projectName:kn,serialize:r.serialize,deserialize:r.deserialize})}var yr=null;function gr(){return yr||(yr=Cl()),yr}var Y=class{warned=false;async getSecret(t,r){return gr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Tl[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
2
+ import {Box,Text,render,useWindowSize,useApp,useInput}from'ink';import $c,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import Vl,{HTTPError}from'ky';import*as yt from'crypto';import {randomUUID}from'crypto';import*as z from'fs';import z__default,{readFileSync,existsSync,realpathSync}from'fs';import*as U from'path';import U__default,{join,relative,resolve,normalize,sep,dirname,isAbsolute,basename}from'path';import*as he from'os';import he__default,{homedir,tmpdir}from'os';import {execFile,exec,spawn}from'child_process';import {promisify}from'util';import*as co from'readline';import {createInterface}from'readline';import An from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import C from'chalk';import xc from'ink-big-text';import Gc from'ink-spinner';import*as Ie from'fs/promises';import {stat,rm,readdir,readFile,mkdtemp,mkdir,writeFile,cp}from'fs/promises';import eu from'extract-zip';import tu from'proper-lockfile';import lo from'semver';import {execa}from'execa';import Mo from'yocto-spinner';import {Command,Option}from'commander';import {simpleGit}from'simple-git';import {parse}from'yaml';var Uo="FLOW",O="flow-skills",yn="flow-cli",Lt="internal",lr="external",gt={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},Bo={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Sn=new Set(["internal","external"]),Rt={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},Oe=5,Ze=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Ko=new Set(["skill","mcp","plugin"]),f=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,catalogFilters:{types:new Set(Ko),origins:new Set(Sn)},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(Ko)},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(Sn)},selectedIndex:0}))}));var cr="aes-256-gcm",pl=16,jo=16,Mt=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=yt.randomBytes(pl),n=yt.createCipheriv(cr,this.key,r,{authTagLength:jo}),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:cr}}decrypt(t){if(t.algorithm!==cr)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=yt.createDecipheriv(cr,this.key,Buffer.from(t.iv,"hex"),{authTagLength:jo});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var dl=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,ml=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,fl=/[A-Za-z0-9+/]{40,}={0,2}/g;function hn(e){return e.replace(dl,"Bearer ***").replace(ml,"***").replace(fl,"***")}var _t=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
3
+ `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var Ot=".claude",Jo=".flow";function Ho(e,t){return U.join(he.homedir(),Ot,"plugins","cache",O,e,t)}function wn(e){return U.join(he.homedir(),Ot,"plugins","marketplaces",O,"plugins","native",e)}function ur(){return U.join(he.homedir(),Ot,"plugins","marketplaces",O,".claude-plugin","marketplace.json")}function Go(){return U.join(he.homedir(),Ot,"plugins","known_marketplaces.json")}function Vo(){return U.join(he.homedir(),Ot,"plugins","marketplaces",O)}function zo(){return U.join(he.homedir(),Jo,"cache","install.lock")}function Wo(){return U.join(he.homedir(),Jo,"logs","flowsetup.log")}function Dt(e){let t=e==="global"?he.homedir():process.cwd();return U.join(t,".claude","skills")}function xn(e){let t=e==="global"?he.homedir():process.cwd();return U.join(t,".claude","skills-lock.json")}var gl=5*1024*1024,yl=3,pr=class{filePath;constructor(){this.filePath=Wo(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
4
+ `;try{z.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=U.dirname(this.filePath);z.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(z.statSync(this.filePath).size>gl){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);z.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=U.dirname(this.filePath),r=U.basename(this.filePath,".log"),n=z.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(yl))z.unlinkSync(U.join(t,o));}catch{}}};var dr=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var St={debug:0,info:1,warn:2,error:3},et={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Sl(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function oe(e,t){if(e==="tui"){let r=Sl();et={context:e,transports:[new _t("tui"),new pr],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?et={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?et={context:e,transports:[new _t("cli")],minLevel:"debug",debugModules:null}:et={context:e,transports:[new dr],minLevel:"info",debugModules:null};}function qo(){return et.transports}function Xo(e,t){let{debugModules:r,minLevel:n}=et;return et.context==="tui"&&r&&r!=="all"?r.has(t)?St[e]>=St.debug:St[e]>=St.warn:St[e]>=St[n]}var Yo=new Map;function mr(e,t,r){if(!Xo(e,t))return;let n={level:e,module:t,message:hn(r),timestamp:new Date};for(let o of qo())o.write(n);}function S(e){let t=Yo.get(e);if(t)return t;let r={debug:n=>mr("debug",e,n),info:n=>mr("info",e,n),warn:n=>mr("warn",e,n),error:n=>mr("error",e,n)};return Yo.set(e,r),r}var In=S("encryption"),bn="__encrypted__";function hl(e){return typeof e=="object"&&e!==null&&bn in e&&e[bn]===true}function vn(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 In.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(hl(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return In.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return In.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Pn=promisify(execFile),Il=promisify(exec),ue=S("encryption:macos-keyvault"),ht=class{static async isAvailable(){try{let{stdout:t}=await Il("command -v security");return ue.debug(`security binary found at: ${t.trim()}`),!0}catch{return ue.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{ue.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Pn("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return ue.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ue.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{ue.debug(`Storing secret: service=${t}, account=${r}`),await Pn("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),ue.debug("security add-generic-password succeeded");}catch(o){let i=o;throw ue.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),o}}async deleteSecret(t,r){try{return ue.debug(`Deleting secret: service=${t}, account=${r}`),await Pn("security",["delete-generic-password","-a",r,"-s",t]),ue.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return ue.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};var En=promisify(execFile),Tn=promisify(exec),El=[{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 Tl(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 kl(e){let t=co.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(e,n=>{t.close(),r(n.trim().toLowerCase());});})}var De=class e{static async isAvailable(){try{let{stdout:t}=await Tn("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 En("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 El)try{return await Tn(`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 kl(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return R.info(`Running: ${t.command}`),await Tl("Installing secret-tool...",()=>Tn(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 En("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 En("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 Al=promisify(execFile),pe=S("encryption:windows-keyvault"),kn=1,Ll=1,Rl=2,Ml=3;function Cn(e,t){return `${e}:${t}`}var $n=`
6
+ using System;
7
+ using System.Runtime.InteropServices;
8
+ using System.Text;
9
+
10
+ public class FlowCredManager {
11
+ [StructLayout(LayoutKind.Sequential)]
12
+ private struct CREDENTIAL {
13
+ public int Flags;
14
+ public int Type;
15
+ public IntPtr TargetName;
16
+ public IntPtr Comment;
17
+ public long LastWritten;
18
+ public int CredentialBlobSize;
19
+ public IntPtr CredentialBlob;
20
+ public int Persist;
21
+ public int AttributeCount;
22
+ public IntPtr Attributes;
23
+ public IntPtr TargetAlias;
24
+ public IntPtr UserName;
25
+ }
26
+
27
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
28
+ private static extern bool CredRead(string target, int type, int flags, out IntPtr credential);
29
+
30
+ [DllImport("advapi32.dll", SetLastError = true)]
31
+ private static extern bool CredWrite(ref CREDENTIAL credential, int flags);
32
+
33
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
34
+ private static extern bool CredDelete(string target, int type, int flags);
35
+
36
+ [DllImport("advapi32.dll")]
37
+ private static extern void CredFree(IntPtr buffer);
38
+
39
+ public static string Read(string target) {
40
+ IntPtr credPtr;
41
+ if (!CredRead(target, ${kn}, 0, out credPtr)) return "";
42
+ try {
43
+ var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
44
+ if (cred.CredentialBlobSize <= 0) return "";
45
+ return Marshal.PtrToStringUni(cred.CredentialBlob, cred.CredentialBlobSize / 2);
46
+ } finally { CredFree(credPtr); }
47
+ }
48
+
49
+ public static string Write(string target, string secret, string userName) {
50
+ byte[] bytes = Encoding.Unicode.GetBytes(secret);
51
+ IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
52
+ IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
53
+ int[] persistLevels = new int[] { ${Rl}, ${Ml}, ${Ll} };
54
+ int lastErr = 0;
55
+ try {
56
+ foreach (int persist in persistLevels) {
57
+ IntPtr blobPtr = Marshal.AllocHGlobal(bytes.Length);
58
+ try {
59
+ Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
60
+ var cred = new CREDENTIAL();
61
+ cred.Type = ${kn};
62
+ cred.TargetName = targetPtr;
63
+ cred.CredentialBlobSize = bytes.Length;
64
+ cred.CredentialBlob = blobPtr;
65
+ cred.Persist = persist;
66
+ cred.UserName = userPtr;
67
+ if (CredWrite(ref cred, 0)) return "OK:" + persist;
68
+ lastErr = Marshal.GetLastWin32Error();
69
+ } finally { Marshal.FreeHGlobal(blobPtr); }
70
+ }
71
+ return "ERR:" + lastErr;
72
+ } finally {
73
+ Marshal.FreeHGlobal(targetPtr);
74
+ Marshal.FreeHGlobal(userPtr);
75
+ }
76
+ }
77
+
78
+ public static bool Delete(string target) {
79
+ return CredDelete(target, ${kn}, 0);
80
+ }
81
+ }
82
+ `;function Nt(e){return e.replace(/'/g,"''")}function fr(e){return ["-NoProfile","-NonInteractive","-Command",e]}function _l(e){return `Add-Type -TypeDefinition @'
83
+ ${$n}
84
+ '@
85
+ [FlowCredManager]::Read('${Nt(e)}')`}function Ol(e,t,r){return `Add-Type -TypeDefinition @'
86
+ ${$n}
87
+ '@
88
+ [FlowCredManager]::Write('${Nt(e)}', '${Nt(t)}', '${Nt(r)}')`}function Dl(e){return `Add-Type -TypeDefinition @'
89
+ ${$n}
90
+ '@
91
+ [FlowCredManager]::Delete('${Nt(e)}')`}async function gr(e){return Al("powershell.exe",e)}var wt=class{static async isAvailable(){try{let{stdout:t}=await gr(fr('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(`
92
+ `)[0]:"unknown error";return pe.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Cn(t,r);pe.debug(`Looking up secret: target=${n}`);let o=_l(n),{stdout:i}=await gr(fr(o)),s=i.trim();return pe.debug(`CredRead result: ${s?"found":"empty"}`),s||null}catch(n){let o=n instanceof Error?n.message.split(`
93
+ `)[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=Cn(t,r);pe.debug(`Storing secret: target=${o}`);let i=Ol(o,n,r),{stdout:s}=await gr(fr(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(`
94
+ `)[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=Cn(t,r);pe.debug(`Deleting secret: target=${n}`);let o=Dl(n),{stdout:i}=await gr(fr(o)),s=i.trim()==="True";return pe.debug(`CredDelete result: ${s}`),s}catch(n){let o=n instanceof Error?n.message.split(`
95
+ `)[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 Nl=32,Fl="flow-plugins-cli-fallback",Ln="flow-plugins-cli-fallback",Ul={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 Bl(){let e=`${he.hostname()}${he.userInfo().username}`;return yt.scryptSync(e,Fl,Nl)}function Kl(){let e=Bl(),t=new Mt(e),r=vn(t);return new An({projectName:Ln,serialize:r.serialize,deserialize:r.deserialize})}var Sr=null;function yr(){return Sr||(Sr=Kl()),Sr}var X=class{warned=false;async getSecret(t,r){return yr().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Ul[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
10
96
  using a machine-derived key. For stronger security, ${o}.
11
- `),this.warned=true;}gr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=gr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return gr().path}static hasExistingData(){try{let t=new Tn({projectName:kn});return q.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Tn({projectName:kn});q.rmSync(t.path,{force:!0});}catch{}yr=null;}};async function Cn(){if(Y.hasExistingData())return new Y;switch(process.platform){case "darwin":return await wt.isAvailable()?new wt:new Y;case "linux":return await Ne.isAvailable()?new Ne:await Ne.ensureInstalled()?new Ne:new Y;case "win32":return await xt.isAvailable()?new xt:new Y;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var $l=S("config:credentials"),Ae="flow-plugins-cli",$n="credentials",An="token-cache",Ln="user-info",wr=null;async function Fe(){return wr||(wr=Cn()),wr}function xr(){wr=null;}async function N(){let t=await(await Fe()).getSecret(Ae,$n);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function rt(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 $l.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Fe()).setSecret(Ae,$n,JSON.stringify(e));}async function Zo(){let e=await Fe();await e.deleteSecret(Ae,$n),await e.deleteSecret(Ae,An),await e.deleteSecret(Ae,Ln);}async function Qo(){return (await Fe()).getStoragePath()}async function ei(e){await(await Fe()).setSecret(Ae,An,JSON.stringify(e));}async function Ir(){let t=await(await Fe()).getSecret(Ae,An);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function br(e){await(await Fe()).setSecret(Ae,Ln,JSON.stringify(e));}async function ti(){let t=await(await Fe()).getSecret(Ae,Ln);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function It(){let e=await Ir();return e?new Date(e.expiresAt)>new Date:false}function vr(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 ri=[/^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 Al(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 Ll(e){if(ri.some(r=>r.test(e)))return true;let t=Al(e);return !!(t&&ri.some(r=>r.test(t)))}function Rl(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function bt(e,t){let r=Rl(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&&Ll(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Rn=S("api:auth");function Ol(e){if(!Qe.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var ni={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 Dl(e){if(e instanceof HTTPError){let t=e.response.status;Rn.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&&ni[r]?new Error(ni[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?(Rn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Rn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function nt(e){let t=bt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Ol(e.tenant);let r;try{r=await _l.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await Dl(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await rt(e),await ei({accessToken:r.access_token,expiresAt:n});let o=vr(r.access_token);await br({sub:o.sub,name:o.name,email:o.email});}var oi=S("lib:tokenProvider");async function Ue(){if(await It()){let n=await Ir();if(n)return n.accessToken}oi.debug("Token expired or missing, re-authenticating...");let t=await N();if(!t)throw new Error("Not authenticated. Run: flow auth login");Y.clearFallbackFile(),xr(),await nt(t);let r=await Ir();if(!r)throw new Error("Authentication succeeded but token was not persisted");return oi.debug("Token refreshed successfully"),r.accessToken}var Pr=S("api:metrics");function ii(){return bt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function si(e,t,r){return _l.post(e,{json:t,headers:r})}async function Fl(e){let t=await ti();if(t)return t;let r=vr(e),n={sub:r.sub,name:r.name,email:r.email};return await br(n),n}async function b(e,t){let r=await Ue(),n=await Fl(r),o=await N();if(!Qe.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:gn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await si(ii(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Pr.debug(`Metrics event sent: ${e}`);}catch(s){throw Pr.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function ai(e,t,r){try{let n=r&&Qe.test(r)?r:"unknown",o={action:e,booster:gn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await si(ii(),o,{FlowTenant:n}),Pr.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Pr.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var x={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED"};var Ul={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},me={...Ul};function li(e){let t=Date.now();me={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function ot(e){me.currentStep=e,me.stepStart=Date.now();}function A(){return {...me}}function Ke(){return me.sessionStart===0?0:Date.now()-me.sessionStart}function it(){return me.stepStart===0?0:Date.now()-me.stepStart}function ci(){me.tuiSessionStart=Date.now();}function ui(){return me.tuiSessionStart===0?0:Date.now()-me.tuiSessionStart}var Kl=3e3,jl=S("abandonment");async function Er(e){let{currentStep:t,sessionStart:r}=A();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Ke()};try{await Promise.race([b(x.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Kl))]);}catch(o){jl.warn(`Abandonment event failed: ${String(o)}`);}}function pi(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Bl=3e3,Jl=S("session-end");async function Ut(e){let{activeTab:t,screen:r}=f.getState(),n=ui(),i=[b(x.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(Er(e));try{await pi(Promise.all(i).then(()=>{}),Bl);}catch(s){Jl.warn(`Session end event failed: ${String(s)}`);}}var zl=2e3;function mi(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=f(s=>s.pendingExit),o=f(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Ut("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},zl);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var Yl=16;function fi({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(Yl)}),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 fe=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 z(e){process.stdout.write(C.green(` \u2713 ${p(e)}
97
+ `),this.warned=true;}yr().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=yr(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return yr().path}static hasExistingData(){try{let t=new An({projectName:Ln});return z.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new An({projectName:Ln});z.rmSync(t.path,{force:!0});}catch{}Sr=null;}};async function Rn(){if(X.hasExistingData())return new X;switch(process.platform){case "darwin":return await ht.isAvailable()?new ht:new X;case "linux":return await De.isAvailable()?new De:await De.ensureInstalled()?new De:new X;case "win32":return await wt.isAvailable()?new wt:new X;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var jl=S("config:credentials"),$e="flow-plugins-cli",Mn="credentials",_n="token-cache",On="user-info",xr=null;async function Ne(){return xr||(xr=Rn()),xr}function Ir(){xr=null;}async function D(){let t=await(await Ne()).getSecret($e,Mn);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function tt(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw jl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ne()).setSecret($e,Mn,JSON.stringify(e));}async function ri(){let e=await Ne();await e.deleteSecret($e,Mn),await e.deleteSecret($e,_n),await e.deleteSecret($e,On);}async function ni(){return (await Ne()).getStoragePath()}async function oi(e){await(await Ne()).setSecret($e,_n,JSON.stringify(e));}async function br(){let t=await(await Ne()).getSecret($e,_n);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function vr(e){await(await Ne()).setSecret($e,On,JSON.stringify(e));}async function ii(){let t=await(await Ne()).getSecret($e,On);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function xt(){let e=await br();return e?new Date(e.expiresAt)>new Date:false}function Pr(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 si=[/^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 Jl(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 Hl(e){if(si.some(r=>r.test(e)))return true;let t=Jl(e);return !!(t&&si.some(r=>r.test(t)))}function Gl(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function It(e,t){let r=Gl(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&&Hl(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Dn=S("api:auth");function Wl(e){if(!Ze.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var ai={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 ql(e){if(e instanceof HTTPError){let t=e.response.status;Dn.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&&ai[r]?new Error(ai[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?(Dn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Dn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function rt(e){let t=It("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Wl(e.tenant);let r;try{r=await Vl.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await ql(i)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await tt(e),await oi({accessToken:r.access_token,expiresAt:n});let o=Pr(r.access_token);await vr({sub:o.sub,name:o.name,email:o.email});}var li=S("lib:tokenProvider");async function Fe(){if(await xt()){let n=await br();if(n)return n.accessToken}li.debug("Token expired or missing, re-authenticating...");let t=await D();if(!t)throw new Error("Not authenticated. Run: flow auth login");X.clearFallbackFile(),Ir(),await rt(t);let r=await br();if(!r)throw new Error("Authentication succeeded but token was not persisted");return li.debug("Token refreshed successfully"),r.accessToken}var Er=S("api:metrics");function ci(){return It("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ui(e,t,r){return Vl.post(e,{json:t,headers:r})}async function Yl(e){let t=await ii();if(t)return t;let r=Pr(e),n={sub:r.sub,name:r.name,email:r.email};return await vr(n),n}async function b(e,t){let r=await Fe(),n=await Yl(r),o=await D();if(!Ze.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let i={action:e,booster:yn,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await ui(ci(),i,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Er.debug(`Metrics event sent: ${e}`);}catch(s){throw Er.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function pi(e,t,r){try{let n=r&&Ze.test(r)?r:"unknown",o={action:e,booster:yn,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ui(ci(),o,{FlowTenant:n}),Er.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Er.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var x={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED"};var Zl={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},de={...Zl};function di(e){let t=Date.now();de={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function nt(e){de.currentStep=e,de.stepStart=Date.now();}function A(){return {...de}}function Ue(){return de.sessionStart===0?0:Date.now()-de.sessionStart}function ot(){return de.stepStart===0?0:Date.now()-de.stepStart}function mi(){de.tuiSessionStart=Date.now();}function fi(){return de.tuiSessionStart===0?0:Date.now()-de.tuiSessionStart}var Ql=3e3,ec=S("abandonment");async function Tr(e){let{currentStep:t,sessionStart:r}=A();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Ue()};try{await Promise.race([b(x.CLI_ONBOARDING_ABANDONED,n),new Promise((o,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Ql))]);}catch(o){ec.warn(`Abandonment event failed: ${String(o)}`);}}function gi(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var tc=3e3,rc=S("session-end");async function Ut(e){let{activeTab:t,screen:r}=f.getState(),n=fi(),i=[b(x.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&i.push(Tr(e));try{await gi(Promise.all(i).then(()=>{}),tc);}catch(s){rc.warn(`Session end event failed: ${String(s)}`);}}var sc=2e3;function Si(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=f(s=>s.pendingExit),o=f(s=>s.setPendingExit),i=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Ut("double-ctrl-c").finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},sc);},[e,o]);return useInput((s,c)=>{c.ctrl&&s==="c"&&i();}),{pendingExit:n}}var uc=16;function hi({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(uc)}),jsx(Text,{color:o?"cyan":"gray",children:c}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}var me=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));var fc=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8")),Be=fc.version;function p(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function V(e){process.stdout.write(C.green(` \u2713 ${p(e)}
12
98
  `));}function k(e){process.stderr.write(C.red(` \u2717 ${p(e)}
13
99
  `));}function I(e){process.stdout.write(C.cyan(` \u2139 ${p(e)}
14
- `));}function Tr(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(`
100
+ `));}function kr(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(`
15
101
  `),process.stdout.write(` ${C.bold(s(e))}
16
102
  `),process.stdout.write(` ${C.dim(i)}
17
103
  `);for(let c of r)process.stdout.write(` ${s(c)}
18
104
  `);process.stdout.write(`
19
- `);}function vt(e){process.stdout.write(JSON.stringify(e,null,2)+`
20
- `);}function Z(e){process.stdout.write(JSON.stringify(e)+`
21
- `);}function se(e){process.stderr.write(JSON.stringify(e)+`
22
- `);}function F(e){return e instanceof Error?e.message:String(e)}function kr(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function oc(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 Ie=["clientId","clientSecret","tenant"],ic={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function gi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),u=useRef(0),{setCredentials:g,setJustAuthenticated:v}=fe(),{setFocus:d}=f();useInput((h,T)=>{if(!a){if(T.shift&&T.tab){let y=Ie.indexOf(r);y>0&&n(Ie[y-1]);}else if(T.tab){let y=Ie.indexOf(r);y<Ie.length-1&&n(Ie[y+1]);}else if(T.return)if(r==="tenant")E();else {let y=Ie.indexOf(r);n(Ie[y+1]);}}},{isActive:true});let E=async()=>{let h={};for(let T of Ie)e[T].trim()||(h[T]="This field is required");if(Object.keys(h).length>0){i(h);let T=Ie.find(y=>h[y]);T&&n(T);return}l(true),c(null),u.current+=1;try{await nt({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:T,...y}=e;g(y),v(!0),f.getState().setScreen("bundleSetup"),d("bundleList"),b(x.CLI_SESSION_STARTED,{cli_version:je,os:process.platform,node_version:process.version,duration_ms:Ke(),interface:"tui"}).catch(()=>{});}catch(T){let y=T instanceof Error?T.message:"Authentication failed";c(y),ai(x.CLI_AUTH_FAILED,{error_code:oc(T),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(T=>({...T,clientSecret:""}));}},m=h=>T=>{t(y=>({...y,[h]:T})),o[h]&&i(y=>({...y,[h]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Oo," \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:Ie.map(h=>jsx(Box,{marginBottom:1,children:jsx(fi,{label:ic[h],value:e[h],onChange:m(h),masked:h==="clientSecret",isActive:r===h&&!a,error:o[h]})},h))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",p(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function $r(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(ac,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",je]})})]})}var On={discover:"Discover",installed:"Installed"},lc=Object.keys(On);function Ii(){let e=f(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:lc.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${On[t]} `}):jsx(Text,{dimColor:true,children:` ${On[t]} `})},t))})}var Q=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function vi(){let e=f(s=>s.focus),t=Q(s=>s.query),r=Q(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 dc=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...yt[e]})),mc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Do[e]}));function Pi(){let e=f(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),dc.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"]})]}),mc.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 Ei({type:e}){let{label:t,color:r}=yt[e];return jsx(Text,{color:r,children:t})}function Ci({origin:e}){return e===Rt?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Lr=yc.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(Ei,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ci,{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 ",kr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Et({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Li({items:e,emptyMessage:t}){let r=f(a=>a.selectedIndex);if(e.length===0)return jsx(Et,{message:t});let n=Math.max(0,r-Math.floor(De/2)),o=Math.min(e.length,n+De);o===e.length&&(n=Math.max(0,o-De));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(Lr,{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 Mi({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 Di({groups:e,emptyMessage:t}){let r=f(d=>d.selectedIndex),n=[],o=0;for(let d of e){n.push({kind:"header",label:d.label,pathHint:d.pathHint,key:`h-${d.scope}`});for(let E of d.items)n.push({kind:"item",item:E,itemIndex:o,key:`i-${d.scope}-${E.name}`}),o++;}if(o===0)return jsx(Et,{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(De/2)),l=Math.min(n.length,a+De);l===n.length&&(a=Math.max(0,l-De));let u=n.slice(a,l),g=a,v=n.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),u.map(d=>d.kind==="header"?jsx(Mi,{label:d.label,pathHint:d.pathHint},d.key):jsx(Lr,{item:d.item,isSelected:d.itemIndex===r},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:v>0?`\u2193 ${v} more below`:" "})})]})}var vc={discover:"Discover",installed:"Installed"};function Fi({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(vi,{}),jsx(Pi,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:vc[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(Di,{groups:n,emptyMessage:r}):jsx(Li,{items:e,emptyMessage:r})]})}function Ui({filteredItems:e,emptyMessage:t,groups:r}){let n=f(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Fi,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Fi,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Tc={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 Rr(){let e=f(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:Tc[e]})})}function ji({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",p(e)]})}):null}function _r({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Rc,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Mr({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 pt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=f(a=>a.focus),[s,c]=useState(0);return useInput((a,l)=>{l.upArrow?c(u=>u>0?u-1:u):l.downArrow?c(u=>u<t.length-1?u+1:u):l.return?n(t[s]):l.escape&&o();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",a]}),r?.[a]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[a]]})]},l))})]})}var Hn=Object.entries(_t),qi=[...Hn.map(([,e])=>e.actionLabel),"Cancel"],Wi=Object.fromEntries(Hn.map(([,e])=>[e.actionLabel,e.description]));function Xi(e){let t=Hn.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function Zi({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=Xi(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(pt,{itemName:`${e} \u2014 Choose scope`,actions:qi,descriptions:Wi,onAction:i,onClose:s}):jsx(pt,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Dr({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=f(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?n("idle"):i==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function ts({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Dr({activeFocus:"actionMenu",onConfirm:()=>i(t)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let g=r==="enabled"?"Disable":"Enable",v=o&&p(o),d=v?`Update to v${v}`:"Update";return jsx(pt,{itemName:e,actions:n?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===g?s(t):h.startsWith("Update")?c?.():a();},onClose:a})}function os({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Dr({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(pt,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function is(e,t){let r=K.resolve(t);await be.mkdir(r,{recursive:true});let n=K.join(K.dirname(r),`${randomUUID()}.zip`);try{await be.writeFile(n,e),await jc(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=K.resolve(r,o.fileName);if(!s.startsWith(r+K.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(K.resolve(K.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 be.unlink(n);}catch{}}}async function Gn(e){await be.rm(e,{recursive:true,force:true});}async function He(){let e=Jo();await be.mkdir(K.dirname(e),{recursive:true});try{await be.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Bc.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var Hc={user:"global",project:"project",local:"local"};function Ur(e){return e?Hc[e]:"global"}var ve=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},Ve=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 qt(){return _l.create({prefix:bt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Ue();e.headers.set("Authorization",`Bearer ${t}`);let r=await N();r?.tenant&&Qe.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Gc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function ss(e){if(!e||!Gc.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function Pe(){try{let{plugins:e}=await qt().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 kt(e){ss(e);try{return await qt().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 as(e){ss(e);try{let t=await qt().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 Kr(){try{let{profiles:e}=await qt().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 zc=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,qc=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function jr(e){if(!zc.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Wc(e){if(!qc.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 Ge=S("installer");function Xc(e,t){let r=`${e}@${D}`,o=Re().plugins[r];if(o&&!t)throw new ve(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Yc(e,t,r){r&&await Gn(t);try{Ge.debug(`[${t}] Extracting archive...`),await is(e,t);}catch(n){throw await Gn(t),n}}function Zc(e,t,r,n,o){let i=Re(),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],dt(i),zn(e,true,n);}async function Qc(e,t,r,n,o){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:A().interfaceType});}catch(i){Ge.warn(`Failed to send install metrics: ${String(i)}`);}}async function eu(e,t,r){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(n){Ge.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function Ee(e,t={}){let r=Date.now(),n=null;try{Ge.debug(`[${e}] Acquiring lock...`),n=await He();let{pluginKey:o,alreadyInstalled:i}=Xc(e,t.force);Ge.debug(`[${e}] Fetching manifest...`);let s=await kt(e);jr(s.name),Wc(s.version),Ge.debug(`[${e}] Downloading archive...`);let c=await as(e),a=t.scope??"user",l=Ko(s.name,s.version);await Yc(c,l,!!i&&!!t.force),Zc(o,l,s.version,a,"internal"),ls(s,l);let u=Date.now()-r;Ge.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await Qc(s.name,s.version,u,Ur(a),"internal"),g}catch(o){throw await eu(e,o,"internal"),Ge.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=ur();if(!q__default.existsSync(e))return null;try{return JSON.parse(q__default.readFileSync(e,"utf-8"))}catch{return null}}function ru(){let e=ps();if(e)return e;let t=tu(),r=ur();return q__default.mkdirSync(K__default.dirname(r),{recursive:true}),qn(t),t}function qn(e){let t=ur(),r=`${t}.${randomUUID()}.tmp`;q__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),q__default.renameSync(r,t);}function nu(){let e=jo(),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:Bo(),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 ls(e,t){jr(e.name),nu();let r=hn(e.name);q__default.mkdirSync(K__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=ru();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}),qn(n));}function Wn(e){jr(e);let t=hn(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&&qn(r);}var iu=S("mcpConfigReader"),su=500,au=512;function lu(){return K__default.join(we__default.homedir(),".claude.json")}function cu(){return K__default.join(process.cwd(),".mcp.json")}function ms(e){if(!q__default.existsSync(e))return null;try{return JSON.parse(q__default.readFileSync(e,"utf-8"))}catch{return iu.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xn(e){if(!Wt(e))return {};let t=e.mcpServers;return Wt(t)?t:{}}function Yn(e,t){return Object.keys(e).slice(0,su).map(n=>({name:p(n.slice(0,au)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function gs(){let e=[],t=lu(),r=ms(t);if(Wt(r)){let c=r,a=Xn(c);e.push(...Yn(a,"user"));let l=process.cwd();if(Wt(c.projects)){let u=c.projects[l];if(Wt(u)){let g=Xn(u);e.push(...Yn(g,"local"));}}}let n=cu(),o=ms(n),i=Xn(o);e.push(...Yn(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 le=S("storage");async function pu(e,t){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:A().interfaceType});}catch(r){le.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function du(e,t,r){let n=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:A().interfaceType}).catch(o=>le.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ss(){return K__default.join(we__default.homedir(),".claude","plugins","installed_plugins.json")}function mu(){return K__default.join(we__default.homedir(),".claude","plugins")}function ys(e){let t=K__default.resolve(e),r=K__default.resolve(mu()),n=K__default.resolve(K__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+K__default.sep)||t===r,i=t.startsWith(n+K__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function hs(e="user"){return e==="local"?K__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?K__default.join(process.cwd(),".claude","settings.json"):K__default.join(we__default.homedir(),".claude","settings.json")}function Re(){let e=Ss();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 fu(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function ws(e,t){try{q__default.mkdirSync(K__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 fu(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function dt(e){ws(Ss(),e);}function Xt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function gu(e,t){let r=K__default.join(e,".claude-plugin"),n=K__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=K__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 to(e="user"){let t=hs(e);if(!q__default.existsSync(t))return {};try{return JSON.parse(q__default.readFileSync(t,"utf-8"))}catch{return {}}}function xs(e,t="user"){ws(hs(t),e);}function yu(e,t){let{name:r,marketplace:n}=Xt(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Xt(s).name===r)[0],!o)throw le.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Su(e,t){let{name:r,marketplace:n}=Xt(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Xt(s).name===r)[0],o?{key:o,name:r}:null}function Zn(e="user"){return to(e).enabledPlugins??{}}function Qn(e,t="user"){let r=to(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,xs(r,t);}function zn(e,t,r="user"){let n=to(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},xs(n,r);}function hu(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 Te(){let e=Re(),t=Zn(),r=Zn("project"),n=Zn("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:v}=Xt(l),d=u.map(m=>m.scope==="managed"?{...m,scope:"user"}:m);return hu(d).map(m=>{let h=gu(m.installPath,g),y=(o[m.scope]??t)[l];return {name:g,marketplace:v,version:m.version&&m.version!=="unknown"?m.version:void 0,installedAt:m.installedAt,installPath:m.installPath,scope:m.scope,description:h?.description,author:h?.author,status:y===false?"disabled":"enabled"}})}),s=gs(),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 Br(e,t){le.debug(`[${e}] Acquiring lock to uninstall`);let r=await He();try{let n=Re(),o=Su(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`);le.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),ys(a.installPath);let l=K__default.dirname(a.installPath);le.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,...v}=n.plugins;dt({...n,plugins:v}),Qn(i,t),Wn(s);}else n.plugins[i]=u,dt(n),Qn(i,t);}else {le.debug(`[${s}] Resolved key: ${i}`);for(let u of c){ys(u.installPath);let g=K__default.dirname(u.installPath);le.debug(`[${s}] Removing directory: ${g}`),q__default.rmSync(g,{recursive:!0,force:!0}),Qn(i,u.scope);}Wn(s);let{[i]:a,...l}=n.plugins;dt({...n,plugins:l});}await pu(s,c[0].origin??"internal"),le.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function Yt(e,t,r){le.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await He();try{let o=Re(),{key:i,name:s}=yu(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";le.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),zn(i,t==="enabled",a),du(s,t,l),le.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var B=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Te()})}));var U=["discover","installed"];function Is(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 bs(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 vs(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Ps(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 Hr(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=f.getState();for(let i of e)if(i.type==="setTab")t(i.tab);else if(i.type==="setFocus")r(i.focus);else if(i.type==="setSelectedIndex")n(i.index);else if(i.type==="setActionMenuOpen")o(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:c,setCursorPosition:a,cursorPosition:l}=Q.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?f.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?f.getState().selectAllTypes():i.type==="toggleOriginFilter"?f.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&f.getState().selectAllOrigins();}function Es({listLength:e}){let t=f(m=>m.focus),r=f(m=>m.selectedIndex),n=f(m=>m.actionMenuOpen),o=f(m=>m.setFocus),i=f(m=>m.setActionMenuOpen),s=Q(m=>m.query),c=Q(m=>m.setQuery),a=Q(m=>m.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:m,setCursorPosition:h}=Q.getState();h(m.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let m=setTimeout(()=>g(s),300);return ()=>clearTimeout(m)},[s]),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Hr(Is(m,h,{activeTab:T}));},{isActive:t==="tabs"}),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Hr(bs(m,h,{activeTab:T,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((m,h)=>{Hr(vs(m,h));},{isActive:t==="actionMenu"}),useInput((m,h)=>{let T=Ps(m,h,Q.getState().query),y=T.queryUpdate;if(Hr(T.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:$,setCursorPosition:V}=Q.getState();if("backspace"in y)$>0&&(c(L.slice(0,$-1)+L.slice($)),V($-1));else if("append"in y)c(L.slice(0,$)+y.append+L.slice($)),V($+y.append.length);else if("cursorMove"in y){let X=$+y.cursorMove;X>=0&&X<=L.length&&V(X);}}},{isActive:t==="search"});let v=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(m=>{let{setSelectedIndex:h,selectedIndex:T}=f.getState();m===0?h(0):T>=m&&h(m-1);},[]),E=useCallback(m=>{if(!u)return l.current=m.length,m;let h=u.toLowerCase(),T=m.filter(y=>y.name.toLowerCase().includes(h)||y.description?.toLowerCase().includes(h));return l.current=T.length,T},[u]);return {actionMenuOpen:n,closeMenu:v,selectedIndex:r,clampIndex:d,filteredItems:E}}function ks(){let e=f(c=>c.notification),t=f(c=>c.showNotification),r=f(c=>c.clearNotification),n=fe(c=>c.justAuthenticated),o=fe(c=>c.credentials),i=fe(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 _e(e,t,r=false){return r?true:!oo.valid(e)||!oo.valid(t)?false:oo.gt(t,e)}var Me=S("updater");async function bu(e,t,r,n,o){try{await b(x.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:A().interfaceType});}catch(i){Me.warn(`Failed to send update metrics: ${String(i)}`);}}function vu(e){let t=Re(),r=`${e}@${D}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Vr(e,t={}){let r=Date.now(),n=null;try{Me.debug(`[${e}] Acquiring lock...`),n=await He();let o=vu(e);if(!o)throw Me.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;Me.debug(`[${e}] Fetching manifest...`);let l=(await kt(e)).version;if(!s||!_e(s,l,t.force))throw Me.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Ve(e,s??"unknown");Me.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await Ee(e,{force:!0,skipMetrics:!0}),g=Date.now()-r;return await bu(u.name,s,u.version,g,i.origin??"internal"),Me.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){Me.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await He();let g=Re(),v=`${e}@${D}`;throw g.plugins[v]&&(g.plugins[v][0].version=s,g.plugins[v][0].installPath=c,dt(g),Me.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var Pu=S("commands:helpers");async function te(){let e=await N();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Ue();}catch(t){return Pu.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 ze(e){let t=io.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 Cs(e){let t=io.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(n.trim());});})}var Eu=/^[^@]+@[^@]+$/;function Zt(e){return Eu.test(e)}function Ct(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Tu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function $s(e){if(!Tu.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 ku=/^[\w./:@?&=+#%-]+$/;function Gr(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!ku.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Qt=S("claudeProxy"),lo="claude ",As="flow ",so=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ao=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";}},Cu=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/;function $u(e){Rs(e);let t=e.slice(lo.length);if(!Cu.test(t))throw new ao(e)}var zr=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function Rs(e){if(!e||!/^claude /.test(e))throw new so(e)}async function ce(e){Rs(e);let t=e.slice(lo.length).split(/\s+/).filter(Boolean),r=Au(t);Qt.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 Qt.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 _s(o)?new zr:o}}function Au(e){return e.length>=3?e[2]:e.join(" ")}function _s(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Lu(e){return e.startsWith(As)?lo+e.slice(As.length):e}var Ru=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function _u(e,t){return !t||e.includes("--scope")||!Ru.test(e)?e:`${e} --scope ${t}`}async function Ms(e,t){let r=e.split("&&").map(o=>Lu(o.trim())).filter(Boolean).map(o=>_u(o,t));if(r.length===0)throw new Error("Empty install command");for(let o of r)$u(o);Qt.debug(`[installCommand] Executing ${r.length} command(s)`);let n=await ce(r[0]);if(n.exitCode!==0)return n;for(let o=1;o<r.length;o++)if(n=await ce(r[o]),n.exitCode!==0)return n;return n}async function Os(e,t,r){let n=Ct(e),o=t?.trim();if(!o&&(o=(await Cs(`Plugin "${n}" could not be installed.
23
- If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Gr(o),r?.(),Qt.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"}`);Qt.debug(`[${n}] Marketplace added successfully`);}catch(i){throw _s(i)?new zr:i}}var qe=S("installDispatcher");async function Ds(e,t,r){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Ur(r),version:"unknown",duration_ms:t,interface:A().interfaceType});}catch(n){qe.warn(`Failed to send external install metrics: ${String(n)}`);}}async function Ns(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){qe.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function co(e,t){let r=Ct(e);$s(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function uo(e,t,r,n){let o=co(e,n),i=Ct(e);r?.onStatus?.(`Installing ${i}...`),qe.debug(`[${e}] Attempting install: ${o}`);let s=await ce(o);return s.exitCode===0?s:(qe.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 Os(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),qe.debug(`[${e}] Retrying install after marketplace add`),ce(o))}async function Fs(e,t){if(e.origin===lr&&e.installCommand){qe.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await Ms(e.installCommand,t?.scope);return r.exitCode===0?await Ds(e.name,r.duration_ms,t?.scope):await Ns(e.name,new Error(r.stderr||"Install failed")),r}if(Zt(e.name)){qe.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await uo(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await Ds(e.name,r.duration_ms,t?.scope):await Ns(e.name,new Error(r.stderr||"Install failed")),r}return qe.debug(`[${e.name}] Routing to internal installer`),Ee(e.name,t)}function Us(e){return "exitCode"in e}function Ks(){let e=B(s=>s.installedItems),t=B(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await Fs(s,c);if(Us(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");B.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await Br(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 Yt(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Vr(s),B.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var Wr=S("mcp");function er(e,t){e.silent?se({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 Bs(e,t){e.silent?Z({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(z(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function Mu(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 po(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Js(e,t,r){if(!await te())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return er(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}Wr.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Mu(e,t,r.transport,r.scope);if(!r.force){let i=p(e),s=p(n);if(!await ze(`Install external MCP "${i}"?
105
+ `);}function bt(e){process.stdout.write(JSON.stringify(e,null,2)+`
106
+ `);}function Y(e){process.stdout.write(JSON.stringify(e)+`
107
+ `);}function ie(e){process.stderr.write(JSON.stringify(e)+`
108
+ `);}function N(e){return e instanceof Error?e.message:String(e)}function Cr(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}function Sc(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var xe=["clientId","clientSecret","tenant"],hc={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function wi(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,i]=useState({}),[s,c]=useState(null),[a,l]=useState(false),u=useRef(0),{setCredentials:g,setJustAuthenticated:v}=me(),{setFocus:d}=f();useInput((h,T)=>{if(!a){if(T.shift&&T.tab){let y=xe.indexOf(r);y>0&&n(xe[y-1]);}else if(T.tab){let y=xe.indexOf(r);y<xe.length-1&&n(xe[y+1]);}else if(T.return)if(r==="tenant")E();else {let y=xe.indexOf(r);n(xe[y+1]);}}},{isActive:true});let E=async()=>{let h={};for(let T of xe)e[T].trim()||(h[T]="This field is required");if(Object.keys(h).length>0){i(h);let T=xe.find(y=>h[y]);T&&n(T);return}l(true),c(null),u.current+=1;try{await rt({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()});let{clientSecret:T,...y}=e;g(y),v(!0),f.getState().setScreen("bundleSetup"),d("bundleList"),b(x.CLI_SESSION_STARTED,{cli_version:Be,os:process.platform,node_version:process.version,duration_ms:Ue(),interface:"tui"}).catch(()=>{});}catch(T){let y=T instanceof Error?T.message:"Authentication failed";c(y),pi(x.CLI_AUTH_FAILED,{error_code:Sc(T),attempt:u.current},e.tenant.trim()).catch(()=>{});}finally{l(false),t(T=>({...T,clientSecret:""}));}},m=h=>T=>{t(y=>({...y,[h]:T})),o[h]&&i(y=>({...y,[h]:void 0}));};return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Uo," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:xe.map(h=>jsx(Box,{marginBottom:1,children:jsx(hi,{label:hc[h],value:e[h],onChange:m(h),masked:h==="clientSecret",isActive:r===h&&!a,error:o[h]})},h))}),a&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),s&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",p(s)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Ar(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(xc,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",Be]})})]})}var Un={discover:"Discover",installed:"Installed"},Ic=Object.keys(Un);function Ei(){let e=f(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Ic.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${Un[t]} `}):jsx(Text,{dimColor:true,children:` ${Un[t]} `})},t))})}var Z=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function ki(){let e=f(s=>s.focus),t=Z(s=>s.query),r=Z(s=>s.cursorPosition),n=e==="search",o=t.slice(0,r),i=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var Ec=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...gt[e]})),Tc=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Bo[e]}));function Ci(){let e=f(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Ec.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"]})]}),Tc.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 $i({type:e}){let{label:t,color:r}=gt[e];return jsx(Text,{color:r,children:t})}function Ri({origin:e}){return e===Lt?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Rr=$c.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($i,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ri,{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 ",Cr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Pt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Oi({items:e,emptyMessage:t}){let r=f(a=>a.selectedIndex);if(e.length===0)return jsx(Pt,{message:t});let n=Math.max(0,r-Math.floor(Oe/2)),o=Math.min(e.length,n+Oe);o===e.length&&(n=Math.max(0,o-Oe));let i=e.slice(n,o),s=n,c=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((a,l)=>jsx(Rr,{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 Fi({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 Bi({groups:e,emptyMessage:t}){let r=f(d=>d.selectedIndex),n=[],o=0;for(let d of e){n.push({kind:"header",label:d.label,pathHint:d.pathHint,key:`h-${d.scope}`});for(let E of d.items)n.push({kind:"item",item:E,itemIndex:o,key:`i-${d.scope}-${E.name}`}),o++;}if(o===0)return jsx(Pt,{message:t});let s=n.findIndex(d=>d.kind==="item"&&d.itemIndex===r),c=s>=0?s:0,a=Math.max(0,c-Math.floor(Oe/2)),l=Math.min(n.length,a+Oe);l===n.length&&(a=Math.max(0,l-Oe));let u=n.slice(a,l),g=a,v=n.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),u.map(d=>d.kind==="header"?jsx(Fi,{label:d.label,pathHint:d.pathHint},d.key):jsx(Rr,{item:d.item,isSelected:d.itemIndex===r},d.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:v>0?`\u2193 ${v} more below`:" "})})]})}var Dc={discover:"Discover",installed:"Installed"};function ji({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(ki,{}),jsx(Ci,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Dc[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(Bi,{groups:n,emptyMessage:r}):jsx(Oi,{items:e,emptyMessage:r})]})}function Ji({filteredItems:e,emptyMessage:t,groups:r}){let n=f(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(ji,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(ji,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}var Uc={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 Mr(){let e=f(t=>t.focus);return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsx(Text,{dimColor:true,children:Uc[e]})})}function Gi({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",p(e)]})}):null}function _r({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gc,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Or({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ut({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let i=f(a=>a.focus),[s,c]=useState(0);return useInput((a,l)=>{l.upArrow?c(u=>u>0?u-1:u):l.downArrow?c(u=>u<t.length-1?u+1:u):l.return?n(t[s]):l.escape&&o();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((a,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",a]}),r?.[a]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[a]]})]},l))})]})}var Wn=Object.entries(Rt),Zi=[...Wn.map(([,e])=>e.actionLabel),"Cancel"],Qi=Object.fromEntries(Wn.map(([,e])=>[e.actionLabel,e.description]));function es(e){let t=Wn.find(([,r])=>r.actionLabel===e);return t?t[0]:null}function rs({itemName:e,onInstall:t,onClose:r}){let[n,o]=useState(false),i=useCallback(l=>{let u=es(l);u?t(u):o(false);},[t]),s=useCallback(()=>{o(false);},[]),c=useCallback(l=>{l==="Install"?o(true):r();},[r]);return n?jsx(ut,{itemName:`${e} \u2014 Choose scope`,actions:Zi,descriptions:Qi,onAction:i,onClose:s}):jsx(ut,{itemName:e,actions:["Install","Cancel"],onAction:c,onClose:r})}function Nr({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=f(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?n("idle"):i==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function is({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:i,onToggleStatus:s,onUpdate:c,onClose:a}){let{isConfirming:l,requestConfirm:u}=Nr({activeFocus:"actionMenu",onConfirm:()=>i(t)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let g=r==="enabled"?"Disable":"Enable",v=o&&p(o),d=v?`Update to v${v}`:"Update";return jsx(ut,{itemName:e,actions:n?["Uninstall",g,d,"Cancel"]:["Uninstall",g,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===g?s(t):h.startsWith("Update")?c?.():a();},onClose:a})}function ls({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:i}=Nr({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ut,{itemName:e,actions:["Uninstall","Cancel"],onAction:a=>{a==="Uninstall"?i():n();},onClose:n})}async function cs(e,t){let r=U.resolve(t);await Ie.mkdir(r,{recursive:true});let n=U.join(U.dirname(r),`${randomUUID()}.zip`);try{await Ie.writeFile(n,e),await eu(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let s=U.resolve(r,o.fileName);if(!s.startsWith(r+U.sep)&&s!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(U.resolve(U.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Ie.unlink(n);}catch{}}}async function Xn(e){await Ie.rm(e,{recursive:true,force:true});}async function Je(){let e=zo();await Ie.mkdir(U.dirname(e),{recursive:true});try{await Ie.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await tu.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}var nu={user:"global",project:"project",local:"local"};function Br(e){return e?nu[e]:"global"}var be=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},He=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};function Wt(){return Vl.create({prefix:It("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Fe();e.headers.set("Authorization",`Bearer ${t}`);let r=await D();r?.tenant&&Ze.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var iu=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function us(e){if(!e||!iu.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}async function ve(){try{let{plugins:e}=await Wt().get("v1/plugins/catalog").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${e.message}`):e}}async function Tt(e){us(e);try{return await Wt().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 ps(e){us(e);try{let t=await Wt().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 Kr(){try{let{profiles:e}=await Wt().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 su=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,au=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function jr(e){if(!su.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function lu(e){if(!au.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 Ge=S("installer");function cu(e,t){let r=`${e}@${O}`,o=Le().plugins[r];if(o&&!t)throw new be(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function uu(e,t,r){r&&await Xn(t);try{Ge.debug(`[${t}] Extracting archive...`),await cs(e,t);}catch(n){throw await Xn(t),n}}function pu(e,t,r,n,o){let i=Le(),s={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o},c=i.plugins[e]??[];i.plugins[e]=[...c.filter(a=>a.scope!==n),s],pt(i),Yn(e,true,n);}async function du(e,t,r,n,o){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:A().interfaceType});}catch(i){Ge.warn(`Failed to send install metrics: ${String(i)}`);}}async function mu(e,t,r){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(n){Ge.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function Pe(e,t={}){let r=Date.now(),n=null;try{Ge.debug(`[${e}] Acquiring lock...`),n=await Je();let{pluginKey:o,alreadyInstalled:i}=cu(e,t.force);Ge.debug(`[${e}] Fetching manifest...`);let s=await Tt(e);jr(s.name),lu(s.version),Ge.debug(`[${e}] Downloading archive...`);let c=await ps(e),a=t.scope??"user",l=Ho(s.name,s.version);await uu(c,l,!!i&&!!t.force),pu(o,l,s.version,a,"internal"),ds(s,l);let u=Date.now()-r;Ge.debug(`[${e}] Installed successfully in ${u}ms`);let g={name:s.name,version:s.version,path:l,duration_ms:u};return t.skipMetrics||await du(s.name,s.version,u,Br(a),"internal"),g}catch(o){throw await mu(e,o,"internal"),Ge.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}function fu(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:O,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function gs(){let e=ur();if(!z__default.existsSync(e))return null;try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return null}}function gu(){let e=gs();if(e)return e;let t=fu(),r=ur();return z__default.mkdirSync(U__default.dirname(r),{recursive:true}),Zn(t),t}function Zn(e){let t=ur(),r=`${t}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(e,null,2),"utf-8"),z__default.renameSync(r,t);}function yu(){let e=Go(),t={};try{z__default.existsSync(e)&&(t=JSON.parse(z__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[O])return;t[O]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Vo(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),z__default.renameSync(r,e);}function ds(e,t){jr(e.name),yu();let r=wn(e.name);z__default.mkdirSync(U__default.dirname(r),{recursive:true});try{z__default.lstatSync(r),z__default.rmSync(r,{recursive:!0,force:!0});}catch{}z__default.symlinkSync(t,r);let n=gu();n.plugins.some(i=>i.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Zn(n));}function Qn(e){jr(e);let t=wn(e);try{z__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=gs();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Zn(r);}var hu=S("mcpConfigReader"),wu=500,xu=512;function Iu(){return U__default.join(he__default.homedir(),".claude.json")}function bu(){return U__default.join(process.cwd(),".mcp.json")}function Ss(e){if(!z__default.existsSync(e))return null;try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return hu.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e){if(!qt(e))return {};let t=e.mcpServers;return qt(t)?t:{}}function to(e,t){return Object.keys(e).slice(0,wu).map(n=>({name:p(n.slice(0,xu)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function ws(){let e=[],t=Iu(),r=Ss(t);if(qt(r)){let c=r,a=eo(c);e.push(...to(a,"user"));let l=process.cwd();if(qt(c.projects)){let u=c.projects[l];if(qt(u)){let g=eo(u);e.push(...to(g,"local"));}}}let n=bu(),o=Ss(n),i=eo(o);e.push(...to(i,"project"));let s=new Map;for(let c of e){let a=`${c.name}@${c.scope}`;s.has(a)||s.set(a,c);}return [...s.values()]}var ae=S("storage");async function Pu(e,t){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:A().interfaceType});}catch(r){ae.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function Eu(e,t,r){let n=t==="enabled"?x.CLI_TOOL_ENABLED:x.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:A().interfaceType}).catch(o=>ae.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Is(){return U__default.join(he__default.homedir(),".claude","plugins","installed_plugins.json")}function Tu(){return U__default.join(he__default.homedir(),".claude","plugins")}function xs(e){let t=U__default.resolve(e),r=U__default.resolve(Tu()),n=U__default.resolve(U__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+U__default.sep)||t===r,i=t.startsWith(n+U__default.sep)||t===n;if(!o&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function bs(e="user"){return e==="local"?U__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?U__default.join(process.cwd(),".claude","settings.json"):U__default.join(he__default.homedir(),".claude","settings.json")}function Le(){let e=Is();if(!z__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(z__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}function ku(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function vs(e,t){try{z__default.mkdirSync(U__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;z__default.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),z__default.renameSync(r,e);}catch(r){throw ku(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function pt(e){vs(Is(),e);}function Xt(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Cu(e,t){let r=U__default.join(e,".claude-plugin"),n=U__default.join(r,"plugin.json");if(z__default.existsSync(n))try{return JSON.parse(z__default.readFileSync(n,"utf-8"))}catch{return null}let o=U__default.join(r,"marketplace.json");if(z__default.existsSync(o))try{let i=JSON.parse(z__default.readFileSync(o,"utf-8"));return {description:i.plugins?.find(c=>c.name===t)?.description,author:i.owner}}catch{return null}return null}function io(e="user"){let t=bs(e);if(!z__default.existsSync(t))return {};try{return JSON.parse(z__default.readFileSync(t,"utf-8"))}catch{return {}}}function Ps(e,t="user"){vs(bs(t),e);}function $u(e,t){let{name:r,marketplace:n}=Xt(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Xt(s).name===r)[0],!o)throw ae.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Au(e,t){let{name:r,marketplace:n}=Xt(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(s=>Xt(s).name===r)[0],o?{key:o,name:r}:null}function ro(e="user"){return io(e).enabledPlugins??{}}function no(e,t="user"){let r=io(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...i}=n;r.enabledPlugins=i,Ps(r,t);}function Yn(e,t,r="user"){let n=io(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Ps(n,r);}function Lu(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function Ee(){let e=Le(),t=ro(),r=ro("project"),n=ro("local"),o={project:r,local:n},i=Object.entries(e.plugins).flatMap(([l,u])=>{let{name:g,marketplace:v}=Xt(l),d=u.map(m=>m.scope==="managed"?{...m,scope:"user"}:m);return Lu(d).map(m=>{let h=Cu(m.installPath,g),y=(o[m.scope]??t)[l];return {name:g,marketplace:v,version:m.version&&m.version!=="unknown"?m.version:void 0,installedAt:m.installedAt,installPath:m.installPath,scope:m.scope,description:h?.description,author:h?.author,status:y===false?"disabled":"enabled"}})}),s=ws(),c=new Set(i.map(l=>`${l.name}@${l.scope}`)),a=s.filter(l=>!c.has(`${l.name}@${l.scope}`));return [...i,...a]}async function Jr(e,t){ae.debug(`[${e}] Acquiring lock to uninstall`);let r=await Je();try{let n=Le(),o=Au(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=o,c=n.plugins[i];if(t){let a=c.find(g=>g.scope===t);if(!a)throw new Error(`Plugin '${s}' is not installed in ${t} scope`);ae.debug(`[${s}] Resolved key: ${i}, scope: ${t}`),xs(a.installPath);let l=U__default.dirname(a.installPath);ae.debug(`[${s}] Removing directory: ${l}`),z__default.rmSync(l,{recursive:!0,force:!0});let u=c.filter(g=>g.scope!==t);if(u.length===0){let{[i]:g,...v}=n.plugins;pt({...n,plugins:v}),no(i,t),Qn(s);}else n.plugins[i]=u,pt(n),no(i,t);}else {ae.debug(`[${s}] Resolved key: ${i}`);for(let u of c){xs(u.installPath);let g=U__default.dirname(u.installPath);ae.debug(`[${s}] Removing directory: ${g}`),z__default.rmSync(g,{recursive:!0,force:!0}),no(i,u.scope);}Qn(s);let{[i]:a,...l}=n.plugins;pt({...n,plugins:l});}await Pu(s,c[0].origin??"internal"),ae.debug(`[${s}] Uninstalled successfully`);}finally{await r();}}async function Yt(e,t,r){ae.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Je();try{let o=Le(),{key:i,name:s}=$u(e,o.plugins),c=o.plugins[i],a=r??c[0].scope,l=c[0].origin??"internal";ae.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),Yn(i,t==="enabled",a),Eu(s,t,l),ae.debug(`[${s}] Status updated to ${t}`);}finally{await n();}}var K=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Ee()})}));var F=["discover","installed"];function Es(e,t,r){if(t.rightArrow||t.tab){let n=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(n+1)%F.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}if(t.leftArrow){let n=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(n-1+F.length)%F.length]},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}]}return t.downArrow?[{type:"setFocus",focus:"list"}]:[]}function Ts(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o-1+F.length)%F.length]},{type:"setSelectedIndex",index:0}]}if(t.rightArrow){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o+1)%F.length]},{type:"setSelectedIndex",index:0}]}if(t.tab){let o=F.indexOf(r.activeTab);return [{type:"setTab",tab:F[(o+1)%F.length]},{type:"setSelectedIndex",index:0}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function ks(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Cs(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 Gr(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=f.getState();for(let i of e)if(i.type==="setTab")t(i.tab);else if(i.type==="setFocus")r(i.focus);else if(i.type==="setSelectedIndex")n(i.index);else if(i.type==="setActionMenuOpen")o(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:c,setCursorPosition:a,cursorPosition:l}=Z.getState();s(c.slice(0,l)+i.char+c.slice(l)),a(l+i.char.length);}else i.type==="toggleTypeFilter"?f.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?f.getState().selectAllTypes():i.type==="toggleOriginFilter"?f.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&f.getState().selectAllOrigins();}function $s({listLength:e}){let t=f(m=>m.focus),r=f(m=>m.selectedIndex),n=f(m=>m.actionMenuOpen),o=f(m=>m.setFocus),i=f(m=>m.setActionMenuOpen),s=Z(m=>m.query),c=Z(m=>m.setQuery),a=Z(m=>m.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:m,setCursorPosition:h}=Z.getState();h(m.length);}},[t]);let[u,g]=useState("");useEffect(()=>{let m=setTimeout(()=>g(s),300);return ()=>clearTimeout(m)},[s]),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Gr(Es(m,h,{activeTab:T}));},{isActive:t==="tabs"}),useInput((m,h)=>{let{activeTab:T,selectedIndex:y,actionMenuOpen:L}=f.getState();Gr(Ts(m,h,{activeTab:T,selectedIndex:y},l.current));},{isActive:t==="list"}),useInput((m,h)=>{Gr(ks(m,h));},{isActive:t==="actionMenu"}),useInput((m,h)=>{let T=Cs(m,h,Z.getState().query),y=T.queryUpdate;if(Gr(T.actions),y==="reset")a(),g("");else if(y!==null){let{query:L,cursorPosition:$,setCursorPosition:H}=Z.getState();if("backspace"in y)$>0&&(c(L.slice(0,$-1)+L.slice($)),H($-1));else if("append"in y)c(L.slice(0,$)+y.append+L.slice($)),H($+y.append.length);else if("cursorMove"in y){let q=$+y.cursorMove;q>=0&&q<=L.length&&H(q);}}},{isActive:t==="search"});let v=useCallback(()=>{i(false),o("list");},[i,o]),d=useCallback(m=>{let{setSelectedIndex:h,selectedIndex:T}=f.getState();m===0?h(0):T>=m&&h(m-1);},[]),E=useCallback(m=>{if(!u)return l.current=m.length,m;let h=u.toLowerCase(),T=m.filter(y=>y.name.toLowerCase().includes(h)||y.description?.toLowerCase().includes(h));return l.current=T.length,T},[u]);return {actionMenuOpen:n,closeMenu:v,selectedIndex:r,clampIndex:d,filteredItems:E}}function Ls(){let e=f(c=>c.notification),t=f(c=>c.showNotification),r=f(c=>c.clearNotification),n=me(c=>c.justAuthenticated),o=me(c=>c.credentials),i=me(c=>c.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),i(false));},[n,o]),useEffect(()=>{if(!e)return;let c=setTimeout(r,3e3);return ()=>clearTimeout(c)},[e]),{notify:(c,a)=>{t(c,a);}}}function Re(e,t,r=false){return r?true:!lo.valid(e)||!lo.valid(t)?false:lo.gt(t,e)}var Me=S("updater");async function Ou(e,t,r,n,o){try{await b(x.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:A().interfaceType});}catch(i){Me.warn(`Failed to send update metrics: ${String(i)}`);}}function Du(e){let t=Le(),r=`${e}@${O}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Vr(e,t={}){let r=Date.now(),n=null;try{Me.debug(`[${e}] Acquiring lock...`),n=await Je();let o=Du(e);if(!o)throw Me.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=o,s=i.version,c=i.installPath;Me.debug(`[${e}] Fetching manifest...`);let l=(await Tt(e)).version;if(!s||!Re(s,l,t.force))throw Me.debug(`[${e}] Already up to date (v${s??"n/a"})`),new He(e,s??"unknown");Me.info(`[${e}] Updating v${s} \u2192 v${l}...`),await n(),n=null;try{let u=await Pe(e,{force:!0,skipMetrics:!0}),g=Date.now()-r;return await Ou(u.name,s,u.version,g,i.origin??"internal"),Me.debug(`[${e}] Updated successfully in ${g}ms`),{name:u.name,previousVersion:s,newVersion:u.version,path:u.path,duration_ms:g}}catch(u){Me.warn(`[${e}] Install failed, rolling back to v${s}...`),n=await Je();let g=Le(),v=`${e}@${O}`;throw g.plugins[v]&&(g.plugins[v][0].version=s,g.plugins[v][0].installPath=c,pt(g),Me.info(`[${e}] Rollback completed, restored to v${s}`)),u}}finally{n&&await n();}}var Nu=S("commands:helpers");async function ee(){let e=await D();if(!e)return k("Not authenticated. Run: flow auth login"),false;try{await Fe();}catch(t){return Nu.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 Ve(e){let t=co.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 Rs(e){let t=co.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(p(e),n=>{t.close(),r(n.trim());});})}var Fu=/^[^@]+@[^@]+$/;function Zt(e){return Fu.test(e)}function kt(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Uu=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Ms(e){if(!Uu.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 Bu=/^[\w./:@?&=+#%-]+$/;function zr(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Bu.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Qt=S("claudeProxy"),mo="claude ",_s="flow ",uo=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},po=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Ku=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/;function ju(e){Ds(e);let t=e.slice(mo.length);if(!Ku.test(t))throw new po(e)}var Wr=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function Ds(e){if(!e||!/^claude /.test(e))throw new uo(e)}async function le(e){Ds(e);let t=e.slice(mo.length).split(/\s+/).filter(Boolean),r=Ju(t);Qt.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 Qt.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 Ns(o)?new Wr:o}}function Ju(e){return e.length>=3?e[2]:e.join(" ")}function Ns(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Hu(e){return e.startsWith(_s)?mo+e.slice(_s.length):e}var Gu=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Vu(e,t){return !t||e.includes("--scope")||!Gu.test(e)?e:`${e} --scope ${t}`}async function Fs(e,t){let r=e.split("&&").map(o=>Hu(o.trim())).filter(Boolean).map(o=>Vu(o,t));if(r.length===0)throw new Error("Empty install command");for(let o of r)ju(o);Qt.debug(`[installCommand] Executing ${r.length} command(s)`);let n=await le(r[0]);if(n.exitCode!==0)return n;for(let o=1;o<r.length;o++)if(n=await le(r[o]),n.exitCode!==0)return n;return n}async function Us(e,t,r){let n=kt(e),o=t?.trim();if(!o&&(o=(await Rs(`Plugin "${n}" could not be installed.
109
+ 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=zr(o),r?.(),Qt.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"}`);Qt.debug(`[${n}] Marketplace added successfully`);}catch(i){throw Ns(i)?new Wr:i}}var ze=S("installDispatcher");async function Bs(e,t,r){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Br(r),version:"unknown",duration_ms:t,interface:A().interfaceType});}catch(n){ze.warn(`Failed to send external install metrics: ${String(n)}`);}}async function Ks(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){ze.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}function fo(e,t){let r=kt(e);Ms(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}async function go(e,t,r,n){let o=fo(e,n),i=kt(e);r?.onStatus?.(`Installing ${i}...`),ze.debug(`[${e}] Attempting install: ${o}`);let s=await le(o);return s.exitCode===0?s:(ze.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`),r?.onError?.(s.stderr||`Install failed with exit code ${s.exitCode}`),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await Us(e,t,()=>{t||r?.onResume?.(`Adding marketplace for ${i}...`);}),r?.onResume?.(`Retrying install for ${i}...`),ze.debug(`[${e}] Retrying install after marketplace add`),le(o))}async function js(e,t){if(e.origin===lr&&e.installCommand){ze.debug(`[${e.name}] Routing to external installer via installCommand`);let r=await Fs(e.installCommand,t?.scope);return r.exitCode===0?await Bs(e.name,r.duration_ms,t?.scope):await Ks(e.name,new Error(r.stderr||"Install failed")),r}if(Zt(e.name)){ze.debug(`[${e.name}] Routing to external installer via name pattern`);let r=await go(e.name,t?.marketplaceSource,void 0,t?.scope);return r.exitCode===0?await Bs(e.name,r.duration_ms,t?.scope):await Ks(e.name,new Error(r.stderr||"Install failed")),r}return ze.debug(`[${e.name}] Routing to internal installer`),Pe(e.name,t)}function Js(e){return "exitCode"in e}function Hs(){let e=K(s=>s.installedItems),t=K(s=>s.setInstalledItems),r=useCallback(async(s,c)=>{let a=await js(s,c);if(Js(a)&&a.exitCode!==0)throw new Error(a.stderr||"External installation failed");K.getState().loadFromDisk();},[]),n=useCallback(async(s,c)=>{await Jr(s,c),t(e.filter(a=>a.name!==s));},[e,t]),o=useCallback(async(s,c)=>{let l=e.find(u=>u.name===s)?.status==="enabled"?"disabled":"enabled";await Yt(s,l,c),t(e.map(u=>u.name===s?{...u,status:l}:u));},[e,t]),i=useCallback(async s=>{await Vr(s),K.getState().loadFromDisk();},[]);return {install:r,uninstall:n,toggle:o,update:i}}var Xr=S("mcp");function er(e,t){e.silent?ie({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):k(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Vs(e,t){e.silent?Y({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(V(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function zu(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 yo(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function zs(e,t,r){if(!await ee())return 1;if(t.length===0){let i=r.transport==="http"?"a URL":"a command";return er(r,{name:e,action:"add",message:`${r.transport} transport requires ${i}`}),1}Xr.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=zu(e,t,r.transport,r.scope);if(!r.force){let i=p(e),s=p(n);if(!await Ve(`Install external MCP "${i}"?
24
110
  This will run: ${s}
25
- [y/N] `))return Wr.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:$o({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await ce(n);return o?.stop(),i.exitCode!==0?(er(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&I(`stdout: ${i.stdout}`),1):(Bs(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),er(r,{name:e,action:"add",message:F(i)}),1}}async function Hs(e,t){if(!await te())return 1;Wr.debug(`[${e}] Starting MCP remove`);let r=po(e,t.scope);if(!t.force){let o=p(e),i=p(r);if(!await ze(`Remove MCP "${o}"?
111
+ [y/N] `))return Xr.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:Mo({text:`Adding MCP "${p(e)}"...`}).start();try{let i=await le(n);return o?.stop(),i.exitCode!==0?(er(r,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!r.silent&&r.verbose&&i.stdout&&I(`stdout: ${i.stdout}`),1):(Vs(r,{name:e,actionPastTense:"added",command:n,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return o?.stop(),er(r,{name:e,action:"add",message:N(i)}),1}}async function Ws(e,t){if(!await ee())return 1;Xr.debug(`[${e}] Starting MCP remove`);let r=yo(e,t.scope);if(!t.force){let o=p(e),i=p(r);if(!await Ve(`Remove MCP "${o}"?
26
112
  This will run: ${i}
27
- [y/N] `))return Wr.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:$o({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await ce(r);return n?.stop(),o.exitCode!==0?(er(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(Bs(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),er(t,{name:e,action:"remove",message:F(o)}),1}}function Vs({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=f(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Ks(),v=async(y,L,$)=>{c(true,y),n();try{await L(),o(r.length),i($,"success");}catch(V){let X=V instanceof Error?V.message:"Something went wrong";s.error(`[withLoading] ${y} failed: ${X}`),i(X,"error");}finally{c(false);}};return {handleInstall:y=>{e&&t&&v(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&v(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";v(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,y),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let y=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${y}...`),n();try{await g(e.name),o(r.length),i(`\u2713 Updated ${e.name}${y}`,"success");}catch($){if($ instanceof Ve)i($.message,"info");else {let V=$ instanceof Error?$.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${V}`),i(V,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:y=>{e&&v(`Removing MCP ${e.name}...`,async()=>{let L=po(e.name,y),$=await ce(L);if($.exitCode!==0)throw new Error($.stderr||"MCP removal failed");B.getState().loadFromDisk();},"\u2713 MCP removed");}}}var tr=["local","project","user"],Ou=new Set(["--transport","--scope","-s"]);function Gs(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(Ou.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function rr(e,t){return t?`${e}::${t}`:e}function mo(e){return e===D?Rt:lr}function zs(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??Rt}}function qs(e,t){let r=mo(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 Ws(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 tr.filter(r=>t.has(r)).map(r=>({scope:r,label:_t[r].label,pathHint:_t[r].pathHint,items:t.get(r)??[]}))}function Xs(e){let t=r=>{if(!r)return 1/0;let n=tr.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Ys({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>rr(d.name,d.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(d=>d.type==="mcp").map(d=>d.name.toLowerCase())),[t]),c=useMemo(()=>{let d=new Map(e.map(E=>[rr(E.name,E.author.name),E]));return t.map(E=>{let m=d.get(rr(E.name,E.author?.name)),h=m?.version,T=!!h&&!!E.version&&_e(E.version,h);return {...E,updateAvailable:T,catalogItem:m}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(d=>{if(i.has(rr(d.name,d.author.name)))return false;if(d.type==="mcp"){let E=d.installCommand?Gs(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||E&&s.has(E))return false}return true}).map(d=>zs(d)):c.map(d=>qs(d,d.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let E=d.type??"plugin";if(!n.types.has(E))return false;let m=d.origin??"internal";return n.origins.has(m)}),[a,n]),u=useMemo(()=>{let{types:d}=n;if(d.size===1){if(d.has("skill"))return "skills";if(d.has("mcp"))return "MCPs";if(d.has("plugin"))return "plugins"}return "items"},[n]),g=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),v=useMemo(()=>d=>d?e.find(E=>E.name===d.name&&E.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:v}}function Zs(){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 Pe();t(a),s.current||(s.current=!0,b(x.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:a.length}).catch(()=>{}));}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c]),{catalog:e,isLoading:r,error:o,refetch:c}}function Qs(){return {items:B(t=>t.installedItems)}}var Ku=S("catalog");function ea(){let e=f(_=>_.activeTab),t=f(_=>_.notification),r=f(_=>_.loading),n=f(_=>_.loadingMessage),o=f(_=>_.catalogError),i=f(_=>_.setCatalogError),s=f(_=>_.catalogFilters),c=Q(_=>_.query),{catalog:a,isLoading:l,error:u,refetch:g}=Zs(),{items:v}=Qs(),d=B(_=>_.loadFromDisk),{items:E,emptyMessage:m,getSelectedCatalogItem:h}=Ys({catalog:a,installedItems:v,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:T,closeMenu:y,selectedIndex:L,clampIndex:$,filteredItems:V}=Es({listLength:E.length}),X=V(E),$e=useMemo(()=>e!=="installed"?X:Xs(X),[e,X]),dn=useMemo(()=>e==="installed"?Ws($e):[],[e,$e]),G=$e[L]??null,w=useMemo(()=>h(G),[h,G]),{notify:ne}=ks(),{handleInstall:H,handleUninstall:j,handleToggleStatus:mn,handleUpdate:fn,handleMcpConfigUninstall:Mo}=Vs({selectedItem:G,selectedCatalogItem:w,items:E,closeMenu:y,clampIndex:$,notify:ne});return useEffect(()=>{d();},[]),useEffect(()=>{$($e.length);},[$e.length,$]),useEffect(()=>{u&&(Ku.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($r,{}),jsx(Ii,{}),jsx(Ui,{filteredItems:$e,groups:dn,emptyMessage:m}),(r||l)&&jsx(_r,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Mr,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(ji,{message:t.message,type:t.type}),T&&G&&(e==="discover"?jsx(Zi,{itemName:G.name,onInstall:H,onClose:y}):G.type==="mcp"?jsx(os,{itemName:G.name,itemScope:G.scope??"user",onUninstall:Mo,onClose:y}):jsx(ts,{itemName:G.name,itemScope:G.scope??"user",itemStatus:G.status??"enabled",updateAvailable:G.updateAvailable??false,catalogVersion:w?.version,onUninstall:j,onToggleStatus:_=>mn(_),onUpdate:fn,onClose:y})),jsx(Rr,{})]})}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(B.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 Hu=3;function ra(){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 Kr();e(a);}catch(a){r(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,r,e]);useEffect(()=>{B.getState().loadFromDisk(),s();},[s]);let c=useCallback(async()=>{let a=P.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){n(u.name,"installing");let g="",v=false;for(let d=1;d<=Hu;d++)try{await Ee(u.name),n(u.name,"success"),v=!0;break}catch(E){if(E instanceof ve){n(u.name,"success"),v=true;break}g=E instanceof Error?E.message:"Unknown error";}v||(n(u.name,"failed",g),b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:g,interface:A().interfaceType}).catch(()=>{}));}let l=it();ot("summary_review"),b(x.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),B.getState().loadFromDisk(),i(),o("summary");},[n,i,o]);return {loadStarterKits:s,installSelected:c}}var nr={cursorDelta:0,confirm:false,back:false};function na(e,t){return t.upArrow?{...nr,cursorDelta:-1}:t.downArrow?{...nr,cursorDelta:1}:t.escape?{...nr,back:true}:t.return?{...nr,confirm:true}:nr}var Vu={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}:Vu}var ia=yc.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 xo=5;function sa({onRetry:e}){let t=P(u=>u.starterKits),r=P(u=>u.selectedStarterKitIndex),n=P(u=>u.isLoadingStarterKits),o=P(u=>u.starterKitsError);if(n)return jsx(_r,{message:"Loading Starter Kits..."});if(o)return jsx(Mr,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Et,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor(xo/2)),s=Math.min(t.length,i+xo);s===t.length&&(i=Math.max(0,s-xo));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(ia,{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 la=yc.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 vo=8;function ca(){let e=P(u=>u.selectedStarterKit),t=P(u=>u.plugins),r=P(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(x.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,i=Math.max(0,r-Math.floor(vo/2)),s=Math.min(t.length,i+vo);s===t.length&&(i=Math.max(0,s-vo));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(la,{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 ep=["Retry failed","Continue anyway"];function ua({name:e,status:t,error:r}){let n=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Rc,{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=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(ua,{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(ua,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:ep.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 da(){let e=P(w=>w.step),t=P(w=>w.starterKits),r=P(w=>w.selectedStarterKitIndex),n=P(w=>w.setSelectedStarterKitIndex),o=P(w=>w.selectStarterKit),i=P(w=>w.plugins),s=P(w=>w.pluginCursorIndex),c=P(w=>w.setPluginCursorIndex),a=P(w=>w.setStep),l=P(w=>w.summaryActionIndex),u=P(w=>w.setSummaryActionIndex),g=P(w=>w.failedCount),v=P(w=>w.resetForRetry),d=P(w=>w.goBackToList),E=f(w=>w.setScreen),m=f(w=>w.setFocus),h=f(w=>w.focus),T=fe(w=>w.setJustAuthenticated),y=fe(w=>w.justAuthenticated),{loadStarterKits:L,installSelected:$}=ra(),V=useRef(false);useEffect(()=>{e==="bundleList"?(m("bundleList"),V.current||(V.current=true,ot("bundle_selection"))):m(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,m]);let X=useCallback(async()=>{let w=P.getState().selectedStarterKit;if(w){let H=await N();H&&await rt({...H,starterKit:w.slug});}b(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:it()}).catch(()=>{});let{successCount:ne}=P.getState();b(x.CLI_ONBOARDING_COMPLETED,{duration_ms:Ke(),tools_installed_count:ne}).catch(()=>{}),T(false),m("list"),E("main");},[T,m,E]),$e=useCallback(()=>{v(),$();},[v,$]),dn=useCallback(()=>{L();},[L]),G=useCallback(()=>{m("list"),E("main");},[m,E]);return useInput((w,ne)=>{if(ne.escape)Er("esc"),G();else if(ne.upArrow&&r>0)n(r-1);else if(ne.downArrow&&r<t.length-1)n(r+1);else if(ne.return&&t.length>0){let H=it();o(t[r]),ot("kit_display"),b(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:H}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((w,ne)=>{let H=na(w,ne);if(H.cursorDelta!==0){let j=s+H.cursorDelta;j>=0&&j<i.length&&c(j);}if(H.confirm){let j=P.getState().selectedStarterKit;j&&(async()=>(await N())?.starterKit!==j.slug&&b(x.CLI_KIT_ACCEPTED,{bundle_slug:j.slug}).catch(()=>{}))();let mn=it();ot("kit_confirmation"),b(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:mn}).catch(()=>{});let fn=it();ot("tool_installation"),b(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:fn}).catch(()=>{}),a("installing"),$();}if(H.back){let j=P.getState().selectedStarterKit;j&&b(x.CLI_KIT_REJECTED,{bundle_slug:j.slug}).catch(()=>{}),d();}},{isActive:h==="bundleDetail"}),useInput((w,ne)=>{if(g===0)return;let H=oa(w,ne);if(H.cursorDelta!==0){let j=l+H.cursorDelta;j>=0&&j<=1&&u(j);}H.select&&(l===0?$e():X());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx($r,{}),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(sa,{onRetry:dn}),e==="bundleDetail"&&jsx(ca,{}),(e==="installing"||e==="summary")&&jsx(pa,{onComplete:X,onRetry:$e})]}),jsx(Rr,{})]})}var op=S("app"),ip={auth:gi,bundleSetup:da,main:ea};function ga(){f.getState().setScreen("auth"),f.getState().setFocus("auth");}async function Sa(){let e=await N();if(!e){ga();return}try{await Ue();}catch(o){op.debug(`Token validation failed: ${String(o)}`),ga();return}b(x.CLI_SESSION_STARTED,{cli_version:je,os:process.platform,node_version:process.version,duration_ms:Ke(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...r}=e;fe.getState().setCredentials(r),!e.starterKit||e.starterKit.trim()===""?(f.getState().setScreen("bundleSetup"),f.getState().setFocus("bundleList")):(f.getState().setScreen("main"),f.getState().setFocus("list"));}function ha(){let{columns:e,rows:t}=useWindowSize(),r=f(i=>i.screen),n=ip[r],{pendingExit:o}=mi();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 Ce=S("auth");function xa(){Y.clearFallbackFile(),xr();}var sp=3,wa=3,Ia=` \u2139 The data collected during setup is used solely to improve
113
+ [y/N] `))return Xr.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:Mo({text:`Removing MCP "${p(e)}"...`}).start();try{let o=await le(r);return n?.stop(),o.exitCode!==0?(er(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(Vs(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),er(t,{name:e,action:"remove",message:N(o)}),1}}function qs({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:i}){let s=S("pluginHandlers"),c=f(y=>y.setLoading),{install:a,uninstall:l,toggle:u,update:g}=Hs(),v=async(y,L,$)=>{c(true,y),n();try{await L(),o(r.length),i($,"success");}catch(H){let q=H instanceof Error?H.message:"Something went wrong";s.error(`[withLoading] ${y} failed: ${q}`),i(q,"error");}finally{c(false);}};return {handleInstall:y=>{e&&t&&v(`Installing ${e.name}...`,()=>a(t,{scope:y}),"\u2713 Installed successfully");},handleUninstall:y=>{e&&v(`Uninstalling ${e.name}...`,()=>l(e.name,y),"\u2713 Uninstalled");},handleToggleStatus:y=>{if(!e)return;let L=e.status==="enabled";v(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,y),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let y=t?` to v${t.version}`:"";(async()=>{c(true,`Updating ${e.name}${y}...`),n();try{await g(e.name),o(r.length),i(`\u2713 Updated ${e.name}${y}`,"success");}catch($){if($ instanceof He)i($.message,"info");else {let H=$ instanceof Error?$.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${H}`),i(H,"error");}}finally{c(false);}})();},handleMcpConfigUninstall:y=>{e&&v(`Removing MCP ${e.name}...`,async()=>{let L=yo(e.name,y),$=await le(L);if($.exitCode!==0)throw new Error($.stderr||"MCP removal failed");K.getState().loadFromDisk();},"\u2713 MCP removed");}}}var tr=["local","project","user"],Wu=new Set(["--transport","--scope","-s"]);function Xs(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(Wu.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function rr(e,t){return t?`${e}::${t}`:e}function So(e){return e===O?Lt:lr}function Ys(e){return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author.name?p(e.author.name):e.author.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??Lt}}function Zs(e,t){let r=So(e.marketplace);return {name:p(e.name),version:e.version?p(e.version):e.version,description:e.description?p(e.description):e.description,authorName:e.author?.name?p(e.author.name):e.author?.name,status:e.status,scope:e.scope,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??r}}function Qs(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return tr.filter(r=>t.has(r)).map(r=>({scope:r,label:Rt[r].label,pathHint:Rt[r].pathHint,items:t.get(r)??[]}))}function ea(e){let t=r=>{if(!r)return 1/0;let n=tr.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function ta({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let i=useMemo(()=>new Set(t.map(d=>rr(d.name,d.author?.name))),[t]),s=useMemo(()=>new Set(t.filter(d=>d.type==="mcp").map(d=>d.name.toLowerCase())),[t]),c=useMemo(()=>{let d=new Map(e.map(E=>[rr(E.name,E.author.name),E]));return t.map(E=>{let m=d.get(rr(E.name,E.author?.name)),h=m?.version,T=!!h&&!!E.version&&Re(E.version,h);return {...E,updateAvailable:T,catalogItem:m}})},[t,e]),a=useMemo(()=>r==="discover"?e.filter(d=>{if(i.has(rr(d.name,d.author.name)))return false;if(d.type==="mcp"){let E=d.installCommand?Xs(d.installCommand)?.toLowerCase():null;if(s.has(d.name.toLowerCase())||E&&s.has(E))return false}return true}).map(d=>Ys(d)):c.map(d=>Zs(d,d.catalogItem)),[r,e,i,s,c]),l=useMemo(()=>a.filter(d=>{let E=d.type??"plugin";if(!n.types.has(E))return false;let m=d.origin??"internal";return n.origins.has(m)}),[a,n]),u=useMemo(()=>{let{types:d}=n;if(d.size===1){if(d.has("skill"))return "skills";if(d.has("mcp"))return "MCPs";if(d.has("plugin"))return "plugins"}return "items"},[n]),g=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),v=useMemo(()=>d=>d?e.find(E=>E.name===d.name&&E.author.name===d.authorName)??null:null,[e]);return {items:l,emptyMessage:g,getSelectedCatalogItem:v}}function ra(){let[e,t]=useState([]),[r,n]=useState(true),[o,i]=useState(null),s=useRef(false),c=useCallback(async()=>{n(true),i(null);try{let a=await ve();t(a),s.current||(s.current=!0,b(x.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:a.length}).catch(()=>{}));}catch(a){i(a instanceof Error?a:new Error(String(a))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c]),{catalog:e,isLoading:r,error:o,refetch:c}}function na(){return {items:K(t=>t.installedItems)}}var Qu=S("catalog");function oa(){let e=f(M=>M.activeTab),t=f(M=>M.notification),r=f(M=>M.loading),n=f(M=>M.loadingMessage),o=f(M=>M.catalogError),i=f(M=>M.setCatalogError),s=f(M=>M.catalogFilters),c=Z(M=>M.query),{catalog:a,isLoading:l,error:u,refetch:g}=ra(),{items:v}=na(),d=K(M=>M.loadFromDisk),{items:E,emptyMessage:m,getSelectedCatalogItem:h}=ta({catalog:a,installedItems:v,activeTab:e,catalogFilters:s,searchQuery:c}),{actionMenuOpen:T,closeMenu:y,selectedIndex:L,clampIndex:$,filteredItems:H}=$s({listLength:E.length}),q=H(E),Ce=useMemo(()=>e!=="installed"?q:ea(q),[e,q]),mn=useMemo(()=>e==="installed"?Qs(Ce):[],[e,Ce]),G=Ce[L]??null,w=useMemo(()=>h(G),[h,G]),{notify:re}=Ls(),{handleInstall:J,handleUninstall:B,handleToggleStatus:fn,handleUpdate:gn,handleMcpConfigUninstall:Fo}=qs({selectedItem:G,selectedCatalogItem:w,items:E,closeMenu:y,clampIndex:$,notify:re});return useEffect(()=>{d();},[]),useEffect(()=>{$(Ce.length);},[Ce.length,$]),useEffect(()=>{u&&(Qu.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(Ar,{}),jsx(Ei,{}),jsx(Ji,{filteredItems:Ce,groups:mn,emptyMessage:m}),(r||l)&&jsx(_r,{message:r?n:"Loading catalog..."}),o&&!l&&e==="discover"&&jsx(Or,{message:o,onRetry:()=>{i(null),g();},onBack:()=>i(null)}),t&&jsx(Gi,{message:t.message,type:t.type}),T&&G&&(e==="discover"?jsx(rs,{itemName:G.name,onInstall:J,onClose:y}):G.type==="mcp"?jsx(ls,{itemName:G.name,itemScope:G.scope??"user",onUninstall:Fo,onClose:y}):jsx(is,{itemName:G.name,itemScope:G.scope??"user",itemStatus:G.status??"enabled",updateAvailable:G.updateAvailable??false,catalogVersion:w?.version,onUninstall:B,onToggleStatus:M=>fn(M),onUpdate:gn,onClose:y})),jsx(Mr,{})]})}var P=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(K.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let i=t().plugins.map(s=>s.name===r?{...s,status:n,error:o}:s);e({plugins:i});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var np=3;function sa(){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 Kr();e(a);}catch(a){r(a instanceof Error?a.message:String(a));}finally{t(false);}},[t,r,e]);useEffect(()=>{K.getState().loadFromDisk(),s();},[s]);let c=useCallback(async()=>{let a=P.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of a){n(u.name,"installing");let g="",v=false;for(let d=1;d<=np;d++)try{await Pe(u.name),n(u.name,"success"),v=!0;break}catch(E){if(E instanceof be){n(u.name,"success"),v=true;break}g=E instanceof Error?E.message:"Unknown error";}v||(n(u.name,"failed",g),b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:g,interface:A().interfaceType}).catch(()=>{}));}let l=ot();nt("summary_review"),b(x.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:l}).catch(()=>{}),K.getState().loadFromDisk(),i(),o("summary");},[n,i,o]);return {loadStarterKits:s,installSelected:c}}var nr={cursorDelta:0,confirm:false,back:false};function aa(e,t){return t.upArrow?{...nr,cursorDelta:-1}:t.downArrow?{...nr,cursorDelta:1}:t.escape?{...nr,back:true}:t.return?{...nr,confirm:true}:nr}var op={cursorDelta:0,select:false};function la(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:op}var ca=$c.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 Po=5;function ua({onRetry:e}){let t=P(u=>u.starterKits),r=P(u=>u.selectedStarterKitIndex),n=P(u=>u.isLoadingStarterKits),o=P(u=>u.starterKitsError);if(n)return jsx(_r,{message:"Loading Starter Kits..."});if(o)return jsx(Or,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Pt,{message:"No Starter Kits available."});let i=Math.max(0,r-Math.floor(Po/2)),s=Math.min(t.length,i+Po);s===t.length&&(i=Math.max(0,s-Po));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(ca,{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 da=$c.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 ko=8;function ma(){let e=P(u=>u.selectedStarterKit),t=P(u=>u.plugins),r=P(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(x.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,i=Math.max(0,r-Math.floor(ko/2)),s=Math.min(t.length,i+ko);s===t.length&&(i=Math.max(0,s-ko));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(da,{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 mp=["Retry failed","Continue anyway"];function fa({name:e,status:t,error:r}){let n=p(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gc,{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 ga({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(fa,{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(fa,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:mp.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 ya(){let e=P(w=>w.step),t=P(w=>w.starterKits),r=P(w=>w.selectedStarterKitIndex),n=P(w=>w.setSelectedStarterKitIndex),o=P(w=>w.selectStarterKit),i=P(w=>w.plugins),s=P(w=>w.pluginCursorIndex),c=P(w=>w.setPluginCursorIndex),a=P(w=>w.setStep),l=P(w=>w.summaryActionIndex),u=P(w=>w.setSummaryActionIndex),g=P(w=>w.failedCount),v=P(w=>w.resetForRetry),d=P(w=>w.goBackToList),E=f(w=>w.setScreen),m=f(w=>w.setFocus),h=f(w=>w.focus),T=me(w=>w.setJustAuthenticated),y=me(w=>w.justAuthenticated),{loadStarterKits:L,installSelected:$}=sa(),H=useRef(false);useEffect(()=>{e==="bundleList"?(m("bundleList"),H.current||(H.current=true,nt("bundle_selection"))):m(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,m]);let q=useCallback(async()=>{let w=P.getState().selectedStarterKit;if(w){let J=await D();J&&await tt({...J,starterKit:w.slug});}b(x.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ot()}).catch(()=>{});let{successCount:re}=P.getState();b(x.CLI_ONBOARDING_COMPLETED,{duration_ms:Ue(),tools_installed_count:re}).catch(()=>{}),T(false),m("list"),E("main");},[T,m,E]),Ce=useCallback(()=>{v(),$();},[v,$]),mn=useCallback(()=>{L();},[L]),G=useCallback(()=>{m("list"),E("main");},[m,E]);return useInput((w,re)=>{if(re.escape)Tr("esc"),G();else if(re.upArrow&&r>0)n(r-1);else if(re.downArrow&&r<t.length-1)n(r+1);else if(re.return&&t.length>0){let J=ot();o(t[r]),nt("kit_display"),b(x.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:J}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((w,re)=>{let J=aa(w,re);if(J.cursorDelta!==0){let B=s+J.cursorDelta;B>=0&&B<i.length&&c(B);}if(J.confirm){let B=P.getState().selectedStarterKit;B&&(async()=>(await D())?.starterKit!==B.slug&&b(x.CLI_KIT_ACCEPTED,{bundle_slug:B.slug}).catch(()=>{}))();let fn=ot();nt("kit_confirmation"),b(x.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:fn}).catch(()=>{});let gn=ot();nt("tool_installation"),b(x.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:gn}).catch(()=>{}),a("installing"),$();}if(J.back){let B=P.getState().selectedStarterKit;B&&b(x.CLI_KIT_REJECTED,{bundle_slug:B.slug}).catch(()=>{}),d();}},{isActive:h==="bundleDetail"}),useInput((w,re)=>{if(g===0)return;let J=la(w,re);if(J.cursorDelta!==0){let B=l+J.cursorDelta;B>=0&&B<=1&&u(B);}J.select&&(l===0?Ce():q());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Ar,{}),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(ua,{onRetry:mn}),e==="bundleDetail"&&jsx(ma,{}),(e==="installing"||e==="summary")&&jsx(ga,{onComplete:q,onRetry:Ce})]}),jsx(Mr,{})]})}var Sp=S("app"),hp={auth:wi,bundleSetup:ya,main:oa};function wa(){f.getState().setScreen("auth"),f.getState().setFocus("auth");}async function Ia(){let e=await D();if(!e){wa();return}try{await Fe();}catch(o){Sp.debug(`Token validation failed: ${String(o)}`),wa();return}b(x.CLI_SESSION_STARTED,{cli_version:Be,os:process.platform,node_version:process.version,duration_ms:Ue(),interface:"tui"}).catch(()=>{});let{clientSecret:t,...r}=e;me.getState().setCredentials(r),!e.starterKit||e.starterKit.trim()===""?(f.getState().setScreen("bundleSetup"),f.getState().setFocus("bundleList")):(f.getState().setScreen("main"),f.getState().setFocus("list"));}function ba(){let{columns:e,rows:t}=useWindowSize(),r=f(i=>i.screen),n=hp[r],{pendingExit:o}=Si();return n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}var ke=S("auth");function Pa(){X.clearFallbackFile(),Ir();}var wp=3,va=3,Ea=` \u2139 The data collected during setup is used solely to improve
28
114
  Flow's internal tools and will not be shared externally.
29
115
  `;function sr(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===`
30
116
  `){a(),process.stdout.write(`
31
- `),r(s);return}if(u==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(s+=u,process.stdout.write(o?"*".repeat(u.length):u));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",c),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",c);})}async function ba(){for(let e=1;e<=wa;e++)try{return await Kr()}catch{if(e===wa)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function va(){let e=await ba();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
117
+ `),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 Ta(){for(let e=1;e<=va;e++)try{return await Kr()}catch{if(e===va)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function ka(){let e=await Ta();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
32
118
  `+C.cyan(" ? ")+`Starter Kit:
33
119
  `),e.forEach((t,r)=>{process.stdout.write(` ${C.cyan(`${r+1})`)} ${p(t.name)}
34
120
  `);}),process.stdout.write(`
35
121
  `);;){let t=(await sr(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
36
- `));}}async function Pa(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
122
+ `));}}async function Ca(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
37
123
  Starter kit '${p(e.name)}' has no plugins to install.
38
124
  `)),true;process.stdout.write(`
39
125
  Installing ${e.plugins.length} plugins from '${p(e.name)}'...
40
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(C.dim(` [${i}/${n}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=sp;c++)try{await Ee(o),t++,s=!0;break}catch(a){if(a instanceof ve){t++,s=true;break}}s?process.stdout.write(C.green(` done
126
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let i=t+r+1;process.stdout.write(C.dim(` [${i}/${n}] Installing ${p(o)}...`));let s=false;for(let c=1;c<=wp;c++)try{await Pe(o),t++,s=!0;break}catch(a){if(a instanceof be){t++,s=true;break}}s?process.stdout.write(C.green(` done
41
127
  `)):(r++,process.stdout.write(C.red(` failed
42
128
  `)));}return r===0?process.stdout.write(C.green(` \u2713 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed successfully.
43
129
  `)):process.stdout.write(C.yellow(` \u26A0 Starter kit '${p(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
44
- `)),r===0}async function ap(e){xa(),process.stdout.write(`
45
- `+Ia+`
46
- `),Ce.debug(`[${e.tenant}] Authenticating tenant`);try{await nt(e);}catch(t){let r=p(t instanceof Error?t.message:"unknown error");return Ce.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${r}
47
- `)),1}try{let t;if(e.starterKit){let r=await ba(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(C.red(` \u2717 Starter kit '${p(e.starterKit)}' not found.
130
+ `)),r===0}async function xp(e){Pa(),process.stdout.write(`
131
+ `+Ea+`
132
+ `),ke.debug(`[${e.tenant}] Authenticating tenant`);try{await rt(e);}catch(t){let r=p(t instanceof Error?t.message:"unknown error");return ke.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${r}
133
+ `)),1}try{let t;if(e.starterKit){let r=await Ta(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(C.red(` \u2717 Starter kit '${p(e.starterKit)}' not found.
48
134
  `)),process.stderr.write(` Available starter kits:
49
135
  `);for(let o of r)process.stderr.write(` - ${p(o.slug)} (${p(o.name)})
50
- `);return 1}t=n;}else t=await va();return await rt({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug}),await Pa(t),Ce.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${e.tenant}
136
+ `);return 1}t=n;}else t=await ka();return await tt({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug}),await Ca(t),ke.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${e.tenant}
51
137
 
52
- `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=p(t instanceof Error?t.message:"unknown error");return Ce.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${r}
53
- `)),1}}async function lp(){xa(),Ce.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
54
- `),process.stdout.write(Ia+`
55
- `);let e=(await sr(C.cyan(" ? ")+"Client ID: ")).trim(),t=(await sr(C.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await sr(C.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return Ce.error("[auth] Validation failed: all fields are required"),process.stderr.write(C.red(` \u2717 All fields are required
56
- `)),1;Ce.debug(`[${r}] Authenticating tenant`);try{await nt({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return Ce.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${i}
57
- `)),1}let n=await va();return await rt({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug}),await Pa(n),Ce.info(`[${r}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${r}
138
+ `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=p(t instanceof Error?t.message:"unknown error");return ke.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${r}
139
+ `)),1}}async function Ip(){Pa(),ke.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
140
+ `),process.stdout.write(Ea+`
141
+ `);let e=(await sr(C.cyan(" ? ")+"Client ID: ")).trim(),t=(await sr(C.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await sr(C.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return ke.error("[auth] Validation failed: all fields are required"),process.stderr.write(C.red(` \u2717 All fields are required
142
+ `)),1;ke.debug(`[${r}] Authenticating tenant`);try{await rt({clientId:e,clientSecret:t,tenant:r});}catch(o){let i=p(o instanceof Error?o.message:"unknown error");return ke.error(`[${r}] Authentication failed: ${i}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${i}
143
+ `)),1}let n=await ka();return await tt({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug}),await Ca(n),ke.info(`[${r}] Authentication successful`),process.stdout.write(C.green(` \u2713 Setup complete. Tenant: ${r}
58
144
 
59
- `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return Ce.error(`[auth] Unexpected error: ${t}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${t}
60
- `)),1}}async function Co(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return ap({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await lp()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
61
- `),130;throw t}}async function cp(){try{return process.stdout.write(`
145
+ `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=p(e instanceof Error?e.message:"unknown error");return ke.error(`[auth] Unexpected error: ${t}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${t}
146
+ `)),1}}async function Ro(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return xp({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await Ip()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
147
+ `),130;throw t}}async function bp(){try{return process.stdout.write(`
62
148
  `),(await sr(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
63
149
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
64
- `),130;throw e}}async function Ea(e){if(!await N())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
65
- `)),0;if(!e){let t=await cp();if(t!==null)return t}try{return await Zo(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
150
+ `),130;throw e}}async function $a(e){if(!await D())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
151
+ `)),0;if(!e){let t=await bp();if(t!==null)return t}try{return await ri(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
66
152
  `)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
67
- `)),1}}async function Ta(){let e=await N();return e?await It()?(process.stdout.write(`
153
+ `)),1}}async function Aa(){let e=await D();return e?await xt()?(process.stdout.write(`
68
154
  `+C.bold(` Authenticated
69
155
  `)),process.stdout.write(C.dim(" Tenant: ")+p(e.tenant)+`
70
156
  `),process.stdout.write(C.dim(" Client ID: ")+p(e.clientId)+`
71
157
  `),process.stdout.write(C.dim(" Starter Kit: ")+p(e.starterKit??"not set")+`
72
- `),process.stdout.write(C.dim(" Config: ")+p(await Qo())+`
158
+ `),process.stdout.write(C.dim(" Config: ")+p(await ni())+`
73
159
  `),process.stdout.write(`
74
- `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function up(e){let t=Te(),r;try{r=await Pe();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(vt(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Tr(["","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 pp(e){let t=Te(),r=await Pe(),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&&_e(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(vt(o),0):(Tr(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
160
+ `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function vp(e){let t=Ee(),r;try{r=await ve();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(bt(r.map(o=>({...o,installed:n.has(o.name)}))),0):(kr(["","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 Pp(e){let t=Ee(),r=await ve(),n=new Map(r.map(i=>[i.name,i])),o=t.map(i=>{let s=n.get(i.name);return s&&i.version&&s.version&&Re(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(bt(o),0):(kr(["Name","Installed","Available"],o.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
75
161
  ${o.length} plugin(s) outdated.
76
- `),0)}async function dp(e){let t=Te();if(b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return vt(t),0;let r=[];try{r=await Pe();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=tr.indexOf(i.scope??"user"),a=tr.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return Tr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=n.get(i.name),c=s?.type??"plugin",a=s?.origin??mo(i.marketplace);return [i.name??"",i.version??"n/a",yt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",kr(i.installedAt??"")]})),process.stdout.write(`
162
+ `),0)}async function Ep(e){let t=Ee();if(b(x.CLI_CATALOG_VIEWED,{interface:A().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return bt(t),0;let r=[];try{r=await ve();}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=[...t].sort((i,s)=>{let c=tr.indexOf(i.scope??"user"),a=tr.indexOf(s.scope??"user");return (c===-1?1/0:c)-(a===-1?1/0:a)});return kr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(i=>{let s=n.get(i.name),c=s?.type??"plugin",a=s?.origin??So(i.marketplace);return [i.name??"",i.version??"n/a",gt[c]?.label??"Plugin",a,i.scope??"user",i.status??"enabled",Cr(i.installedAt??"")]})),process.stdout.write(`
77
163
  ${t.length} plugin(s) installed.
78
- `),0}async function ka(e){if(!await te())return 1;try{return e.available?await up(e):e.outdated?await pp(e):await dp(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var M=S("manage");function rn(e,t){return t?Te().find(r=>r.name===e&&r.scope===t):Te().find(r=>r.name===e)}function mp(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=$o({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function fp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=p(e),c=p(co(e,r.scope));if(!await ze(`${t}Install external plugin "${s}"?
164
+ `),0}async function La(e){if(!await ee())return 1;try{return e.available?await vp(e):e.outdated?await Pp(e):await Ep(e)}catch(t){return k(t instanceof Error?t.message:"Failed to list plugins."),1}}var _=S("manage");function nn(e,t){return t?Ee().find(r=>r.name===e&&r.scope===t):Ee().find(r=>r.name===e)}function Tp(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Mo({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function kp(e,t,r,n){let o=n;if(!r.force){o?.stop();let s=p(e),c=p(fo(e,r.scope));if(!await Ve(`${t}Install external plugin "${s}"?
79
165
  This will run: ${c}
80
- [y/N] `))return M.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=$o({text:`${t}Installing ${e}...`}).start());}let i=o?mp(t,o):void 0;try{let s=await uo(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?se({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?Z({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):z(`${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?se({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function gp(e,t,r){let n=r.silent?void 0:$o({text:`${t}Installing ${e}...`}).start();if(Zt(e))return fp(e,t,r,n);try{let o=await Ee(e,r);return n?.stop(),r.silent?Z({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):z(`${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 ve)return r.silent?Z({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let i=F(o);return r.silent?se({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;I(`
81
- Installation summary: ${t} succeeded, ${r} failed`);}async function Ca(e,t={}){if(!await te())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await gp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?Z({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 $a(e,t){if(!await te())return 1;if(M.debug(`[${e}] Looking up installed plugin`),!t.force){let r=rn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;let n=p(r.name),o=r.version?p(r.version):void 0,i=t.scope?` (${t.scope})`:"";if(!await ze(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return M.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return M.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Br(e,t.scope),M.info(`[${e}] Uninstalled successfully`),z("Plugin removed successfully"),0}catch(r){return M.error(`[${e}] Failed to uninstall: ${F(r)}`),k(F(r)),1}}async function Aa(e,t={}){if(!await te())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=rn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return M.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return M.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Yt(e,"enabled",t.scope),M.info(`[${e}] Enabled successfully`),z(`${r.name} enabled successfully`),0}catch(n){return M.error(`[${e}] Failed to enable: ${F(n)}`),k(F(n)),1}}async function La(e,t={}){if(!await te())return 1;M.debug(`[${e}] Looking up installed plugin`);let r=rn(e,t.scope);if(!r)return M.error(`[${e}] Plugin is not installed`),k(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return M.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return M.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Yt(e,"disabled",t.scope),M.info(`[${e}] Disabled successfully`),z(`${r.name} disabled successfully`),0}catch(n){return M.error(`[${e}] Failed to disable: ${F(n)}`),k(F(n)),1}}async function Ra(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await Vr(e,r);return r.silent?Z({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):z(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Ve)return r.silent?Z({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=F(n);return r.silent?se({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Sp(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
82
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function hp(e,t,r){try{let n=await kt(e);_e(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return k(F(n)),1}return 0}function wp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function xp(e,t,r){let n=t.get(e.name);return n?e.version&&_e(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function Ip(e,t){try{let r=await Pe(),n=wp(r),o=0;for(let i of e)xp(i,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return k(F(r)),1}return 0}async function bp(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await Ra(e[n].name,o,t);r.push(i);}return t.silent?Z({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}:{}}))}):Sp(r),r.some(n=>!n.success)?1:0}async function _a(e,t={}){if(!await te())return 1;if(e){let o=rn(e,t.scope);return o?t.dryRun?hp(e,o.version??"",t):(await Ra(e,"",t)).success?0:1:(t.silent?se({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let n=Te().filter(o=>o.marketplace===D);return n.length===0?(t.silent?Z({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?Ip(n,t):bp(n,t)}var Ma=S("marketplace");function Pp(e){return `claude plugin marketplace add ${e}`}async function Oa(e,t){if(!await te())return 1;let r;try{r=Gr(e);}catch(i){let s=F(i);return t.silent?se({status:"error",source:e,message:s}):k(s),1}Ma.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Pp(r);if(!t.force){let i=p(r),s=p(n);if(!await ze(`Add marketplace "${i}"?
166
+ [y/N] `))return _.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Mo({text:`${t}Installing ${e}...`}).start());}let i=o?Tp(t,o):void 0;try{let s=await go(e,r.marketplaceSource,i?.callbacks,r.scope);if(i?.stopSpinner(),s.exitCode!==0){let c=s.stderr||"Command failed";return r.silent?ie({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:!1,error:c}}return r.silent?Y({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):V(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let c=N(s);return r.silent?ie({status:"error",plugin:e,message:c}):k(`${t}Failed to install "${e}": ${c}`),{name:e,success:false,error:c}}}async function Cp(e,t,r){let n=r.silent?void 0:Mo({text:`${t}Installing ${e}...`}).start();if(Zt(e))return kp(e,t,r,n);try{let o=await Pe(e,r);return n?.stop(),r.silent?Y({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):V(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof be)return r.silent?Y({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let i=N(o);return r.silent?ie({status:"error",plugin:e,message:i}):k(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function $p(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
167
+ Installation summary: ${t} succeeded, ${r} failed`);}async function Ra(e,t={}){if(!await ee())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",i=await Cp(e[n],o,t);r.push(i);}return e.length>1&&(t.silent?Y({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):$p(r)),r.some(n=>!n.success)?1:0}async function Ma(e,t){if(!await ee())return 1;if(_.debug(`[${e}] Looking up installed plugin`),!t.force){let r=nn(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 Ve(`Remove ${n} ${o?`v${o}`:"(n/a)"}${i}? [y/N] `))return _.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return _.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Jr(e,t.scope),_.info(`[${e}] Uninstalled successfully`),V("Plugin removed successfully"),0}catch(r){return _.error(`[${e}] Failed to uninstall: ${N(r)}`),k(N(r)),1}}async function _a(e,t={}){if(!await ee())return 1;_.debug(`[${e}] Looking up installed plugin`);let r=nn(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`),I(`${r.name} is already enabled`),0;try{return _.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Yt(e,"enabled",t.scope),_.info(`[${e}] Enabled successfully`),V(`${r.name} enabled successfully`),0}catch(n){return _.error(`[${e}] Failed to enable: ${N(n)}`),k(N(n)),1}}async function Oa(e,t={}){if(!await ee())return 1;_.debug(`[${e}] Looking up installed plugin`);let r=nn(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`),I(`${r.name} is already disabled`),0;try{return _.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Yt(e,"disabled",t.scope),_.info(`[${e}] Disabled successfully`),V(`${r.name} disabled successfully`),0}catch(n){return _.error(`[${e}] Failed to disable: ${N(n)}`),k(N(n)),1}}async function Da(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await Vr(e,r);return r.silent?Y({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):V(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof He)return r.silent?Y({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=N(n);return r.silent?ie({status:"error",plugin:e,message:o}):k(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Ap(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
168
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Lp(e,t,r){try{let n=await Tt(e);Re(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return k(N(n)),1}return 0}function Rp(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Mp(e,t,r){let n=t.get(e.name);return n?e.version&&Re(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function _p(e,t){try{let r=await ve(),n=Rp(r),o=0;for(let i of e)Mp(i,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return k(N(r)),1}return 0}async function Op(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,i=await Da(e[n].name,o,t);r.push(i);}return t.silent?Y({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):Ap(r),r.some(n=>!n.success)?1:0}async function Na(e,t={}){if(!await ee())return 1;if(e){let o=nn(e,t.scope);return o?t.dryRun?Lp(e,o.version??"",t):(await Da(e,"",t)).success?0:1:(t.silent?ie({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):k(`Plugin "${e}" is not installed`),1)}let n=Ee().filter(o=>o.marketplace===O);return n.length===0?(t.silent?Y({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?_p(n,t):Op(n,t)}var Fa=S("marketplace");function Np(e){return `claude plugin marketplace add ${e}`}async function Ua(e,t){if(!await ee())return 1;let r;try{r=zr(e);}catch(i){let s=N(i);return t.silent?ie({status:"error",source:e,message:s}):k(s),1}Fa.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Np(r);if(!t.force){let i=p(r),s=p(n);if(!await Ve(`Add marketplace "${i}"?
83
169
  This will run: ${s}
84
- [y/N] `))return Ma.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:$o({text:`Adding marketplace "${p(r)}"...`}).start();try{let i=await ce(n);return o?.stop(),i.exitCode!==0?(t.silent?se({status:"error",source:r,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(k(`Failed to add marketplace "${r}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&I(`stdout: ${i.stdout}`)),1):(t.silent?Z({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(z(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&I(i.stdout)),0)}catch(i){o?.stop();let s=F(i);return t.silent?se({status:"error",source:r,message:s}):k(`Failed to add marketplace "${r}": ${s}`),1}}async function Cp(){return await N()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function $p(){let e=Date.now();try{await Pe();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 Ap(){return await It()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Lp(){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 Da(){process.stdout.write(`
170
+ [y/N] `))return Fa.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:Mo({text:`Adding marketplace "${p(r)}"...`}).start();try{let i=await le(n);return o?.stop(),i.exitCode!==0?(t.silent?ie({status:"error",source:r,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(k(`Failed to add marketplace "${r}": ${i.stderr||"Command failed"}`),t.verbose&&i.stdout&&I(`stdout: ${i.stdout}`)),1):(t.silent?Y({status:"success",source:r,command:n,duration_ms:i.duration_ms}):(V(`Marketplace "${r}" added successfully`),t.verbose&&i.stdout&&I(i.stdout)),0)}catch(i){o?.stop();let s=N(i);return t.silent?ie({status:"error",source:r,message:s}):k(`Failed to add marketplace "${r}": ${s}`),1}}async function Kp(){return await D()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function jp(){let e=Date.now();try{await ve();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function Jp(){return await xt()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Hp(){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 Ba(){process.stdout.write(`
85
171
  `+C.bold(` FlowSetup CLI Diagnostics
86
172
 
87
- `));let e=[{name:"Credentials",fn:Cp},{name:"Prompt Manager",fn:$p},{name:"Valid Token",fn:Ap},{name:"Claude Code",fn:Lp}],t=true;for(let r of e){let n=await r.fn(),o="",i=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),i=C.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${p(n.message)}`;process.stdout.write(s+`
173
+ `));let e=[{name:"Credentials",fn:Kp},{name:"Prompt Manager",fn:jp},{name:"Valid Token",fn:Jp},{name:"Claude Code",fn:Hp}],t=true;for(let r of e){let n=await r.fn(),o="",i=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),i=C.red,t=false);let s=` ${o} ${i(r.name.padEnd(18))} ${p(n.message)}`;process.stdout.write(s+`
88
174
  `);}return process.stdout.write(`
89
175
  `),t?(process.stdout.write(C.green(` \u2713 All checks passed!
90
176
 
91
177
  `)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
92
178
 
93
- `)),1)}var Mp=["github.com","www.github.com"],Op=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Dp=/^([^@]+)@(.+)$/;function Np(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Ao(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 Fp(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=Ao(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=Ao(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function nn(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Np(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:")&&Mp.includes(r.hostname))return Fp(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(Op);if(i){let s=i[1],c=i[2],a=i[3],l,u=c.match(Dp);u&&(c=u[1],l=u[2]),c.endsWith(".git")&&(c=c.slice(0,-4));let g={type:"github",url:`https://github.com/${s}/${c}.git`};if(n&&(g.ref=n),l&&(g.skillFilter=l),a){let v=a.replace(/^\//,"");v&&(g.subpath=Ao(v));}return g}}return {type:"git",url:t}}function on(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}var Jp=6e4,Ye=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 sn(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Jp}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(i){await rm(r,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),c=s.includes("block timeout")||s.includes("timed out"),a=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw c?new Ye("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new Ye(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Ye(`Failed to clone ${e}: ${s}`,e,false,false)}}async function an(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 ja(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 Ro=new Set(["node_modules",".git","dist","build","__pycache__"]);function At(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Ha(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function qp(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Lo(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ar(e){try{let t=await readFile(e,"utf-8"),{data:r}=ja(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 Va(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Lo(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!Ro.has(c.name)).map(c=>Va(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function un(e,t){let r=[],n=new Set;if(t&&!qp(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Lo(o)){let s=await ar(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 Lo(l)){let u=await ar(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await Va(o);for(let c of s){let a=await ar(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function Ga(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 qa=1;function za(){return {version:qa,skills:{}}}async function pn(e){let t=wn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<qa?za():n}catch{return za()}}function Qp(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Wa(e,t){let r=wn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Qp(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
94
- `,"utf-8");}async function Xa(e,t,r){let n=await pn(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await Wa(n,r);}async function Ya(e,t){let r=await pn(t);e in r.skills&&(delete r.skills[e],await Wa(r,t));}var Za=S("skillInstaller");async function sd(e,t,r,n){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:A().interfaceType});}catch(o){Za.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function ad(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){Za.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function ld(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Ro.has(basename(r))});}async function cd(e,t,r){let n=At(e.name),o=Nt(t),i=join(o,n);if(!Ha(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 ld(e.path,i);let c=on(r)??r.url;return await Xa(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 Qa(e,t){let r=nn(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 sn(r.url,r.ref),o=n;let i=await un(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?Ga(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let g=Date.now(),v=await cd(u,t.scope,r);a.push(v);let d=Date.now()-g;v.success?await sd(u.name,t.scope,l,d):await ad(u.name,new Error(v.error??"Unknown error"));}return {source:e,results:a,discovered:i.length,installed:a.filter(u=>u.success).length,failed:a.filter(u=>!u.success).length}}finally{n&&await an(n).catch(()=>{});}}var fd=S("skills");async function gd(e){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:A().interfaceType});}catch(t){fd.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 Sd(e){let t=nn(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${p(e)}...`),r=await sn(t.url,t.ref),n=r;let o=await un(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let s=on(t)??p(e);I(`Found ${o.length} skill(s) in ${s}:
179
+ `)),1)}var zp=["github.com","www.github.com"],Wp=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,qp=/^([^@]+)@(.+)$/;function Xp(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function _o(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function Yp(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let i=t.slice(4).join("/");o.subpath=_o(i);}}else if(t.length>2){let i=t.slice(2).join("/");o.subpath=_o(i);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function on(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Xp(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:")&&zp.includes(r.hostname))return Yp(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(Wp);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 g={type:"github",url:`https://github.com/${s}/${c}.git`};if(n&&(g.ref=n),l&&(g.skillFilter=l),a){let v=a.replace(/^\//,"");v&&(g.subpath=_o(v));}return g}}return {type:"git",url:t}}function sn(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 rd=6e4,Xe=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function an(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:rd}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(i){await rm(r,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),c=s.includes("block timeout")||s.includes("timed out"),a=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw c?new Xe("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):a?new Xe(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Xe(`Failed to clone ${e}: ${s}`,e,false,false)}}async function ln(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 Ga(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 Do=new Set(["node_modules",".git","dist","build","__pycache__"]);function $t(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Wa(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 Oo(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ar(e){try{let t=await readFile(e,"utf-8"),{data:r}=Ga(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 qa(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Oo(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=n?[e]:[],s=await Promise.all(o.filter(c=>c.isDirectory()&&!Do.has(c.name)).map(c=>qa(join(e,c.name),t+1,r)));return [...i,...s.flat()]}catch{return []}}async function pn(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 Oo(o)){let s=await ar(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 Oo(l)){let u=await ar(join(l,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let s=await qa(o);for(let c of s){let a=await ar(join(c,"SKILL.md"));a&&!n.has(a.name)&&(r.push(a),n.add(a.name));}}return r}function Xa(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(i=>i===o)})}var Za=1;function Ya(){return {version:Za,skills:{}}}async function dn(e){let t=xn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Za?Ya():n}catch{return Ya()}}function dd(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Qa(e,t){let r=xn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:dd(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
180
+ `,"utf-8");}async function el(e,t,r){let n=await dn(r),o=new Date().toISOString(),i=n.skills[e];n.skills[e]={...t,installedAt:i?.installedAt??o,updatedAt:o},await Qa(n,r);}async function tl(e,t){let r=await dn(t);e in r.skills&&(delete r.skills[e],await Qa(r,t));}var rl=S("skillInstaller");async function wd(e,t,r,n){try{await b(x.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:A().interfaceType});}catch(o){rl.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function xd(e,t){try{await b(x.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:A().interfaceType});}catch(r){rl.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function Id(e,t){await cp(e,t,{recursive:true,dereference:true,filter:r=>!Do.has(basename(r))});}async function bd(e,t,r){let n=$t(e.name),o=Dt(t),i=join(o,n);if(!Wa(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 Id(e.path,i);let c=sn(r)??r.url;return await el(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 nl(e,t){let r=on(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 an(r.url,r.ref),o=n;let i=await pn(o,r.subpath),s=[...t.skillFilter??[]];r.skillFilter&&s.push(r.skillFilter);let c=s.length>0?Xa(i,s):i,a=[],l=r.ref??"latest";for(let u of c){let g=Date.now(),v=await bd(u,t.scope,r);a.push(v);let d=Date.now()-g;v.success?await wd(u.name,t.scope,l,d):await xd(u.name,new Error(v.error??"Unknown error"));}return {source:e,results:a,discovered:i.length,installed:a.filter(u=>u.success).length,failed:a.filter(u=>!u.success).length}}finally{n&&await ln(n).catch(()=>{});}}var kd=S("skills");async function Cd(e){try{await b(x.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:A().interfaceType});}catch(t){kd.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function $d(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 Ad(e){let t=on(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return k("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${p(e)}...`),r=await an(t.url,t.ref),n=r;let o=await pn(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let s=sn(t)??p(e);I(`Found ${o.length} skill(s) in ${s}:
95
181
  `);for(let c of o){let a=p(c.name),l=p(c.description);process.stdout.write(` ${C.bold(a)} ${C.dim(l)}
96
182
  `);}return process.stdout.write(`
97
- `),0}catch(n){return n instanceof Ye?k(n.message):k(n instanceof Error?n.message:String(n)),1}finally{r&&await an(r).catch(()=>{});}}function hd(e){for(let r of e.results){let n=p(r.skill);if(r.success){let o=relative(process.cwd(),r.path);z(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else k(`${n}: ${p(r.error??"unknown error")}`);}process.stdout.write(`
98
- `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${p(t)}`),e.failed>0&&k(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function tl(e,t){if(t.list)return Sd(e);let r=t.global?"global":"project";try{let n=await Qa(e,{scope:r,skillFilter:t.skill,yes:t.yes});return hd(n),n.failed>0?1:0}catch(n){return n instanceof Ye?k(n.message):k(n instanceof Error?n.message:String(n)),1}}async function rl(e){let t=Nt(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 ar(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 nl(e){let t=e.global?"global":"project",r=await rl(t),n=await pn(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[At(s.name)]?.source}));return vt(i),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
99
- `);for(let i of r){let s=n.skills[At(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?C.dim(` (${s})`):"";process.stdout.write(` ${C.bold(c)}${u}
183
+ `),0}catch(n){return n instanceof Xe?k(n.message):k(n instanceof Error?n.message:String(n)),1}finally{r&&await ln(r).catch(()=>{});}}function Ld(e){for(let r of e.results){let n=p(r.skill);if(r.success){let o=relative(process.cwd(),r.path);V(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else k(`${n}: ${p(r.error??"unknown error")}`);}process.stdout.write(`
184
+ `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${p(t)}`),e.failed>0&&k(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function il(e,t){if(t.list)return Ad(e);let r=t.global?"global":"project";try{let n=await nl(e,{scope:r,skillFilter:t.skill,yes:t.yes});return Ld(n),n.failed>0?1:0}catch(n){return n instanceof Xe?k(n.message):k(n instanceof Error?n.message:String(n)),1}}async function sl(e){let t=Dt(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let i=join(t,o.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let c=await ar(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 al(e){let t=e.global?"global":"project",r=await sl(t),n=await dn(t);if(e.json){let i=r.map(s=>({name:s.name,description:s.description,path:s.path,source:n.skills[$t(s.name)]?.source}));return bt(i),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
185
+ `);for(let i of r){let s=n.skills[$t(i.name)]?.source,c=p(i.name),a=p(i.description),l=a.length>80?a.slice(0,77)+"...":a,u=s?C.dim(` (${s})`):"";process.stdout.write(` ${C.bold(c)}${u}
100
186
  `),process.stdout.write(` ${C.dim(l)}
101
187
 
102
- `);}return 0}async function ol(e,t){let r=t.global?"global":"project";if(!e){let s=await rl(r);if(s.length===0)return I("No skills installed."),0;I("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
188
+ `);}return 0}async function ll(e,t){let r=t.global?"global":"project";if(!e){let s=await sl(r);if(s.length===0)return I("No skills installed."),0;I("Installed skills:");for(let c of s)process.stdout.write(` - ${p(c.name)}
103
189
  `);return process.stdout.write(`
104
- `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=At(e),o=Nt(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 I("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await Ya(n,r),await gd(n),z(`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",`
190
+ `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=$t(e),o=Dt(r),i=join(o,n);try{await stat(i);}catch{return k(`Skill "${p(e)}" is not installed.`),1}if(!t.force&&!await $d(`Remove skill "${p(n)}"?`))return I("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await tl(n,r),await Cd(n),V(`Skill "${p(n)}" removed.`),0}catch(s){return k(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}function cl(e){let t=new Command;t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@flow/cli v${Be}`,"-V, --version","Display the CLI version").addHelpText("after",`
105
191
  Without arguments, opens the interactive interface (TUI).
106
192
  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",`
107
193
  Examples:
108
- $ flow setup init`).action(async()=>{let a=await Co();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",`
194
+ $ flow setup init`).action(async()=>{let a=await Ro();process.exit(a);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
109
195
  Examples:
110
196
  $ flow plugin list
111
197
  $ flow plugin list --available
112
198
  $ flow plugin list --outdated
113
- $ flow plugin list --json`).action(async a=>{let l=await ka(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",`
199
+ $ flow plugin list --json`).action(async a=>{let l=await La(a);process.exit(l);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
114
200
  Examples:
115
201
  $ flow plugin install flow-adr-writer
116
202
  $ flow plugin install flow-adr-writer --scope project
@@ -118,11 +204,11 @@ Examples:
118
204
  $ flow plugin install flow-adr-writer --force
119
205
  $ flow plugin install flow-adr-writer --silent
120
206
  $ flow plugin install superpowers@claude-plugins-official
121
- $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(v=>v.trim());if(u.length===0){k("No valid plugin names provided"),O(1);return}ie("cli",{verbose:l.verbose,silent:l.silent});let g=await Ca(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",`
207
+ $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(a,l)=>{let u=a.filter(v=>v.trim());if(u.length===0){k("No valid plugin names provided"),process.exit(1);return}oe("cli",{verbose:l.verbose,silent:l.silent});let g=await Ra(u,l);process.exit(g);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
122
208
  Examples:
123
209
  $ flow plugin uninstall flow-adr-writer
124
210
  $ flow plugin uninstall flow-adr-writer --scope project
125
- $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await $a(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",`
211
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(a,l)=>{let u=await Ma(a,l);process.exit(u);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
126
212
  Examples:
127
213
  $ flow plugin update flow-adr-writer
128
214
  $ flow plugin update flow-adr-writer --scope project
@@ -131,49 +217,49 @@ Examples:
131
217
  $ flow plugin update flow-adr-writer --verbose
132
218
  $ flow plugin update flow-adr-writer --silent
133
219
  $ flow plugin update
134
- $ flow plugin update --dry-run`).action(async(a,l)=>{ie("cli",{verbose:l.verbose,silent:l.silent});let u=await _a(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",`
220
+ $ flow plugin update --dry-run`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Na(a??null,l);process.exit(u);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
135
221
  Examples:
136
222
  $ flow plugin enable flow-adr-writer
137
- $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{ie("cli");let u=await Aa(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",`
223
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(a,l)=>{oe("cli");let u=await _a(a,l);process.exit(u);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
138
224
  Examples:
139
225
  $ flow plugin disable flow-adr-writer
140
- $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{ie("cli");let u=await La(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",`
226
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(a,l)=>{oe("cli");let u=await Oa(a,l);process.exit(u);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
141
227
  Examples:
142
228
  $ flow plugin marketplace add anthropics/claude-code
143
229
  $ flow plugin marketplace add https://github.com/owner/repo
144
230
  $ flow plugin marketplace add anthropics/claude-code --force
145
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{ie("cli",{verbose:l.verbose,silent:l.silent});let u=await Oa(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",`
231
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Ua(a,l);process.exit(u);}),n.addCommand(o),t.addCommand(n);let i=new Command("mcp").description("Manage MCP servers from the Findr catalog");i.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
146
232
  Examples:
147
233
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
148
234
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
149
235
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
150
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{ie("cli",{verbose:u.verbose,silent:u.silent});let g=await Js(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",`
236
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(a,l,u)=>{oe("cli",{verbose:u.verbose,silent:u.silent});let g=await zs(a,l,u);process.exit(g);}),i.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
151
237
  Examples:
152
238
  $ flow mcp remove notion
153
239
  $ flow mcp remove notion --scope project
154
- $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{ie("cli",{verbose:l.verbose,silent:l.silent});let u=await Hs(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",`
240
+ $ flow mcp remove playwright-mcp --force`).action(async(a,l)=>{oe("cli",{verbose:l.verbose,silent:l.silent});let u=await Ws(a,l);process.exit(u);}),t.addCommand(i);let s=new Command("auth").description("Manage authentication credentials");s.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
155
241
  Examples:
156
242
  $ flow auth login
157
243
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
158
244
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
159
- $ flow auth login --verbose`).action(async a=>{ie("cli",{verbose:a.verbose});let l=await Co(a);O(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
245
+ $ flow auth login --verbose`).action(async a=>{oe("cli",{verbose:a.verbose});let l=await Ro(a);process.exit(l);}),s.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
160
246
  Examples:
161
247
  $ flow auth logout
162
- $ flow auth logout --force`).action(async a=>{let l=await Ea(a.force);O(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
248
+ $ flow auth logout --force`).action(async a=>{let l=await $a(a.force);process.exit(l);}),s.command("status").description("Display the current authentication status").addHelpText("after",`
163
249
  Examples:
164
- $ flow auth status`).action(async()=>{let a=await Ta();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",`
250
+ $ flow auth status`).action(async()=>{let a=await Aa();process.exit(a);}),t.addCommand(s);let c=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");return c.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
165
251
  Examples:
166
252
  $ flow skills add vercel-labs/agent-skills
167
253
  $ flow skills add owner/repo -g
168
254
  $ flow skills add owner/repo --skill pr-review commit
169
255
  $ flow skills add ./local/skills -y
170
- $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await tl(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",`
256
+ $ flow skills add owner/repo --list`).action(async(a,l)=>{let u=await il(a,l);process.exit(u);}),c.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
171
257
  Examples:
172
258
  $ flow skills list
173
259
  $ flow skills list -g
174
- $ flow skills list --json`).action(async a=>{let l=await nl(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",`
260
+ $ flow skills list --json`).action(async a=>{let l=await al(a);process.exit(l);}),c.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
175
261
  Examples:
176
262
  $ flow skills remove pr-review
177
- $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await ol(a,l);O(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
263
+ $ flow skills remove pr-review -g --force`).action(async(a,l)=>{let u=await ll(a,l);process.exit(u);}),t.addCommand(c),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
178
264
  Examples:
179
- $ flow health`).action(async()=>{let a=await Da();O(a);}),t}var xd=il(async()=>{ie("tui"),li("tui"),ci(),process.on("SIGINT",()=>{Ut("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Ut("sigterm").finally(()=>process.exit(143));}),await Sa(),render(jsx(ha,{}),{alternateScreen:true,exitOnCtrlC:false});});xd.parse();
265
+ $ flow health`).action(async()=>{let a=await Ba();process.exit(a);}),t}var Md=cl(async()=>{oe("tui"),di("tui"),mi(),process.on("SIGINT",()=>{Ut("sigint").finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{Ut("sigterm").finally(()=>process.exit(143));}),await Ia(),render(jsx(ba,{}),{alternateScreen:true,exitOnCtrlC:false});});Md.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciandt-flow/cli",
3
- "version": "1.4.1-beta.174",
3
+ "version": "1.4.1-beta.176",
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,7 +63,6 @@
63
63
  "ink-big-text": "2.0.0",
64
64
  "ink-gradient": "4.0.0",
65
65
  "ink-spinner": "5.0.0",
66
- "keytar": "7.9.0",
67
66
  "ky": "2.0.2",
68
67
  "proper-lockfile": "4.1.2",
69
68
  "react": "19.2.5",