@ciandt-flow/cli 2.8.0-beta.19 → 2.8.0-beta.21

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 +155 -140
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import*as mn from'crypto';import {randomUUID,createHash}from'crypto';import*as Re from'os';import Re__default,{tmpdir,homedir}from'os';import*as xe from'path';import xe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as be from'fs';import be__default,{readFileSync,mkdirSync,writeFileSync,existsSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import C from'chalk';import*as sl from'readline';import {createInterface}from'readline';import ma from'conf';import Qu,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import iy,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import hh from'jsonwebtoken';import kh from'proper-lockfile';import Yh from'ink-big-text';import Xd from'ink-spinner';import*as _t from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp}from'fs/promises';import sw from'unzipper';import {simpleGit}from'simple-git';import yl from'semver';import Jl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var lg=Object.defineProperty;var J=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var oc=(e,t)=>{for(var r in t)lg(e,r,{get:t[r],enumerable:true});};var cr,me,Vi,Zn,an,ln,sc,Hi,Qn,le,Xe,Vt,Xo,cn,un,dn,pn,V=J(()=>{"use strict";cr="FLOW",me="flow-skills",Vi="flow-cli",Zn="internal",an="external",ln={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},sc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Hi=new Set(["internal","external"]),Qn={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"}},le="flow-claude-md-setup",Xe=5,Vt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Xo="https://flow.ciandt.com",cn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,un="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",dn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,pn="Must be a valid email address (e.g. name@example.com)";});var qo,ug,ac,eo,Ji=J(()=>{"use strict";qo="aes-256-gcm",ug=16,ac=16,eo=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=mn.randomBytes(ug),n=mn.createCipheriv(qo,this.key,r,{authTagLength:ac}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:qo}}decrypt(t){if(t.algorithm!==qo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=mn.createDecipheriv(qo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:ac});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Gi(e){return e.replace(fg,"").replace(gg,"").replace(hg,"").replace(dg,"Bearer ***").replace(pg,"***").replace(mg,"***").replace(/\r\n|\r|\n/g,"\\n")}var dg,pg,mg,fg,gg,hg,Wi=J(()=>{"use strict";dg=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,pg=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,mg=/[A-Za-z0-9+/]{40,}={0,2}/g,fg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,gg=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,hg=/\x1b/g;});function Zo(e){return e||me}function lc(e,t,r){return Xi(Zo(r),e,t)}function zi(e,t){return xe.join(Re.homedir(),Dr,"plugins","marketplaces",Zo(t),"plugins","native",e)}function Qo(e){return xe.join(Re.homedir(),Dr,"plugins","marketplaces",Zo(e),".claude-plugin","marketplace.json")}function es(){return xe.join(Re.homedir(),Dr,"plugins","known_marketplaces.json")}function cc(e){return xe.join(Re.homedir(),Dr,"plugins","marketplaces",Zo(e))}function uc(){return xe.join(Re.homedir(),Yo,"cache","install.lock")}function dc(){return xe.join(Re.homedir(),Yo,"logs","flowsetup.log")}function Xi(e,t,r){return xe.join(Re.homedir(),Dr,"plugins","cache",e,t,r)}function Or(e){let t=e==="global"?Re.homedir():process.cwd();return xe.join(t,".claude","skills")}function to(e){let t=e==="global"?Re.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function ts(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join(Re.homedir(),".config","opencode","plugins")}function pc(){return xe.join(Re.homedir(),Yo,"flow-catalogs.json")}function mc(){let e=process.env.FLOW_HOME??xe.join(Re.homedir(),Yo);return xe.join(e,"config.json")}function rs(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Dr,"agents"):xe.join(Re.homedir(),Dr,"agents")}var Dr,Yo,qe=J(()=>{"use strict";V();Dr=".claude",Yo=".flow";});var yg,wg,ns,fc=J(()=>{"use strict";qe();yg=5*1024*1024,wg=3,ns=class{filePath;constructor(){this.filePath=dc(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{be.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=xe.dirname(this.filePath);be.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(be.statSync(this.filePath).size>yg){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);be.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=xe.dirname(this.filePath),r=xe.basename(this.filePath,".log"),n=be.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(wg))be.unlinkSync(xe.join(t,o));}catch{}}};});var os,gc=J(()=>{"use strict";os=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
- `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var ss,hc=J(()=>{"use strict";ss=class{write(t){process.stdout.write(t.message+`
5
- `);}};});function Yi(){return is}function yc(e){return qi.add(e),()=>{qi.delete(e);}}var is,qi,as,Zi=J(()=>{"use strict";is=[],qi=new Set;as=class{write(t){is.push(t),is.length>100&&is.shift();for(let r of qi)r();}};});function Sg(){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 je(e,t){if(e==="tui"){let r=Sg();Nr={context:e,transports:[new as,new ns],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Nr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Nr={context:e,transports:[new os("cli")],minLevel:"debug",debugModules:null}:Nr={context:e,transports:[new ss],minLevel:"info",debugModules:null};}function wc(){return Nr.transports}function Sc(e,t){let{debugModules:r,minLevel:n}=Nr;return Nr.context==="tui"&&r&&r!=="all"?r.has(t)?fn[e]>=fn.debug:fn[e]>=fn.warn:fn[e]>=fn[n]}var fn,Nr,Qi=J(()=>{"use strict";fc();gc();hc();Zi();fn={debug:0,info:1,warn:2,error:3},Nr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function ls(e,t,r){if(!Sc(e,t))return;let n={level:e,module:t,message:Gi(r),timestamp:new Date};for(let o of wc())o.write(n);}function x(e){let t=xc.get(e);if(t)return t;let r={debug:n=>ls("debug",e,n),info:n=>ls("info",e,n),warn:n=>ls("warn",e,n),error:n=>ls("error",e,n)};return xc.set(e,r),r}var xc,bc=J(()=>{"use strict";Wi();Qi();xc=new Map;});var $=J(()=>{"use strict";bc();Qi();Wi();});function xg(e){return typeof e=="object"&&e!==null&&ta in e&&e[ta]===true}function ra(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ta]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return ea.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(xg(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return ea.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return ea.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var ea,ta,na=J(()=>{"use strict";$();ea=x("encryption"),ta="__encrypted__";});var oa,vg,mt,gn,sa=J(()=>{"use strict";$();oa=promisify(execFile),vg=promisify(exec),mt=x("encryption:macos-keyvault"),gn=class{static async isAvailable(){try{let{stdout:t}=await vg("command -v security");return mt.debug(`security binary found at: ${t.trim()}`),!0}catch{return mt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{mt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await oa("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return mt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return mt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{mt.debug(`Storing secret: service=${t}, account=${r}`),await oa("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),mt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw mt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return mt.debug(`Deleting secret: service=${t}, account=${r}`),await oa("security",["delete-generic-password","-a",r,"-s",t]),mt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return mt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function y(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\x0d\x0e-\x1f\x7f]/g,"")}function te(e){process.stdout.write(C.green(` \u2713 ${y(e)}
6
- `));}function E(e){process.stderr.write(C.red(` \u2717 ${y(e)}
7
- `));}function P(e){process.stdout.write(C.cyan(` \u2139 ${y(e)}
8
- `));}function hn(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
2
+ import*as fn from'crypto';import {randomUUID,createHash}from'crypto';import*as Le from'os';import Le__default,{tmpdir,homedir}from'os';import*as xe from'path';import xe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as be from'fs';import be__default,{readFileSync,mkdirSync,writeFileSync,existsSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import C from'chalk';import*as al from'readline';import {createInterface}from'readline';import ga from'conf';import td,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import dy,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import bh from'jsonwebtoken';import Mh from'proper-lockfile';import ry from'ink-big-text';import Yd from'ink-spinner';import*as Dt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp as cp$1}from'fs/promises';import uw from'unzipper';import {simpleGit}from'simple-git';import Sl from'semver';import Wl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var mg=Object.defineProperty;var J=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var ic=(e,t)=>{for(var r in t)mg(e,r,{get:t[r],enumerable:true});};var ur,le,Ji,eo,ln,cn,ac,Gi,to,ce,Ye,Ht,Yo,un,dn,pn,mn,K=J(()=>{"use strict";ur="FLOW",le="flow-skills",Ji="flow-cli",eo="internal",ln="external",cn={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},ac={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Gi=new Set(["internal","external"]),to={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"}},ce="flow-claude-md-setup",Ye=5,Ht=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Yo="https://flow.ciandt.com",un=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,dn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",pn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,mn="Must be a valid email address (e.g. name@example.com)";});var Zo,gg,cc,ro,Wi=J(()=>{"use strict";Zo="aes-256-gcm",gg=16,cc=16,ro=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=fn.randomBytes(gg),n=fn.createCipheriv(Zo,this.key,r,{authTagLength:cc}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:Zo}}decrypt(t){if(t.algorithm!==Zo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=fn.createDecipheriv(Zo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:cc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function zi(e){return e.replace(Sg,"").replace(xg,"").replace(bg,"").replace(hg,"Bearer ***").replace(yg,"***").replace(wg,"***").replace(/\r\n|\r|\n/g,"\\n")}var hg,yg,wg,Sg,xg,bg,Xi=J(()=>{"use strict";hg=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,yg=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,wg=/[A-Za-z0-9+/]{40,}={0,2}/g,Sg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,xg=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,bg=/\x1b/g;});function es(e){return e||le}function uc(e,t,r){return Yi(es(r),e,t)}function qi(e,t){return xe.join(Le.homedir(),Or,"plugins","marketplaces",es(t),"plugins","native",e)}function ts(e){return xe.join(Le.homedir(),Or,"plugins","marketplaces",es(e),".claude-plugin","marketplace.json")}function Ur(){return xe.join(Le.homedir(),Or,"plugins","known_marketplaces.json")}function dc(e){return xe.join(Le.homedir(),Or,"plugins","marketplaces",es(e))}function pc(){return xe.join(Le.homedir(),Qo,"cache","install.lock")}function mc(){return xe.join(Le.homedir(),Qo,"logs","flowsetup.log")}function Yi(e,t,r){return xe.join(Le.homedir(),Or,"plugins","cache",e,t,r)}function Nr(e){let t=e==="global"?Le.homedir():process.cwd();return xe.join(t,".claude","skills")}function no(e){let t=e==="global"?Le.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function rs(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join(Le.homedir(),".config","opencode","plugins")}function fc(){return xe.join(Le.homedir(),Qo,"flow-catalogs.json")}function gc(){let e=process.env.FLOW_HOME??xe.join(Le.homedir(),Qo);return xe.join(e,"config.json")}function ns(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Or,"agents"):xe.join(Le.homedir(),Or,"agents")}var Or,Qo,Ke=J(()=>{"use strict";K();Or=".claude",Qo=".flow";});var Ig,vg,os,hc=J(()=>{"use strict";Ke();Ig=5*1024*1024,vg=3,os=class{filePath;constructor(){this.filePath=mc(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{be.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=xe.dirname(this.filePath);be.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(be.statSync(this.filePath).size>Ig){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);be.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=xe.dirname(this.filePath),r=xe.basename(this.filePath,".log"),n=be.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(vg))be.unlinkSync(xe.join(t,o));}catch{}}};});var ss,yc=J(()=>{"use strict";ss=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
+ `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var is,wc=J(()=>{"use strict";is=class{write(t){process.stdout.write(t.message+`
5
+ `);}};});function Qi(){return as}function Sc(e){return Zi.add(e),()=>{Zi.delete(e);}}var as,Zi,ls,ea=J(()=>{"use strict";as=[],Zi=new Set;ls=class{write(t){as.push(t),as.length>100&&as.shift();for(let r of Zi)r();}};});function Eg(){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 Ve(e,t){if(e==="tui"){let r=Eg();Fr={context:e,transports:[new ls,new os],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Fr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Fr={context:e,transports:[new ss("cli")],minLevel:"debug",debugModules:null}:Fr={context:e,transports:[new is],minLevel:"info",debugModules:null};}function xc(){return Fr.transports}function bc(e,t){let{debugModules:r,minLevel:n}=Fr;return Fr.context==="tui"&&r&&r!=="all"?r.has(t)?gn[e]>=gn.debug:gn[e]>=gn.warn:gn[e]>=gn[n]}var gn,Fr,ta=J(()=>{"use strict";hc();yc();wc();ea();gn={debug:0,info:1,warn:2,error:3},Fr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function cs(e,t,r){if(!bc(e,t))return;let n={level:e,module:t,message:zi(r),timestamp:new Date};for(let o of xc())o.write(n);}function x(e){let t=Ic.get(e);if(t)return t;let r={debug:n=>cs("debug",e,n),info:n=>cs("info",e,n),warn:n=>cs("warn",e,n),error:n=>cs("error",e,n)};return Ic.set(e,r),r}var Ic,vc=J(()=>{"use strict";Xi();ta();Ic=new Map;});var R=J(()=>{"use strict";vc();ta();Xi();});function Pg(e){return typeof e=="object"&&e!==null&&na in e&&e[na]===true}function oa(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[na]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return ra.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Pg(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return ra.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return ra.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var ra,na,sa=J(()=>{"use strict";R();ra=x("encryption"),na="__encrypted__";});var ia,kg,ft,hn,aa=J(()=>{"use strict";R();ia=promisify(execFile),kg=promisify(exec),ft=x("encryption:macos-keyvault"),hn=class{static async isAvailable(){try{let{stdout:t}=await kg("command -v security");return ft.debug(`security binary found at: ${t.trim()}`),!0}catch{return ft.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{ft.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await ia("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return ft.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ft.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{ft.debug(`Storing secret: service=${t}, account=${r}`),await ia("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),ft.debug("security add-generic-password succeeded");}catch(o){let s=o;throw ft.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return ft.debug(`Deleting secret: service=${t}, account=${r}`),await ia("security",["delete-generic-password","-a",r,"-s",t]),ft.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return ft.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function h(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\x0d\x0e-\x1f\x7f]/g,"")}function te(e){process.stdout.write(C.green(` \u2713 ${h(e)}
6
+ `));}function E(e){process.stderr.write(C.red(` \u2717 ${h(e)}
7
+ `));}function P(e){process.stdout.write(C.cyan(` \u2139 ${h(e)}
8
+ `));}function yn(e,t){let r=t.map(a=>a.map(h)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
9
9
  `),process.stdout.write(` ${C.bold(i(e))}
10
10
  `),process.stdout.write(` ${C.dim(s)}
11
11
  `);for(let a of r)process.stdout.write(` ${i(a)}
12
12
  `);process.stdout.write(`
13
- `);}function ur(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function Pe(e){process.stdout.write(JSON.stringify(e)+`
15
- `);}function Ze(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function q(e){return e instanceof Error?e.message:String(e)}function Tt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var B=J(()=>{"use strict";});async function kg(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 Ag(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var ia,aa,Cg,re,dr,la=J(()=>{"use strict";$();B();ia=promisify(execFile),aa=promisify(exec),Cg=[{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"}],re=x("encryption:linux-keyvault");dr=class e{static async isAvailable(){try{let{stdout:t}=await aa("command -v secret-tool");re.debug(`secret-tool found at: ${t.trim()}`);}catch{return re.debug("secret-tool binary not found in PATH"),!1}try{return await ia("secret-tool",["lookup","service","__flow_connectivity_check__"]),re.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(re.debug(`Secret Service D-Bus not available: ${n}`),!1):(re.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of Cg)try{return await aa(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;re.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 re.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await Ag(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return re.info(`Running: ${t.command}`),await kg("Installing secret-tool...",()=>aa(t.command)),e.isAvailable()}catch{return re.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{re.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await ia("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return re.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return re.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){re.debug(`Storing secret: service=${t}, account=${r}`),re.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),re.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),re.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(re.debug("secret-tool store succeeded"),o()):(re.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{re.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return re.debug(`Deleting secret: service=${t}, account=${r}`),await ia("secret-tool",["clear","service",t,"account",r]),re.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return re.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function ua(e,t){return `${e}:${t}`}function no(e){return e.replace(/'/g,"''")}function cs(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Og(e){return `Add-Type -TypeDefinition @'
17
- ${da}
13
+ `);}function dr(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
+ `);}function Te(e){process.stdout.write(JSON.stringify(e)+`
15
+ `);}function Qe(e){process.stderr.write(JSON.stringify(e)+`
16
+ `);}function q(e){return e instanceof Error?e.message:String(e)}function Ct(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var B=J(()=>{"use strict";});async function Mg(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 _g(e){let t=al.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var la,ca,Lg,re,pr,ua=J(()=>{"use strict";R();B();la=promisify(execFile),ca=promisify(exec),Lg=[{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"}],re=x("encryption:linux-keyvault");pr=class e{static async isAvailable(){try{let{stdout:t}=await ca("command -v secret-tool");re.debug(`secret-tool found at: ${t.trim()}`);}catch{return re.debug("secret-tool binary not found in PATH"),!1}try{return await la("secret-tool",["lookup","service","__flow_connectivity_check__"]),re.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(re.debug(`Secret Service D-Bus not available: ${n}`),!1):(re.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of Lg)try{return await ca(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;re.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 re.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await _g(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return re.info(`Running: ${t.command}`),await Mg("Installing secret-tool...",()=>ca(t.command)),e.isAvailable()}catch{return re.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{re.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await la("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return re.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return re.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){re.debug(`Storing secret: service=${t}, account=${r}`),re.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),re.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),re.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(re.debug("secret-tool store succeeded"),o()):(re.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{re.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return re.debug(`Deleting secret: service=${t}, account=${r}`),await la("secret-tool",["clear","service",t,"account",r]),re.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return re.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function pa(e,t){return `${e}:${t}`}function so(e){return e.replace(/'/g,"''")}function us(e){return ["-NoProfile","-NonInteractive","-Command",e]}function jg(e){return `Add-Type -TypeDefinition @'
17
+ ${ma}
18
18
  '@
19
- [FlowCredManager]::Read('${no(e)}')`}function Ug(e,t,r){return `Add-Type -TypeDefinition @'
20
- ${da}
19
+ [FlowCredManager]::Read('${so(e)}')`}function Kg(e,t,r){return `Add-Type -TypeDefinition @'
20
+ ${ma}
21
21
  '@
22
- [FlowCredManager]::Write('${no(e)}', '${no(t)}', '${no(r)}')`}function Ng(e){return `Add-Type -TypeDefinition @'
23
- ${da}
22
+ [FlowCredManager]::Write('${so(e)}', '${so(t)}', '${so(r)}')`}function Vg(e){return `Add-Type -TypeDefinition @'
23
+ ${ma}
24
24
  '@
25
- [FlowCredManager]::Delete('${no(e)}')`}async function us(e){return Lg("powershell.exe",e)}var Lg,ft,ca,Mg,_g,Dg,da,yn,pa=J(()=>{"use strict";$();Lg=promisify(execFile),ft=x("encryption:windows-keyvault"),ca=1,Mg=1,_g=2,Dg=3;da=`
25
+ [FlowCredManager]::Delete('${so(e)}')`}async function ds(e){return Ug("powershell.exe",e)}var Ug,gt,da,Ng,Bg,Fg,ma,wn,fa=J(()=>{"use strict";R();Ug=promisify(execFile),gt=x("encryption:windows-keyvault"),da=1,Ng=1,Bg=2,Fg=3;ma=`
26
26
  using System;
27
27
  using System.Runtime.InteropServices;
28
28
  using System.Text;
@@ -58,7 +58,7 @@ public class FlowCredManager {
58
58
 
59
59
  public static string Read(string target) {
60
60
  IntPtr credPtr;
61
- if (!CredRead(target, ${ca}, 0, out credPtr)) return "";
61
+ if (!CredRead(target, ${da}, 0, out credPtr)) return "";
62
62
  try {
63
63
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
64
64
  if (cred.CredentialBlobSize <= 0) return "";
@@ -72,7 +72,7 @@ public class FlowCredManager {
72
72
  byte[] bytes = Encoding.UTF8.GetBytes(secret);
73
73
  IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
74
74
  IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
75
- int[] persistLevels = new int[] { ${_g}, ${Dg}, ${Mg} };
75
+ int[] persistLevels = new int[] { ${Bg}, ${Fg}, ${Ng} };
76
76
  int lastErr = 0;
77
77
  try {
78
78
  foreach (int persist in persistLevels) {
@@ -80,7 +80,7 @@ public class FlowCredManager {
80
80
  try {
81
81
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
82
82
  var cred = new CREDENTIAL();
83
- cred.Type = ${ca};
83
+ cred.Type = ${da};
84
84
  cred.TargetName = targetPtr;
85
85
  cred.CredentialBlobSize = bytes.Length;
86
86
  cred.CredentialBlob = blobPtr;
@@ -98,149 +98,163 @@ public class FlowCredManager {
98
98
  }
99
99
 
100
100
  public static bool Delete(string target) {
101
- return CredDelete(target, ${ca}, 0);
101
+ return CredDelete(target, ${da}, 0);
102
102
  }
103
103
  }
104
- `;yn=class{static async isAvailable(){try{let{stdout:t}=await us(cs('Write-Output "ok"')),r=t.trim()==="ok";return ft.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
- `)[0]:"unknown error";return ft.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=ua(t,r);ft.debug(`Looking up secret: target=${n}`);let o=Og(n),{stdout:s}=await us(cs(o)),i=s.trim();return ft.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
- `)[0]:"unknown error";return ft.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=ua(t,r);ft.debug(`Storing secret: target=${o}`);let s=Ug(o,n,r),{stdout:i}=await us(cs(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];ft.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
107
- `)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw ft.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=ua(t,r);ft.debug(`Deleting secret: target=${n}`);let o=Ng(n),{stdout:s}=await us(cs(o)),i=s.trim()==="True";return ft.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
- `)[0]:"unknown error";return ft.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Kg(){let e=`${Re.hostname()}${Re.userInfo().username}`;return mn.scryptSync(e,Fg,Bg)}function Vg(){let e=Kg(),t=new eo(e),r=ra(t);return new ma({projectName:fa,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function ds(){return ps||(ps=Vg()),ps}var Bg,Fg,fa,jg,ps,Ke,oo=J(()=>{"use strict";Ji();na();Bg=32,Fg="flow-plugins-cli-fallback",fa="flow-plugins-cli-fallback",jg={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)"};ps=null;Ke=class{warned=!1;async getSecret(t,r){return ds().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=jg[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
104
+ `;wn=class{static async isAvailable(){try{let{stdout:t}=await ds(us('Write-Output "ok"')),r=t.trim()==="ok";return gt.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
+ `)[0]:"unknown error";return gt.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=pa(t,r);gt.debug(`Looking up secret: target=${n}`);let o=jg(n),{stdout:s}=await ds(us(o)),i=s.trim();return gt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
+ `)[0]:"unknown error";return gt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=pa(t,r);gt.debug(`Storing secret: target=${o}`);let s=Kg(o,n,r),{stdout:i}=await ds(us(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];gt.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
107
+ `)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw gt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=pa(t,r);gt.debug(`Deleting secret: target=${n}`);let o=Vg(n),{stdout:s}=await ds(us(o)),i=s.trim()==="True";return gt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
+ `)[0]:"unknown error";return gt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Wg(){let e=`${Le.hostname()}${Le.userInfo().username}`;return fn.scryptSync(e,Jg,Hg)}function zg(){let e=Wg(),t=new ro(e),r=oa(t);return new ga({projectName:ha,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function ps(){return ms||(ms=zg()),ms}var Hg,Jg,ha,Gg,ms,He,io=J(()=>{"use strict";Wi();sa();Hg=32,Jg="flow-plugins-cli-fallback",ha="flow-plugins-cli-fallback",Gg={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)"};ms=null;He=class{warned=!1;async getSecret(t,r){return ps().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Gg[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
109
109
  using a machine-derived key. For stronger security, ${o}.
110
- `),this.warned=!0;}ds().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=ds(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return ds().path}static hasExistingData(){try{let t=new ma({projectName:fa});return be.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ma({projectName:fa});be.rmSync(t.path,{force:!0});}catch{}ps=null;}};});async function ga(){if(Ke.hasExistingData())return new Ke;switch(process.platform){case "darwin":return await gn.isAvailable()?new gn:new Ke;case "linux":return await dr.isAvailable()?new dr:await dr.ensureInstalled()?new dr:new Ke;case "win32":return await yn.isAvailable()?new yn:new Ke;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Tc=J(()=>{"use strict";sa();la();pa();oo();});var Cc=J(()=>{"use strict";Ji();na();Tc();sa();la();pa();oo();});async function pr(){return gs||(gs=ga()),gs}function hs(){gs=null;}async function Y(){let t=await(await pr()).getSecret(Ht,ha);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function mr(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 kc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await pr()).setSecret(Ht,ha,JSON.stringify(e));}async function Ac(){let e=await pr();await e.deleteSecret(Ht,ha),await e.deleteSecret(Ht,ya),await e.deleteSecret(Ht,wa);}async function $c(){return (await pr()).getStoragePath()}async function Rc(e){await(await pr()).setSecret(Ht,ya,JSON.stringify(e));}async function ys(){let t=await(await pr()).getSecret(Ht,ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ws(e){await(await pr()).setSecret(Ht,wa,JSON.stringify(e));}async function wn(){let t=await(await pr()).getSecret(Ht,wa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function fr(){let e=await ys();return e?new Date(e.expiresAt)>new Date:false}function Ct(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,kc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var kc,Ht,ha,ya,wa,gs,Ie=J(()=>{"use strict";Cc();$();kc=x("config:credentials"),Ht="flow-plugins-cli",ha="credentials",ya="token-cache",wa="user-info",gs=null;});function Sn(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 Ss=J(()=>{"use strict";});function Hg(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 Sa(e){if(Lc.some(r=>r.test(e)))return true;let t=Hg(e);return !!(t&&Lc.some(r=>r.test(t)))}function Jg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function kt(e,t){let r=Jg(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(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Sa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Lc,Br=J(()=>{"use strict";Lc=[/^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\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function zg(e){if(!Vt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Xg(e){if(e instanceof HTTPError){let t=e.response.status;xa.debug(`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&&Mc[r]?new Error(Mc[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?(xa.debug(`Non-HTTP error during authentication: ${e.message}`),e):(xa.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Fr(e){let t=kt("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");zg(e.tenant);let r;try{r=await Qu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Xg(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await mr(e),await Rc({accessToken:r.access_token,expiresAt:n});let o=Sn(r.access_token);await ws({sub:o.sub,name:o.name,email:o.email});}var xa,Mc,xs=J(()=>{"use strict";Ie();Ss();Br();$();V();xa=x("api:auth");Mc={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 At(){if(await fr()){let n=await ys();if(n)return n.accessToken}_c.debug("Token expired or missing, re-authenticating...");let t=await Y();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ke.clearFallbackFile(),hs(),await Fr(t);let r=await ys();if(!r)throw new Error("Authentication succeeded but token was not persisted");return _c.debug("Token refreshed successfully"),r.accessToken}var _c,xn=J(()=>{"use strict";Ie();xs();oo();$();_c=x("lib:tokenProvider");});function Wt(){return Qu.create({prefix:kt("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await At();e.headers.set("Authorization",`Bearer ${t}`);let r=await Y();r?.tenant&&Vt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var xo=J(()=>{"use strict";Br();Ie();xn();V();});function kn(e,t){let r=Wt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function An(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Va=J(()=>{"use strict";xo();});function bo(e){if(!e||!Wy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function $n(e){return zy.test(e)}function Rn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Ja(e){if(!Xy.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.`)}function Ln(e,t){let r=Rn(e);Ja(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function Xs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!qy.test(t)&&!Yy.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Wy,zy,Xy,qy,Yy,Er=J(()=>{"use strict";Wy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;zy=/^[^@]+@[^@]+$/;Xy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;qy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,Yy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Xu={};oc(Xu,{FlowApiAdapter:()=>Mn});var Zy,Mn,Ga=J(()=>{"use strict";xo();Va();$();Er();Zy=x("catalog.flow-api"),Mn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await kn("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await An(t);if(r)throw new Error(r);if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${n}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){bo(t);try{return await kn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await An(r);if(n)throw new Error(n);if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${o}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await Wt().head("v1/plugins/catalog"),Zy.debug("ping ok"),!0}catch{return !1}}};});function ew(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Yu(){return qu??=ew(),qu}var qu,Zu=J(()=>{"use strict";});var td={};oc(td,{GitRepoAdapter:()=>_n});function ed(e,t){if(!tw.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var tw,_n,Wa=J(()=>{"use strict";Zu();Br();tw=/^[a-zA-Z0-9_.-]+$/;_n=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Sa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return ed(a,"owner"),ed(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await Qu.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await Qu.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Yu();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});V();var ic=new Set(["skill","mcp","bundle","plugin"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(ic),origins:new Set(Hi)},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:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal: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(ic)},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(Hi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ie();xn();Ss();V();Br();$();var bs=x("api:metrics");function Dc(){return kt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Oc(e,t,r){return Qu.post(e,{json:t,headers:r})}async function Yg(e){let t=await wn();if(t)return t;let r=Sn(e),n={sub:r.sub,name:r.name,email:r.email};return await ws(n),n}async function I(e,t){let r=await At(),n=await Yg(r),o=await Y();if(!Vt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Vi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Oc(Dc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),bs.debug(`Metrics event sent: ${e}`);}catch(i){throw bs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Uc(e,t,r){try{let n=r&&Vt.test(r)?r:"unknown",o={action:e,booster:Vi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Oc(Dc(),o,{FlowTenant:n}),bs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){bs.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var Zg={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},gt={...Zg};function Nc(e){let t=Date.now();gt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function jr(e){gt.currentStep=e,gt.stepStart=Date.now();}function Z(){return {...gt}}function gr(){return gt.sessionStart===0?0:Date.now()-gt.sessionStart}function Kr(){return gt.stepStart===0?0:Date.now()-gt.stepStart}function Bc(){gt.tuiSessionStart=Date.now();}function Fc(){return gt.tuiSessionStart===0?0:Date.now()-gt.tuiSessionStart}$();var Qg=3e3,eh=x("abandonment");async function Is(e){let{currentStep:t,sessionStart:r}=Z();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:gr()};try{await Promise.race([I(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Qg))]);}catch(o){eh.warn(`Abandonment event failed: ${String(o)}`);}}function jc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}$();var th=3e3,rh=x("session-end");async function io(e,t,r){let n=Fc(),s=[I(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Is(e));try{await jc(Promise.all(s).then(()=>{}),th);}catch(i){rh.warn(`Session end event failed: ${String(i)}`);}}var ih=2e3;function Vc(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),io("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},ih);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var uh=16;function Hc({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=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(uh)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}V();function Jc({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();dn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:pn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}V();function Gc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[cr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}V();function Wc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[cr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var Qe=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})}));xs();V();function Jr(){return xe__default.join(Re__default.homedir(),".claude","settings.json")}function Xc(e){return `${(e&&e.trim().length>0?e.trim():Xo).replace(/\/+$/,"")}/flow-litellm/`}function fo(){let e=Jr();if(!be__default.existsSync(e))return {status:"missing"};let t=be__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Es(e){let t=Jr();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;be__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,t);}function qc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function Ca(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function Yc(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var yh=3600,Gr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function go(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function wh(e){return hh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:yh})}function Ps(e,t={}){let r=fo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Gr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Ca(r.settings):null,s=r.status==="ok"?Yc(r.settings):null,i=t.jwtOverride??wh(e),a=Xc(e.customUrl),l=qc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Ts(e){Es(e.merged);}function Zc(){let e=fo();return e.status!=="ok"?false:Ca(e.settings)!==null}Ie();qe();function Sh(){let e=mc();if(!be__default.existsSync(e))return {};try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return {}}}var ka=null;function xh(){return ka===null&&(ka=Sh()),ka}function wr(){return !!xh().ENABLE_EXPERIMENTAL_BETAS}V();function Eh(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function eu(e){let t=Eh();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Cs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=xe__default.join(Re__default.homedir(),".claude","settings.json"),r=be__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??Xo),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},Ph={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},se=wr()?[Cs,Ph]:[Cs];Ie();$();var Ah=x("moduleState");function As(){let e=process.env.FLOW_HOME??xe__default.join(Re__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var $h={retries:5,minTimeout:50};async function tu(e,t){be__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await kh.lock(e+".lock",{realpath:false,retries:$h});try{return await t()}finally{await r();}}function ru(){let e=As();if(!be__default.existsSync(e))return [];try{let t=JSON.parse(be__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Ah.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),be__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return be__default.rmSync(e,{force:true}),[]}}function Wr(){return ru()}function nu(e){let t=As();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};be__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,t);}function et(e){return Wr().find(t=>t.alias===e)??null}async function ht(e){let t=As();await tu(t,async()=>{let r=ru(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,nu(r);});}async function zr(){let e=As();be__default.existsSync(e)||await tu(e,async()=>{be__default.existsSync(e)||nu([]);});}var Mh=promisify(execFile);function Sr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Rt(e){let t=process.platform==="win32"?"where":"which";try{return await Mh(t,[e]),!0}catch{return false}}function Jt(){return process.platform==="win32"?"npm.cmd":"npm"}var ou=promisify(execFile),In=class{type="npm";async isAvailable(){return Rt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Sr(t,"npm");if(!r)return null;try{let{stdout:n}=await ou(Jt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=Sr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await ou(Jt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var $s=promisify(execFile),Nh=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Rs=class{type="homebrew";async isAvailable(){return Rt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Sr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Sr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await $s("brew",["tap",o.tap]),await $s("brew",["trust",o.tap])),await $s("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await $s("brew",["list","--versions",t]),n=r.trim().match(Nh);return n?n[2]:null}catch{return null}}};var vn=promisify(execFile),iu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function au(){let e=process.env.FLOW_HOME??xe__default.join(Re__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ls=class{type="curl";async isAvailable(){return Rt("curl")}async install(t){let r=Date.now(),n=Sr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=xe__default.join(au(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await vn(n,["--version"]),s=o.match(iu);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=xe__default.join(Re__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await vn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{be__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return be__default.chmodSync(s,448),await vn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{be__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=au(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(be__default.mkdirSync(s,{recursive:!0}),a=!0,await vn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return be__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}be__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await vn(i,["--version"]),c=u.match(iu);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{be__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=xe__default.join(Re__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await vn("curl",["-L","--fail","-o",n,r]);let o=be__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=be__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{be__default.unlinkSync(n);}catch{}}}};$();var lu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(lu=e.version);}catch{}var ce=lu;var Te=x("moduleInstaller");function Mt(e){switch(e){case "npm":return new In;case "homebrew":return new Rs;case "curl":return new Ls}}async function ho(e,t,r){try{await I(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Te.warn(`Failed to emit install failed event: ${String(n)}`);}}async function br(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await ho(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await ho(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await ho(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Mt(r),u=false;try{u=await l.isAvailable();}catch(d){Te.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await ho(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await I(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ce,trigger:t});}catch(d){Te.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Te.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await ht({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await I(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Te.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Jh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await ho(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Jh(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await Y(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Te.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Te.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Te.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Te.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Ms(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Mt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await I(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ce,trigger:"command"});}catch(a){Te.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Te.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await ht({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await I(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Te.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await I(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Te.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await I(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Te.warn(`Failed to emit update failed event: ${String(a)}`);}return i}$();var _s=x("flowAiObsSetup");async function Ds(e,t){try{if(!await new In().isAvailable().catch(()=>!1))return _s.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await br(Cs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(_s.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(_s.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return _s.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}$();function cu(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 Gh=x("useAuthSetup");function uu(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:v}=Qe(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},M=()=>{I(b.CLI_SESSION_STARTED,{cli_version:ce,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});},T=async K=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{K&&Ts(K),await mr(z);}catch(G){l(G instanceof Error?G.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:A,...N}=z;w(N),v(true),M(),await Ds(n.current,o.current).catch(G=>Gh.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Os({starterKit:N.starterKit});},R=async()=>T(),_=async K=>T(K),O=K=>{try{let z={...r.current,customUrl:n.current??void 0};return Ps(z,{allowOverwriteMalformed:K,jwtOverride:e.trim()})}catch(z){return z instanceof Gr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},ee=()=>{let K=O(true);K&&(f(K),_(K));},k=async()=>{let K=e.trim();if(!K){i("This field is required");return}let z;try{z=go(K);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=z,m("customUrl");},H=K=>{n.current=K,m("email");},Q=K=>{o.current=K,j();},j=async()=>{let K=n.current;K&&Ct(K),c(true),l(null),h.current+=1;try{await Fr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),Uc(b.CLI_AUTH_FAILED,{error_code:cu(z),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:D,handleSubmit:k,goToEmailStep:H,handleEmailConfirm:Q,commitAndProceed:_,skipJwtAndProceed:R,planPersistOverwrite:ee}}V();B();function du(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=uu(),[g,w]=useState("confirm"),[v,D]=useState(""),M=useRef(""),[T,R]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),M.current="",D(""),R(false));},[o]),useInput((_,O)=>{if(!(n||i.current)){if(o==="preview"){O.return&&s?p(s):O.escape?f():_==="q"&&u();return}if(o==="malformedConfirm"){O.return?h():O.escape&&u();return}if(o==="customUrl"){if(g==="confirm")_==="y"||_==="Y"?w("input"):(_==="n"||_==="N"||O.return)&&d(null);else if(O.escape)M.current="",D(""),w("confirm");else if(O.return){let ee=M.current.trim();ee.length>0&&cn.test(ee)?(R(false),d(ee)):ee.length>0&&R(true);}else O.backspace||O.delete?(M.current=M.current.slice(0,-1),D(M.current)):_&&!O.ctrl&&!O.meta&&(M.current=M.current+_,D(M.current),R(false));return}o!=="email"&&O.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[cr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),T&&jsx(Text,{color:"red",children:un}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[cr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Jc,{onConfirm:m})]}):o==="preview"&&s?jsx(Gc,{plan:s}):o==="malformedConfirm"?jsx(Wc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[cr," \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:jsx(Box,{marginBottom:1,children:jsx(Hc,{label:"JWT",value:e,onChange:_=>{a(_),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Pn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Yh,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ce]})})]})}var gu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ne=wr()?gu:gu.slice(0,3);function Zh(e){return ne.findIndex(t=>t.id===e)}function Ra(e,t,r){let n=Zh(r.activeTab);if(t.rightArrow||t.tab){let o=ne[(n+1)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ne[(n-1+ne.length)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ne[n]?.focus??"list"}]:[]}var wu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Su({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ne.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${wu[r]} (${e})`:wu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ve=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function bu(){let e=S(i=>i.focus),t=Ve(i=>i.query),r=Ve(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=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:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}V();var ry=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...ln[e]})),ny=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...sc[e]}));function Iu(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),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"]})]}),ry.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"]})]}),ny.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)})]})}V();function vu({type:e}){let{label:t,color:r}=ln[e];return jsx(Text,{color:r,children:t})}V();function Tu({origin:e}){return e===Zn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}B();var Ns=iy.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(vu,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Tu,{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 ",Tt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Tn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}V();function Au({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Tn,{message:t});let n=Math.max(0,r-Math.floor(Xe/2)),o=Math.min(e.length,n+Xe);o===e.length&&(n=Math.max(0,o-Xe));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Ns,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Lu({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}V();function _u({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(Tn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Xe/2)),u=Math.min(n.length,l+Xe);u===n.length&&(l=Math.max(0,u-Xe));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Lu,{label:p.label,pathHint:p.pathHint},p.key):jsx(Ns,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var fy={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function gy({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(bu,{}),jsx(Iu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:fy[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(_u,{groups:n,emptyMessage:r}):jsx(Au,{items:e,emptyMessage:r})]})}function Du({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(gy,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var wy={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=Bundle | 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",starterKitList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",starterKitDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",moduleSetup:"\u2191\u2193: navigate | Space: toggle | Tab: change method | Enter: confirm",marketplaces:"\u2191\u2193: navigate | a: add catalog | d: remove catalog | r: refresh | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",verify:"\u2191\u2193: navigate | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleInstallProgress:"Enter/Esc: back to catalog"};function Bs(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[wy[e],t?" | Ctrl+D: debug log":""]})})}B();function Ou({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"," ",y(e)]})}):null}function Fs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Na(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Fu=20;function js(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Fu),s="\u2588".repeat(o)+"\u2591".repeat(Fu-o),i=`${Na(e)} / ${Na(t)}`;return {bar:s,percent:n,label:i}}function Ks({received:e,total:t}){let{bar:r,percent:n,label:o}=js(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Vs({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 tt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="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((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}V();var Ka=Object.entries(Qn),Hu=[...Ka.map(([,e])=>e.actionLabel),"Cancel"],Ju=Object.fromEntries(Ka.map(([,e])=>[e.actionLabel,e.description]));function Gu(e){let t=Ka.find(([,r])=>r.actionLabel===e);return t?t[0]:null}$();var My=x("provider.registry"),_y=3e4,Js=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+_y}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&My.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Dy={user:"global",project:"project",local:"local"};function Gs(e){return e?Dy[e]:"global"}var He=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},vr=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};xo();Va();$();var Ny=x("catalog.registry"),Ws=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);Ny.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};qe();var Gy={retries:5,minTimeout:50};async function Ha(e,t){mkdirSync(dirname(e),{recursive:true});let r=await kh.lock(e+".lock",{realpath:false,retries:Gy});try{return await t()}finally{await r();}}var zs=class{filePath;constructor(t){this.filePath=t??pc();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await Ha(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await Ha(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ha(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};Ga();var ue=new Ws,zt=new zs,rw=["flow-harness"];function nw(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?rw:e.split(",").map(t=>t.trim()).filter(Boolean)}ue.register(new Mn);for(let e of nw())ue.register(new Mn(e));var rd=false;async function nd(){if(rd)return;rd=true;let e=await zt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Wa(),td));for(let r of e)ue.register(new t(r.id,r.name,r.source));}Er();var od=2;async function Xt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Ga(),Xu));return new t(e).fetchItems()}return ue.fetchAll()}async function sd(){return ue.fetchAllWithErrors()}async function Dn(e,t){bo(e);try{return await kn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await An(r);throw n?new Error(n):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):r.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${r.message}`):r}}async function id(e,t,r){bo(e);try{let n=await kn(`v1/plugins/${e}/archive`,r),o=n.headers.get("x-archive-size"),s=o?Number(o):NaN,i=Number.isFinite(s)&&s>0?s:0,a=i>0,l=n.body;if(!l)throw new Error("Failed to download plugin: response has no body");let u=l.getReader(),c=[],d=0;for(;;){let{done:m,value:p}=await u.read();if(m)break;if(d+=p.byteLength,a&&d>i*od)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*od}`);c.push(p),a&&t?.(d,i);}return Buffer.concat(c)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await An(n);throw o?new Error(o):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`):n}}async function qs(){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}}qe();qe();async function ad(e,t){let r=xe.resolve(t);await _t.mkdir(r,{recursive:true});let n=xe.join(xe.dirname(r),`${randomUUID()}.zip`);try{await _t.writeFile(n,e);let o=await sw.Open.file(n),s=xe.normalize(r+xe.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=xe.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(xe.resolve(xe.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await _t.unlink(n);}catch{}}}async function za(e){await _t.rm(e,{recursive:true,force:true});}async function Pr(){let e=uc();await _t.mkdir(xe.dirname(e),{recursive:true});try{await _t.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await kh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}qe();V();function lw(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||me,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ud(e){let t=Qo(e);if(!be__default.existsSync(t))return null;try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return null}}function cw(e){let t=ud(e);if(t)return t;let r=lw(e),n=Qo(e);return be__default.mkdirSync(xe__default.dirname(n),{recursive:true}),Xa(r,e),r}function Xa(e,t){let r=Qo(t),n=`${r}.${randomUUID()}.tmp`;be__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(n,r);}function uw(e){let t=e||me,r=es(),n={};try{be__default.existsSync(r)&&(n=JSON.parse(be__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:cc(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;be__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(o,r);}function dd(e,t,r){xt(e.name),uw(r);let n=zi(e.name,r);be__default.mkdirSync(xe__default.dirname(n),{recursive:true});try{be__default.lstatSync(n),be__default.rmSync(n,{recursive:!0,force:!0});}catch{}be__default.cpSync(t,n,{recursive:true,dereference:true});let o=cw(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Xa(o,r));}function qa(e,t){xt(e);let r=zi(e,t);try{be__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=ud(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Xa(n,t);}B();$();var pw=x("mcpConfigReader"),mw=500,fw=512;function gw(){return xe__default.join(Re__default.homedir(),".claude.json")}function hw(){return xe__default.join(process.cwd(),".mcp.json")}function md(e){if(!be__default.existsSync(e))return null;try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return pw.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ya(e){if(!Io(e))return {};let t=e.mcpServers;return Io(t)?t:{}}function Za(e,t){return Object.keys(e).slice(0,mw).map(n=>({name:y(n.slice(0,fw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function gd(){let e=[],t=gw(),r=md(t);if(Io(r)){let a=r,l=Ya(a);e.push(...Za(l,"user"));let u=process.cwd();if(Io(a.projects)){let c=a.projects[u];if(Io(c)){let d=Ya(c);e.push(...Za(d,"local"));}}}let n=hw(),o=md(n),s=Ya(o);e.push(...Za(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}$();var rt=x("storage");async function ww(e,t,r){try{await I(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Z().interfaceType});}catch(n){rt.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Sw(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;I(n,{tool_id:e,source:r,interface:Z().interfaceType}).catch(o=>rt.warn(`Failed to send ${t} metrics: ${String(o)}`));}function rl(){return xe__default.join(Re__default.homedir(),".claude","plugins","installed_plugins.json")}function xw(){return xe__default.join(Re__default.homedir(),".claude","plugins")}function Ys(e){let t;try{t=be__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(xw()),n=xe__default.resolve(xe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+xe__default.sep),s=t.startsWith(n+xe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function yd(e="user"){return e==="local"?xe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?xe__default.join(process.cwd(),".claude","settings.json"):xe__default.join(Re__default.homedir(),".claude","settings.json")}function ot(){let e=rl();if(!be__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function nl(){let e=rl();try{let t=await be__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function bw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function wd(e,t){try{be__default.mkdirSync(xe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;be__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,e);}catch(r){throw bw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function nt(e){wd(rl(),e);}function vo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Iw(e,t){let r=xe__default.join(e,".claude-plugin"),n=xe__default.join(r,"plugin.json");if(be__default.existsSync(n))try{return JSON.parse(be__default.readFileSync(n,"utf-8"))}catch{return null}let o=xe__default.join(r,"marketplace.json");if(be__default.existsSync(o))try{let s=JSON.parse(be__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ol(e="user"){let t=yd(e);if(!be__default.existsSync(t))return {};try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return {}}}function Sd(e,t="user"){wd(yd(t),e);}function vw(e,t){let{name:r,marketplace:n}=vo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vo(i).name===r)[0],!o)throw rt.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Ew(e,t){let{name:r,marketplace:n}=vo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vo(i).name===r)[0],o?{key:o,name:r}:null}function Qa(e="user"){return ol(e).enabledPlugins??{}}function el(e,t="user"){let r=ol(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Sd(r,t);}function Eo(e,t,r="user"){let n=ol(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Sd(n,r);}function Pw(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function ie(){let e=ot(),t=Qa(),r=Qa("project"),n=Qa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=vo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return Pw(p).map(h=>{let g=Iw(h.installPath,d),v=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:v===false?"disabled":"enabled"}})}),i=gd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function hd(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Po(e,t){rt.debug(`[${e}] Acquiring lock to uninstall`);let r=await Pr();try{let n=ot(),o=Ew(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:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);rt.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Ys(l.installPath);let u=xe__default.dirname(l.installPath);Ys(u),rt.debug(`[${i}] Removing directory: ${u}`),be__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;nt({...n,plugins:m}),el(s,t),qa(i,hd(s));}else n.plugins[s]=c,nt(n),el(s,t);}else {rt.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Ys(c.installPath);let d=xe__default.dirname(c.installPath);Ys(d),rt.debug(`[${i}] Removing directory: ${d}`),be__default.rmSync(d,{recursive:!0,force:!0}),el(s,c.scope);}qa(i,hd(s));let{[s]:l,...u}=n.plugins;nt({...n,plugins:u});}await ww(i,a[0].origin??"internal",a[0].type??"skill"),rt.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function To(e,t,r){rt.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Pr();try{let o=ot(),{key:s,name:i}=vw(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";rt.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Eo(s,t==="enabled",l),Sw(i,t,u),rt.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}V();$();var Tw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Cw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function xt(e){if(!Tw.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function kw(e){if(!Cw.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 Tr=x("installer");function Aw(e,t,r){let n=`${e}@${r||me}`,s=ot().plugins[n];if(s&&!t)throw new He(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function $w(e,t,r){r&&await za(t);try{Tr.debug(`[${t}] Extracting archive...`),await ad(e,t);}catch(n){throw await za(t),n}}function Rw(e,t,r,n,o,s="claude-code",i){let a=ot(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],nt(a),Eo(e,true,n);}async function Lw(e,t,r,n,o,s){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Z().interfaceType});}catch(i){Tr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Mw(e,t,r,n){try{await I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Z().interfaceType});}catch(o){Tr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function _e(e,t={}){let r=Date.now(),n=null;try{Tr.debug(`[${e}] Acquiring lock...`),n=await Pr();let{pluginKey:o,alreadyInstalled:s}=Aw(e,t.force,t.source),{source:i}=t;Tr.debug(`[${e}] Fetching manifest...`);let a=await Dn(e,i);xt(a.name),kw(a.version),Tr.debug(`[${e}] Downloading archive...`);let l=await id(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=lc(a.name,a.version,t.source);await $w(l,d,!!s&&!!t.force),Rw(o,d,a.version,u,"internal",t.providerId,c),dd(a,d,t.source);let m=Date.now()-r;Tr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await Lw(a.name,a.version,m,Gs(u),"internal",c),p}catch(o){throw await Mw(e,o,"internal",t.type??"skill"),Tr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}$();B();Ie();xn();$();var _w=x("commands:helpers");async function de(){let e=await Y();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&Ct(e.customUrl);try{await At();}catch(t){return _w.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function st(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function xd(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}Er();var Un=x("claudeProxy"),cl="claude ",bd="flow ",il=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},On=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";}},Dw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ow=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Uw={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Nw=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Bw=/^(flow|claude)\s+auth\s+login(\s|$)/,Id=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function vd(e){return Id.test(e.trim())}function Fw(e){return Id.exec(e.trim())?.[2]??""}async function Ed(e){let t=Fw(e);Ja(t);let r=Date.now();Un.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw ul(n)?new al:n}}function jw(e){Pd(e);let t=e.slice(cl.length);if(!Dw.test(t))throw new On(e)}var Zs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},al=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Pd(e){if(!e||!/^claude /.test(e))throw new il(e)}function Kw(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Ow.test(r))throw new On(`Unexpected flag: ${r}`);let n=Uw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new On(`Flag ${r} requires a value`);if(!n.test(o))throw new On(`Unsafe value for flag ${r}`);t++;}}}async function ke(e){Pd(e);let t=e.slice(cl.length).split(/\s+/).filter(Boolean);Kw(t);let r=Vw(t);Un.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return Un.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw ul(o)?new Zs:o}}function Vw(e){return e.length>=3?e[2]:e.join(" ")}function ul(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Hw(e){return e.startsWith(bd)?cl+e.slice(bd.length):e}function Jw(e){return Nw.test(e)||Bw.test(e)}function Gw(e){let t=0;for(;t<e.length&&Jw(e[t]);)t++;return e.slice(t)}var Ww=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function zw(e,t){return !t||e.includes("--scope")||!Ww.test(e)?e:`${e} --scope ${t}`}async function Co(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Gw(r).map(i=>Hw(i)).map(i=>zw(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)jw(i);Un.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await ke(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await ke(o[i]),s.exitCode!==0)return s;return s}async function Qs(e,t,r){let n=Rn(e),o=t?.trim();if(!o&&(o=(await xd(`Plugin "${n}" could not be installed.
111
- If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Xs(o),r?.(),Un.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);Un.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ul(s)?new Zs:s}}Er();V();qe();$();var Qw=6e4,Cr=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 Dt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Qw}}).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(s){await rm(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new Cr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Cr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Cr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Ot(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});}async function en(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function tS(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function rS(e){return typeof e=="object"&&e!==null&&e.source==="url"}function nS(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Nn(e,t){let r=e.source;if(tS(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(rS(r))return {cloneUrl:r.url,subPath:"."};if(nS(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function it(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Ut=x("claude-code.adapter");function iS(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=es();if(!be__default.existsSync(s))return r;try{let i=JSON.parse(be__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Ld(e,t){let r=e.catalogId?ue.getAdapter(e.catalogId):void 0,n=Nn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=iS(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Xi(s,e.name,"external"):a=join(Or(i==="user"?"global":"project"),e.name);let l=null;try{xt(e.name),l=await Dt(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(be__default.existsSync(a)&&be__default.rmSync(a,{recursive:!0,force:!0}),be__default.mkdirSync(dirname(a),{recursive:!0}),be__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await nl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],nt(d),Eo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Ut.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Ot(l).catch(()=>{});}}async function dl(e,t,r,n){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Gs(n),version:"unknown",duration_ms:t,interface:Z().interfaceType});}catch(o){Ut.warn(`Failed to send external install metrics: ${String(o)}`);}}async function $d(e,t,r){try{await I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Z().interfaceType});}catch(n){Ut.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var aS={async install(e,t){if(e.origin===an&&!e.installCommand&&!$n(e.name))return Ld(e,t);if(e.origin===an&&e.installCommand){let r=e.type??"skill",n=await Co(e.installCommand,t.scope);return n.exitCode===0?(await dl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await $d(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if($n(e.name)){let r=e.type??"skill",n=Ln(e.name,t.scope);Ut.debug(`[${e.name}] Attempting install: ${n}`);let o=await ke(n);if(o.exitCode===0)return await dl(e.name,o.duration_ms,r,t.scope),{success:true};Ut.debug(`[${e.name}] First attempt failed, adding marketplace`),await Qs(e.name,t.marketplaceSource,()=>{});let s=await ke(n);return s.exitCode===0?(await dl(e.name,s.duration_ms,r,t.scope),{success:true}):(await $d(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await _e(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Ut.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Po(e,t);},getInstallPath(e,t){return ""}};function Rd(e){return {async install(t,r){if(t.origin===an&&!t.installCommand&&!$n(t.name))return Ld(t,r);if(!t.installCommand)try{let o=await _e(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Ut.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Ut.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Co(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=ot(),o=`${t}@${me}`;if(n.plugins[o]){await Po(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function lS(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!be__default.existsSync(t))continue;let r=be__default.readdirSync(t).filter(n=>n.endsWith(".md")&&be__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function pl(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,pl(r)]))}function Md(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(pl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(pl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Md(s,o):r[n]=o;}return r}async function _d(e,t,r,n){let o=await nl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],nt(o);}var cS={async install(e,t){let r=t.scope??"user",n=e.catalogId?ue.getAdapter(e.catalogId):void 0,o=Nn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{xt(e.name),s=await Dt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=lS(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=rs(r);be__default.mkdirSync(l,{recursive:!0});let u=it(e.name);if(a.length===1)be__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=it(basename(d,".md"));be__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await _d(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Ut.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Ot(s).catch(()=>{});}},async uninstall(e,t){let r=rs(t),n=it(e);if(be__default.existsSync(r))for(let a of be__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))be__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=ot(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;nt({...s,plugins:l});}else nt({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(rs(t),`${it(e)}.md`)}},uS={async install(e,t){let r=t.scope??"user",n=e.catalogId?ue.getAdapter(e.catalogId):void 0,o=Nn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{xt(e.name),s=await Dt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!be__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(be__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=fo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Md(m,u);return Es({...d,hooks:p}),await _d(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Ut.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Ot(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ei=class{id="claude-code";name="Claude Code";async isAvailable(){return en("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:aS,skill:Rd("skill"),mcp:Rd("mcp"),agent:cS,hook:uS}};function ti(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var pS=new Set(["gh"]),mS=ti(pS,"use: gh copilot mcp remove <name>"),ri=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await en("gh",["--version"])?en("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:mS}};qe();var fS=new Set(["opencode"]),gS=ti(fS,"use: opencode config remove mcp <name>");function hS(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
112
- `)}function Dd(){return {async install(e,t){try{xt(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ue.getAdapter(e.catalogId):void 0,n=Nn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Dt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=ts(t.scope??"user"),a=join(s,".opencode","plugins");if(be__default.existsSync(a)){let l=be__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};be__default.mkdirSync(i,{recursive:!0}),be__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);be__default.existsSync(l)&&be__default.rmSync(l,{recursive:!0,force:!0}),be__default.mkdirSync(l,{recursive:!0}),be__default.cpSync(s,l,{recursive:!0}),be__default.mkdirSync(i,{recursive:!0}),be__default.writeFileSync(join(i,`${e.name}.js`),hS(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await Ot(o).catch(()=>{});}},async uninstall(e,t){xt(e);let r=ts(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);be__default.existsSync(n)&&be__default.rmSync(n,{force:true}),be__default.existsSync(o)&&be__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(ts(t),`${e}.js`)}}}var ni=class{id="opencode";name="OpenCode";async isAvailable(){return en("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:gS,skill:Dd(),bundle:Dd()}};var Nt=new Js;Nt.register(new ei);wr()&&(Nt.register(new ri),Nt.register(new ni));function Od({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Nt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(v=>v.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Gu(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(tt,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(tt,{itemName:`${e} \u2014 Choose scope`,actions:Hu,descriptions:Ju,onAction:f,onClose:h},"scope"):jsx(tt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}B();function Nd({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(tt,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ii({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}B();function jd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ii({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)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 d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(tt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function Hd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ii({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(tt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}$();var jn=x("bundle:installer"),Jd=/already exists/i;async function ES(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(vd(t)){let r=await Ed(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Jd.test(n))return;throw new Error(n)}}else {let r=await Co(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Jd.test(n))return;throw new Error(n)}}}async function PS(e,t){try{await I(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){jn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function TS(e,t,r){try{await I(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){jn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Gd(e,t,r,n){try{await I(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){jn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function CS(e,t,r,n,o){try{await I(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){jn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function ci(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await PS(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){jn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await Gd(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await ES(f),u++,await TS(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let v=w instanceof Error?w.message:String(w);jn.error(`Failed to install artifact "${h}": ${v}`),l.push({name:h,type:g,reason:v}),await Gd(i,h,g,v),r?.({index:p+1,total:c,artifact:f,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await CS(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}B();function qd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,ci(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ie()})}));B();function Yd({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Tt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}B();function Zd({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Tt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Qd(e){return e.adapter.removable!==false?4:2}V();B();function ep({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function rp({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function np({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(T=>r.has(`${T.name}@${o}`)),i=t.filter(T=>!r.has(`${T.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((T,R)=>{if(R.escape){n();return}if(R.return){d(a[l]??null);return}if(R.upArrow){u(_=>Math.max(0,_-1));return}R.downArrow&&u(_=>Math.min(a.length-1,_+1));},{isActive:c===null}),c!==null)return jsx(ep,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Xe/2)),p=Math.min(a.length,m+Xe);p===a.length&&(m=Math.max(0,p-Xe));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,v=p>s.length,D=f.filter(T=>r.has(`${T.name}@${o}`)),M=f.filter(T=>!r.has(`${T.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(T=>jsx(rp,{item:T,isSelected:a.indexOf(T)===l,isInstalled:true},T.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),M.map(T=>jsx(rp,{item:T,isSelected:a.indexOf(T)===l,isInstalled:false},T.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Wa();var _S=/^https?:\/\/.+/;function DS(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function OS(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function ap(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!_S.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let v=randomUUID(),D=new _n(v,w,g);try{await D.fetchItems(),await zt.add({id:v,name:w,source:g}),ue.register(new _n(v,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let T=DS(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":OS(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(T,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function lp(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await zt.remove(o),ue.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function up(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=fe(A=>A.installedItems),[o,s]=useState(()=>ue.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,h]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&h("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=ue.listAdapters(),N=await zt.read(),G=new Map(N.map($e=>[$e.id,$e]));s(A.map($e=>({adapter:$e,stored:G.get($e.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let N=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(G=>{N||p({items:G,loading:false,error:null});}).catch(G=>{N||p({items:[],loading:false,error:G instanceof Error?G.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let v=ap(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:M}=lp(D),T=useCallback(async A=>{h("removing"),await M(A);},[M]),R=useCallback(async A=>{try{let N=await A.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),A.stored){let G=new Date().toISOString();await zt.updateField(A.stored.id,{lastUpdated:G}),w();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[w,r]),_=useCallback(async A=>{if(!A.stored)return;let N=A.stored.autoUpdate!==false;await zt.updateField(A.stored.id,{autoUpdate:!N}),w();},[w]),O=useCallback(()=>h("browse"),[]),ee=useCallback(A=>{let N=o[i-1];if(!N)return;let G=N.adapter.removable!==false;[O,()=>{R(N);},...G?[()=>{_(N);},()=>{T(N.adapter.id);}]:[]][A]?.();},[o,i,O,R,_,T]),k=useCallback(()=>h("main"),[]),H=useCallback(()=>{let A=o[i-1];A&&R(A);},[o,i,R]),Q=useCallback(()=>{let A=o[i-1];A&&_(A);},[o,i,_]),j=useCallback(()=>{let A=o[i-1];A&&T(A.adapter.id);},[o,i,T]);if(useInput((A,N)=>{if(N.upArrow){a(G=>Math.max(0,G-1));return}if(N.downArrow){a(G=>Math.min(o.length,G+1));return}(N.return||N.tab)&&(i===0?v.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&v.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,N)=>{if(N.escape||N.tab){u("list");return}if(N.upArrow){d(G=>Math.max(0,G-1));return}if(N.downArrow){let G=o[i-1],$e=G?Qd(G)-1:0;d(zo=>Math.min(zo+1,$e));return}N.return&&ee(c);},{isActive:f==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(v.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let N=A.adapter.id??"default",G=new Set(n.filter($e=>$e.marketplace===A.adapter.name).map($e=>`${$e.name}@${N}`));return jsx(np,{entry:A,items:m?.items??[],installedKeys:G,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let K=o[i-1]??null,z=K?n.filter(A=>A.marketplace===K.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Yd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&K?jsx(Zd,{entry:K,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:H,onToggleAutoUpdate:Q,onRemove:j}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:K?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function dp(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=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o-1+ne.length)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}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:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function pp(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function mp(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}}var jS=new Set(ne.filter(e=>e.focus!=="list").map(e=>e.focus));function Uo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Ve.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function fp({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Ve(h=>h.query),a=Ve(h=>h.setQuery),l=Ve(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Ve.getState();g(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Uo(Ra(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Uo(Ra("",g,{activeTab:w}));},{isActive:jS.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Uo(dp(h,g,{activeTab:w,selectedIndex:v},u.current));},{isActive:t==="list"}),useInput((h,g)=>{Uo(pp(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=mp(h,g,Ve.getState().query),v=w.queryUpdate;if(Uo(w.actions),v==="reset")l(),d("");else if(v!==null){let{query:D,cursorPosition:M,setCursorPosition:T}=Ve.getState();if("backspace"in v)M>0&&(a(D.slice(0,M-1)+D.slice(M)),T(M-1));else if("append"in v)a(D.slice(0,M)+v.append+D.slice(M)),T(M+v.append.length);else if("cursorMove"in v){let R=M+v.cursorMove;R>=0&&R<=D.length&&T(R);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();h===0?g(0):w>=h&&g(h-1);},[]),f=useCallback(h=>{if(!c)return u.current=h.length,h;let g=c.toLowerCase(),w=h.filter(v=>v.name.toLowerCase().includes(g)||v.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function hp(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Qe(a=>a.justAuthenticated),o=Qe(a=>a.credentials),s=Qe(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Ue(e,t,r=false){return r?true:!yl.valid(e)||!yl.valid(t)?false:yl.gt(t,e)}V();$();var Zt=x("updater");async function KS(e,t,r,n,o,s){try{await I(b.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Z().interfaceType});}catch(i){Zt.warn(`Failed to send update metrics: ${String(i)}`);}}function VS(e){let t=ot(),r=`${e}@${me}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function mi(e,t={}){let r=Date.now(),n=null;try{Zt.debug(`[${e}] Acquiring lock...`),n=await Pr();let o=VS(e);if(!o)throw Zt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Zt.debug(`[${e}] Fetching manifest...`);let u=(await Dn(e,t.source)).version;if(!i||!Ue(i,u,t.force))throw Zt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new vr(e,i??"unknown");Zt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await _e(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await KS(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Zt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Zt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Pr();let d=ot(),m=`${e}@${me}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,nt(d),Zt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Er();$();var fi=x("dispatcher");async function HS(e,t,r,n,o){let s=Rn(e);return fi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Qs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),fi.debug(`[${e}] Retrying install after marketplace add`),ke(t)}async function yp(e,t,r,n){let o=Ln(e,n),s=Rn(e);r?.onStatus?.(`Installing ${s}...`),fi.debug(`[${e}] Attempting install: ${o}`);let i=await ke(o);if(i.exitCode===0)return i;fi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return HS(e,o,a,t,r)}async function wp(e,t,r){let n=e.type??"bundle",o=await Nt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function Sp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await wp(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=ie().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Nt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await To(i,u,a),t();},[e,t]),s=useCallback(async i=>{await mi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}B();$();var hi=x("mcp");function No(e,t){e.silent?Ze({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function bp(e,t){e.silent?Pe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(te(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&P(t.stdout));}function JS(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 wl(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Ip(e,t,r){if(!await de())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return No(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}hi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=JS(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await st(`Install external MCP "${s}"?
110
+ `),this.warned=!0;}ps().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=ps(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return ps().path}static hasExistingData(){try{let t=new ga({projectName:ha});return be.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ga({projectName:ha});be.rmSync(t.path,{force:!0});}catch{}ms=null;}};});async function ya(){if(He.hasExistingData())return new He;switch(process.platform){case "darwin":return await hn.isAvailable()?new hn:new He;case "linux":return await pr.isAvailable()?new pr:await pr.ensureInstalled()?new pr:new He;case "win32":return await wn.isAvailable()?new wn:new He;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var kc=J(()=>{"use strict";aa();ua();fa();io();});var Ac=J(()=>{"use strict";Wi();sa();kc();aa();ua();fa();io();});async function mr(){return hs||(hs=ya()),hs}function ys(){hs=null;}async function Y(){let t=await(await mr()).getSecret(Jt,wa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function fr(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 Rc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await mr()).setSecret(Jt,wa,JSON.stringify(e));}async function $c(){let e=await mr();await e.deleteSecret(Jt,wa),await e.deleteSecret(Jt,Sa),await e.deleteSecret(Jt,xa);}async function Lc(){return (await mr()).getStoragePath()}async function Mc(e){await(await mr()).setSecret(Jt,Sa,JSON.stringify(e));}async function ws(){let t=await(await mr()).getSecret(Jt,Sa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ss(e){await(await mr()).setSecret(Jt,xa,JSON.stringify(e));}async function Sn(){let t=await(await mr()).getSecret(Jt,xa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function gr(){let e=await ws();return e?new Date(e.expiresAt)>new Date:false}function kt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Rc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Rc,Jt,wa,Sa,xa,hs,Ie=J(()=>{"use strict";Ac();R();Rc=x("config:credentials"),Jt="flow-plugins-cli",wa="credentials",Sa="token-cache",xa="user-info",hs=null;});function xn(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 xs=J(()=>{"use strict";});function Xg(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 ba(e){if(_c.some(r=>r.test(e)))return true;let t=Xg(e);return !!(t&&_c.some(r=>r.test(t)))}function qg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function At(e,t){let r=qg(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(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&ba(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var _c,jr=J(()=>{"use strict";_c=[/^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\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function Qg(e){if(!Ht.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function eh(e){if(e instanceof HTTPError){let t=e.response.status;Ia.debug(`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&&Dc[r]?new Error(Dc[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?(Ia.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Ia.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Kr(e){let t=At("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Qg(e.tenant);let r;try{r=await td.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await eh(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await fr(e),await Mc({accessToken:r.access_token,expiresAt:n});let o=xn(r.access_token);await Ss({sub:o.sub,name:o.name,email:o.email});}var Ia,Dc,bs=J(()=>{"use strict";Ie();xs();jr();R();K();Ia=x("api:auth");Dc={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 Rt(){if(await gr()){let n=await ws();if(n)return n.accessToken}Oc.debug("Token expired or missing, re-authenticating...");let t=await Y();if(!t)throw new Error("Not authenticated. Run: flow auth login");He.clearFallbackFile(),ys(),await Kr(t);let r=await ws();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Oc.debug("Token refreshed successfully"),r.accessToken}var Oc,bn=J(()=>{"use strict";Ie();bs();io();R();Oc=x("lib:tokenProvider");});function zt(){return td.create({prefix:At("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Rt();e.headers.set("Authorization",`Bearer ${t}`);let r=await Y();r?.tenant&&Ht.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Io=J(()=>{"use strict";jr();Ie();bn();K();});function An(e,t){let r=zt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function Rn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Ja=J(()=>{"use strict";Io();});function vo(e){if(!e||!Zy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function $n(e){return Qy.test(e)}function Ln(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Wa(e){if(!ew.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.`)}function Mn(e,t){let r=Ln(e);Wa(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function qs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!tw.test(t)&&!rw.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Zy,Qy,ew,tw,rw,Pr=J(()=>{"use strict";Zy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;Qy=/^[^@]+@[^@]+$/;ew=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;tw=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,rw=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Yu={};ic(Yu,{FlowApiAdapter:()=>_n});var nw,_n,za=J(()=>{"use strict";Io();Ja();R();Pr();nw=x("catalog.flow-api"),_n=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await An("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await Rn(t);if(r)throw new Error(r);if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${n}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){vo(t);try{return await An(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Rn(r);if(n)throw new Error(n);if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${o}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await zt().head("v1/plugins/catalog"),nw.debug("ping ok"),!0}catch{return !1}}};});function sw(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Qu(){return Zu??=sw(),Zu}var Zu,ed=J(()=>{"use strict";});var nd={};ic(nd,{GitRepoAdapter:()=>Dn});function rd(e,t){if(!iw.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var iw,Dn,Xa=J(()=>{"use strict";ed();jr();iw=/^[a-zA-Z0-9_.-]+$/;Dn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(ba(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return rd(a,"owner"),rd(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await td.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await td.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Qu();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});K();var lc=new Set(["skill","mcp","bundle","plugin"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(lc),origins:new Set(Gi)},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:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal: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(lc)},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(Gi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ie();bn();xs();K();jr();R();var Is=x("api:metrics");function Uc(){return At("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Nc(e,t,r){return td.post(e,{json:t,headers:r})}async function rh(e){let t=await Sn();if(t)return t;let r=xn(e),n={sub:r.sub,name:r.name,email:r.email};return await Ss(n),n}async function I(e,t){let r=await Rt(),n=await rh(r),o=await Y();if(!Ht.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ji,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Nc(Uc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Is.debug(`Metrics event sent: ${e}`);}catch(i){throw Is.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Bc(e,t,r){try{let n=r&&Ht.test(r)?r:"unknown",o={action:e,booster:Ji,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Nc(Uc(),o,{FlowTenant:n}),Is.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Is.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var nh={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ht={...nh};function Fc(e){let t=Date.now();ht={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Vr(e){ht.currentStep=e,ht.stepStart=Date.now();}function Z(){return {...ht}}function hr(){return ht.sessionStart===0?0:Date.now()-ht.sessionStart}function Hr(){return ht.stepStart===0?0:Date.now()-ht.stepStart}function jc(){ht.tuiSessionStart=Date.now();}function Kc(){return ht.tuiSessionStart===0?0:Date.now()-ht.tuiSessionStart}R();var oh=3e3,sh=x("abandonment");async function vs(e){let{currentStep:t,sessionStart:r}=Z();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:hr()};try{await Promise.race([I(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),oh))]);}catch(o){sh.warn(`Abandonment event failed: ${String(o)}`);}}function Vc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var ih=3e3,ah=x("session-end");async function lo(e,t,r){let n=Kc(),s=[I(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(vs(e));try{await Vc(Promise.all(s).then(()=>{}),ih);}catch(i){ah.warn(`Session end event failed: ${String(i)}`);}}var dh=2e3;function Jc(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),lo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},dh);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var gh=16;function Gc({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=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(gh)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}K();function Wc({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();pn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:mn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}K();function zc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ur," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}K();function Xc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[ur," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var et=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})}));bs();K();function Wr(){return xe__default.join(Le__default.homedir(),".claude","settings.json")}function Yc(e){return `${(e&&e.trim().length>0?e.trim():Yo).replace(/\/+$/,"")}/flow-litellm/`}function ho(){let e=Wr();if(!be__default.existsSync(e))return {status:"missing"};let t=be__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Ps(e){let t=Wr();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;be__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,t);}function Zc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function Aa(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function Qc(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var Ih=3600,zr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function yo(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function vh(e){return bh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Ih})}function Ts(e,t={}){let r=ho();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new zr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Aa(r.settings):null,s=r.status==="ok"?Qc(r.settings):null,i=t.jwtOverride??vh(e),a=Yc(e.customUrl),l=Zc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Cs(e){Ps(e.merged);}function eu(){let e=ho();return e.status!=="ok"?false:Aa(e.settings)!==null}Ie();Ke();function Eh(){let e=gc();if(!be__default.existsSync(e))return {};try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ra=null;function Ph(){return Ra===null&&(Ra=Eh()),Ra}function Sr(){return !!Ph().ENABLE_EXPERIMENTAL_BETAS}K();function Ah(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function ru(e){let t=Ah();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var ks={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=xe__default.join(Le__default.homedir(),".claude","settings.json"),r=be__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??Yo),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},Rh={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},se=Sr()?[ks,Rh]:[ks];Ie();R();var _h=x("moduleState");function Rs(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var Dh={retries:5,minTimeout:50};async function nu(e,t){be__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await Mh.lock(e+".lock",{realpath:false,retries:Dh});try{return await t()}finally{await r();}}function ou(){let e=Rs();if(!be__default.existsSync(e))return [];try{let t=JSON.parse(be__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(_h.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),be__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return be__default.rmSync(e,{force:true}),[]}}function Xr(){return ou()}function su(e){let t=Rs();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};be__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,t);}function tt(e){return Xr().find(t=>t.alias===e)??null}async function yt(e){let t=Rs();await nu(t,async()=>{let r=ou(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,su(r);});}async function qr(){let e=Rs();be__default.existsSync(e)||await nu(e,async()=>{be__default.existsSync(e)||su([]);});}var Nh=promisify(execFile);function xr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Lt(e){let t=process.platform==="win32"?"where":"which";try{return await Nh(t,[e]),!0}catch{return false}}function Gt(){return process.platform==="win32"?"npm.cmd":"npm"}var iu=promisify(execFile),vn=class{type="npm";async isAvailable(){return Lt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=xr(t,"npm");if(!r)return null;try{let{stdout:n}=await iu(Gt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=xr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await iu(Gt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var $s=promisify(execFile),Vh=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Ls=class{type="homebrew";async isAvailable(){return Lt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=xr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=xr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await $s("brew",["tap",o.tap]),await $s("brew",["trust",o.tap])),await $s("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await $s("brew",["list","--versions",t]),n=r.trim().match(Vh);return n?n[2]:null}catch{return null}}};var En=promisify(execFile),lu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function cu(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ms=class{type="curl";async isAvailable(){return Lt("curl")}async install(t){let r=Date.now(),n=xr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=xe__default.join(cu(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await En(n,["--version"]),s=o.match(lu);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=xe__default.join(Le__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await En("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{be__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return be__default.chmodSync(s,448),await En("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{be__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=cu(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(be__default.mkdirSync(s,{recursive:!0}),a=!0,await En("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return be__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}be__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await En(i,["--version"]),c=u.match(lu);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{be__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=xe__default.join(Le__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await En("curl",["-L","--fail","-o",n,r]);let o=be__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=be__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{be__default.unlinkSync(n);}catch{}}}};R();var uu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(uu=e.version);}catch{}var ue=uu;var Ce=x("moduleInstaller");function _t(e){switch(e){case "npm":return new vn;case "homebrew":return new Ls;case "curl":return new Ms}}async function wo(e,t,r){try{await I(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Ce.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ir(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Ce.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await wo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await wo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await wo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=_t(r),u=false;try{u=await l.isAvailable();}catch(d){Ce.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await wo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await I(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:t});}catch(d){Ce.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Ce.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await yt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await I(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Ce.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await qh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await wo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function qh(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await Y(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Ce.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Ce.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Ce.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Ce.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function _s(e,t){let r=Date.now(),n=tt(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=_t(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await I(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:"command"});}catch(a){Ce.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Ce.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await yt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await I(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Ce.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await I(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Ce.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await I(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Ce.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var Ds=x("flowAiObsSetup");async function Os(e,t){try{if(!await new vn().isAvailable().catch(()=>!1))return Ds.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ir(ks,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Ds.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Ds.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Ds.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function du(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 Yh=x("useAuthSetup");function pu(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),y=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:v}=et(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},M=()=>{I(b.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:hr(),interface:"tui"}).catch(()=>{});},T=async V=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{V&&Cs(V),await fr(z);}catch(G){l(G instanceof Error?G.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:A,...N}=z;w(N),v(true),M(),await Os(n.current,o.current).catch(G=>Yh.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Us({starterKit:N.starterKit});},$=async()=>T(),_=async V=>T(V),O=V=>{try{let z={...r.current,customUrl:n.current??void 0};return Ts(z,{allowOverwriteMalformed:V,jwtOverride:e.trim()})}catch(z){return z instanceof zr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},ee=()=>{let V=O(true);V&&(f(V),_(V));},k=async()=>{let V=e.trim();if(!V){i("This field is required");return}let z;try{z=yo(V);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=z,m("customUrl");},H=V=>{n.current=V,m("email");},Q=V=>{o.current=V,j();},j=async()=>{let V=n.current;V&&kt(V),c(true),l(null),y.current+=1;try{await Kr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),Bc(b.CLI_AUTH_FAILED,{error_code:du(z),attempt:y.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:D,handleSubmit:k,goToEmailStep:H,handleEmailConfirm:Q,commitAndProceed:_,skipJwtAndProceed:$,planPersistOverwrite:ee}}K();B();function mu(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:y}=pu(),[g,w]=useState("confirm"),[v,D]=useState(""),M=useRef(""),[T,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),M.current="",D(""),$(false));},[o]),useInput((_,O)=>{if(!(n||i.current)){if(o==="preview"){O.return&&s?p(s):O.escape?f():_==="q"&&u();return}if(o==="malformedConfirm"){O.return?y():O.escape&&u();return}if(o==="customUrl"){if(g==="confirm")_==="y"||_==="Y"?w("input"):(_==="n"||_==="N"||O.return)&&d(null);else if(O.escape)M.current="",D(""),w("confirm");else if(O.return){let ee=M.current.trim();ee.length>0&&un.test(ee)?($(false),d(ee)):ee.length>0&&$(true);}else O.backspace||O.delete?(M.current=M.current.slice(0,-1),D(M.current)):_&&!O.ctrl&&!O.meta&&(M.current=M.current+_,D(M.current),$(false));return}o!=="email"&&O.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ur," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),T&&jsx(Text,{color:"red",children:dn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ur," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Wc,{onConfirm:m})]}):o==="preview"&&s?jsx(zc,{plan:s}):o==="malformedConfirm"?jsx(Xc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[ur," \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:jsx(Box,{marginBottom:1,children:jsx(Gc,{label:"JWT",value:e,onChange:_=>{a(_),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",h(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Tn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(ry,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ue]})})]})}var yu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ne=Sr()?yu:yu.slice(0,3);function ny(e){return ne.findIndex(t=>t.id===e)}function Ma(e,t,r){let n=ny(r.activeTab);if(t.rightArrow||t.tab){let o=ne[(n+1)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ne[(n-1+ne.length)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ne[n]?.focus??"list"}]:[]}var xu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function bu({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ne.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${xu[r]} (${e})`:xu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Je=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function vu(){let e=S(i=>i.focus),t=Je(i=>i.query),r=Je(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=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:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}K();var ay=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...cn[e]})),ly=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...ac[e]}));function Eu(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),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"]})]}),ay.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"]})]}),ly.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)})]})}K();function Pu({type:e}){let{label:t,color:r}=cn[e];return jsx(Text,{color:r,children:t})}K();function ku({origin:e}){return e===eo?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}B();var Bs=dy.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(Pu,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(ku,{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 ",Ct(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Cn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}K();function $u({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Cn,{message:t});let n=Math.max(0,r-Math.floor(Ye/2)),o=Math.min(e.length,n+Ye);o===e.length&&(n=Math.max(0,o-Ye));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Bs,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function _u({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}K();function Ou({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(Cn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Ye/2)),u=Math.min(n.length,l+Ye);u===n.length&&(l=Math.max(0,u-Ye));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(_u,{label:p.label,pathHint:p.pathHint},p.key):jsx(Bs,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Sy={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function xy({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(vu,{}),jsx(Eu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Sy[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Ou,{groups:n,emptyMessage:r}):jsx($u,{items:e,emptyMessage:r})]})}function Uu({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(xy,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var vy={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=Bundle | 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",starterKitList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",starterKitDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",moduleSetup:"\u2191\u2193: navigate | Space: toggle | Tab: change method | Enter: confirm",marketplaces:"\u2191\u2193: navigate | a: add catalog | d: remove catalog | r: refresh | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",verify:"\u2191\u2193: navigate | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleInstallProgress:"Enter/Esc: back to catalog"};function Fs(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[vy[e],t?" | Ctrl+D: debug log":""]})})}B();function Nu({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"," ",h(e)]})}):null}function js({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Fa(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Ku=20;function Ks(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Ku),s="\u2588".repeat(o)+"\u2591".repeat(Ku-o),i=`${Fa(e)} / ${Fa(t)}`;return {bar:s,percent:n,label:i}}function Vs({received:e,total:t}){let{bar:r,percent:n,label:o}=Ks(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Hs({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 rt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="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((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}K();var Ha=Object.entries(to),Gu=[...Ha.map(([,e])=>e.actionLabel),"Cancel"],Wu=Object.fromEntries(Ha.map(([,e])=>[e.actionLabel,e.description]));function zu(e){let t=Ha.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var Ny=x("provider.registry"),By=3e4,Gs=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+By}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&Ny.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Fy={user:"global",project:"project",local:"local"};function Ws(e){return e?Fy[e]:"global"}var Ge=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},Er=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};Io();Ja();R();var Vy=x("catalog.registry"),zs=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);Vy.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};Ke();var Yy={retries:5,minTimeout:50};async function Ga(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Mh.lock(e+".lock",{realpath:false,retries:Yy});try{return await t()}finally{await r();}}var Xs=class{filePath;constructor(t){this.filePath=t??fc();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await Ga(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await Ga(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ga(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};za();var de=new zs,Xt=new Xs,aw=["flow-harness"];function lw(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?aw:e.split(",").map(t=>t.trim()).filter(Boolean)}de.register(new _n);for(let e of lw())de.register(new _n(e));var od=false;async function sd(){if(od)return;od=true;let e=await Xt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Xa(),nd));for(let r of e)de.register(new t(r.id,r.name,r.source));}Pr();var id=2;async function qt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(za(),Yu));return new t(e).fetchItems()}return de.fetchAll()}async function ad(){return de.fetchAllWithErrors()}async function On(e,t){vo(e);try{return await An(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Rn(r);throw n?new Error(n):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):r.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${r.message}`):r}}async function ld(e,t,r){vo(e);try{let n=await An(`v1/plugins/${e}/archive`,r),o=n.headers.get("x-archive-size"),s=o?Number(o):NaN,i=Number.isFinite(s)&&s>0?s:0,a=i>0,l=n.body;if(!l)throw new Error("Failed to download plugin: response has no body");let u=l.getReader(),c=[],d=0;for(;;){let{done:m,value:p}=await u.read();if(m)break;if(d+=p.byteLength,a&&d>i*id)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*id}`);c.push(p),a&&t?.(d,i);}return Buffer.concat(c)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await Rn(n);throw o?new Error(o):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`):n}}async function Ys(){try{let{profiles:e}=await zt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}Ke();Ke();async function cd(e,t){let r=xe.resolve(t);await Dt.mkdir(r,{recursive:true});let n=xe.join(xe.dirname(r),`${randomUUID()}.zip`);try{await Dt.writeFile(n,e);let o=await uw.Open.file(n),s=xe.normalize(r+xe.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=xe.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(xe.resolve(xe.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Dt.unlink(n);}catch{}}}async function qa(e){await Dt.rm(e,{recursive:true,force:true});}async function Tr(){let e=pc();await Dt.mkdir(xe.dirname(e),{recursive:true});try{await Dt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Mh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Ke();K();function mw(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||le,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function pd(e){let t=ts(e);if(!be__default.existsSync(t))return null;try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return null}}function fw(e){let t=pd(e);if(t)return t;let r=mw(e),n=ts(e);return be__default.mkdirSync(xe__default.dirname(n),{recursive:true}),Ya(r,e),r}function Ya(e,t){let r=ts(t),n=`${r}.${randomUUID()}.tmp`;be__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(n,r);}function gw(e){let t=e||le,r=Ur(),n={};try{be__default.existsSync(r)&&(n=JSON.parse(be__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:dc(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;be__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(o,r);}function md(e,t,r){bt(e.name),gw(r);let n=qi(e.name,r);be__default.mkdirSync(xe__default.dirname(n),{recursive:true});try{be__default.lstatSync(n),be__default.rmSync(n,{recursive:!0,force:!0});}catch{}be__default.cpSync(t,n,{recursive:true,dereference:true});let o=fw(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Ya(o,r));}function Za(e,t){bt(e);let r=qi(e,t);try{be__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=pd(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Ya(n,t);}B();R();var yw=x("mcpConfigReader"),ww=500,Sw=512;function xw(){return xe__default.join(Le__default.homedir(),".claude.json")}function bw(){return xe__default.join(process.cwd(),".mcp.json")}function gd(e){if(!be__default.existsSync(e))return null;try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return yw.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Eo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qa(e){if(!Eo(e))return {};let t=e.mcpServers;return Eo(t)?t:{}}function el(e,t){return Object.keys(e).slice(0,ww).map(n=>({name:h(n.slice(0,Sw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function yd(){let e=[],t=xw(),r=gd(t);if(Eo(r)){let a=r,l=Qa(a);e.push(...el(l,"user"));let u=process.cwd();if(Eo(a.projects)){let c=a.projects[u];if(Eo(c)){let d=Qa(c);e.push(...el(d,"local"));}}}let n=bw(),o=gd(n),s=Qa(o);e.push(...el(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}R();var nt=x("storage");async function vw(e,t,r){try{await I(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Z().interfaceType});}catch(n){nt.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Ew(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;I(n,{tool_id:e,source:r,interface:Z().interfaceType}).catch(o=>nt.warn(`Failed to send ${t} metrics: ${String(o)}`));}function ol(){return xe__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function Pw(){return xe__default.join(Le__default.homedir(),".claude","plugins")}function Zs(e){let t;try{t=be__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(Pw()),n=xe__default.resolve(xe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+xe__default.sep),s=t.startsWith(n+xe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Sd(e="user"){return e==="local"?xe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?xe__default.join(process.cwd(),".claude","settings.json"):xe__default.join(Le__default.homedir(),".claude","settings.json")}function st(){let e=ol();if(!be__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function sl(){let e=ol();try{let t=await be__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Tw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function xd(e,t){try{be__default.mkdirSync(xe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;be__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(r,e);}catch(r){throw Tw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function ot(e){xd(ol(),e);}function Po(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Cw(e,t){let r=xe__default.join(e,".claude-plugin"),n=xe__default.join(r,"plugin.json");if(be__default.existsSync(n))try{return JSON.parse(be__default.readFileSync(n,"utf-8"))}catch{return null}let o=xe__default.join(r,"marketplace.json");if(be__default.existsSync(o))try{let s=JSON.parse(be__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function il(e="user"){let t=Sd(e);if(!be__default.existsSync(t))return {};try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return {}}}function bd(e,t="user"){xd(Sd(t),e);}function kw(e,t){let{name:r,marketplace:n}=Po(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Po(i).name===r)[0],!o)throw nt.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Aw(e,t){let{name:r,marketplace:n}=Po(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Po(i).name===r)[0],o?{key:o,name:r}:null}function tl(e="user"){return il(e).enabledPlugins??{}}function rl(e,t="user"){let r=il(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,bd(r,t);}function To(e,t,r="user"){let n=il(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},bd(n,r);}function Rw(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function ie(){let e=st(),t=tl(),r=tl("project"),n=tl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=Po(u),p=c.map(y=>y.scope==="managed"?{...y,scope:"user"}:y);return Rw(p).map(y=>{let g=Cw(y.installPath,d),v=(o[y.scope]??t)[u];return {name:d,marketplace:m,version:y.version&&y.version!=="unknown"?y.version:void 0,installedAt:y.installedAt,installPath:y.installPath,scope:y.scope,providerId:y.providerId,type:y.type,description:g?.description,author:g?.author,status:v===false?"disabled":"enabled"}})}),i=yd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function wd(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Co(e,t){nt.debug(`[${e}] Acquiring lock to uninstall`);let r=await Tr();try{let n=st(),o=Aw(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:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);nt.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Zs(l.installPath);let u=xe__default.dirname(l.installPath);Zs(u),nt.debug(`[${i}] Removing directory: ${u}`),be__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;ot({...n,plugins:m}),rl(s,t),Za(i,wd(s));}else n.plugins[s]=c,ot(n),rl(s,t);}else {nt.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Zs(c.installPath);let d=xe__default.dirname(c.installPath);Zs(d),nt.debug(`[${i}] Removing directory: ${d}`),be__default.rmSync(d,{recursive:!0,force:!0}),rl(s,c.scope);}Za(i,wd(s));let{[s]:l,...u}=n.plugins;ot({...n,plugins:u});}await vw(i,a[0].origin??"internal",a[0].type??"skill"),nt.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function ko(e,t,r){nt.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Tr();try{let o=st(),{key:s,name:i}=kw(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";nt.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),To(s,t==="enabled",l),Ew(i,t,u),nt.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}K();R();var $w=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Lw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function bt(e){if(!$w.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Mw(e){if(!Lw.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 Cr=x("installer");function _w(e,t,r){let n=`${e}@${r||le}`,s=st().plugins[n];if(s&&!t)throw new Ge(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function Dw(e,t,r){r&&await qa(t);try{Cr.debug(`[${t}] Extracting archive...`),await cd(e,t);}catch(n){throw await qa(t),n}}function Ow(e,t,r,n,o,s="claude-code",i){let a=st(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],ot(a),To(e,true,n);}async function Uw(e,t,r,n,o,s){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Z().interfaceType});}catch(i){Cr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Nw(e,t,r,n){try{await I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Z().interfaceType});}catch(o){Cr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function De(e,t={}){let r=Date.now(),n=null;try{Cr.debug(`[${e}] Acquiring lock...`),n=await Tr();let{pluginKey:o,alreadyInstalled:s}=_w(e,t.force,t.source),{source:i}=t;Cr.debug(`[${e}] Fetching manifest...`);let a=await On(e,i);bt(a.name),Mw(a.version),Cr.debug(`[${e}] Downloading archive...`);let l=await ld(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=uc(a.name,a.version,t.source);await Dw(l,d,!!s&&!!t.force),Ow(o,d,a.version,u,"internal",t.providerId,c),md(a,d,t.source);let m=Date.now()-r;Cr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await Uw(a.name,a.version,m,Ws(u),"internal",c),p}catch(o){throw await Nw(e,o,"internal",t.type??"skill"),Cr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();B();Ie();bn();R();var Bw=x("commands:helpers");async function pe(){let e=await Y();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&kt(e.customUrl);try{await Rt();}catch(t){return Bw.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function it(e){let t=al.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Id(e){let t=al.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim());});})}Pr();var Nn=x("claudeProxy"),dl="claude ",vd="flow ",ll=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Un=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";}},Fw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,jw=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Kw={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Vw=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Hw=/^(flow|claude)\s+auth\s+login(\s|$)/,Ed=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Pd(e){return Ed.test(e.trim())}function Jw(e){return Ed.exec(e.trim())?.[2]??""}async function Td(e){let t=Jw(e);Wa(t);let r=Date.now();Nn.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw pl(n)?new cl:n}}function Gw(e){Cd(e);let t=e.slice(dl.length);if(!Fw.test(t))throw new Un(e)}var Qs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},cl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Cd(e){if(!e||!/^claude /.test(e))throw new ll(e)}function Ww(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!jw.test(r))throw new Un(`Unexpected flag: ${r}`);let n=Kw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Un(`Flag ${r} requires a value`);if(!n.test(o))throw new Un(`Unsafe value for flag ${r}`);t++;}}}async function Ae(e){Cd(e);let t=e.slice(dl.length).split(/\s+/).filter(Boolean);Ww(t);let r=zw(t);Nn.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return Nn.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw pl(o)?new Qs:o}}function zw(e){return e.length>=3?e[2]:e.join(" ")}function pl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Xw(e){return e.startsWith(vd)?dl+e.slice(vd.length):e}function qw(e){return Vw.test(e)||Hw.test(e)}function Yw(e){let t=0;for(;t<e.length&&qw(e[t]);)t++;return e.slice(t)}var Zw=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Qw(e,t){return !t||e.includes("--scope")||!Zw.test(e)?e:`${e} --scope ${t}`}async function Ao(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Yw(r).map(i=>Xw(i)).map(i=>Qw(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Gw(i);Nn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Ae(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Ae(o[i]),s.exitCode!==0)return s;return s}async function ei(e,t,r){let n=Ln(e),o=t?.trim();if(!o&&(o=(await Id(`Plugin "${n}" could not be installed.
111
+ If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=qs(o),r?.(),Nn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);Nn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw pl(s)?new Qs:s}}Pr();K();Ke();R();var oS=6e4,kr=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 Ot(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:oS}}).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(s){await rm(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new kr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new kr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new kr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Ut(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});}async function rn(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function iS(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function aS(e){return typeof e=="object"&&e!==null&&e.source==="url"}function lS(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Bn(e,t){let r=e.source;if(iS(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(aS(r))return {cloneUrl:r.url,subPath:"."};if(lS(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function at(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Nt=x("claude-code.adapter");function dS(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=Ur();if(!be__default.existsSync(s))return r;try{let i=JSON.parse(be__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function _d(e,t){let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=Bn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=dS(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Yi(s,e.name,"external"):a=join(Nr(i==="user"?"global":"project"),e.name);let l=null;try{bt(e.name),l=await Ot(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(be__default.existsSync(a)&&be__default.rmSync(a,{recursive:!0,force:!0}),be__default.mkdirSync(dirname(a),{recursive:!0}),be__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await sl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],ot(d),To(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Nt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Ut(l).catch(()=>{});}}async function ml(e,t,r,n){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Ws(n),version:"unknown",duration_ms:t,interface:Z().interfaceType});}catch(o){Nt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Ld(e,t,r){try{await I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Z().interfaceType});}catch(n){Nt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var pS={async install(e,t){if(e.origin===ln&&!e.installCommand&&!$n(e.name))return _d(e,t);if(e.origin===ln&&e.installCommand){let r=e.type??"skill",n=await Ao(e.installCommand,t.scope);return n.exitCode===0?(await ml(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Ld(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if($n(e.name)){let r=e.type??"skill",n=Mn(e.name,t.scope);Nt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Ae(n);if(o.exitCode===0)return await ml(e.name,o.duration_ms,r,t.scope),{success:true};Nt.debug(`[${e.name}] First attempt failed, adding marketplace`),await ei(e.name,t.marketplaceSource,()=>{});let s=await Ae(n);return s.exitCode===0?(await ml(e.name,s.duration_ms,r,t.scope),{success:true}):(await Ld(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await De(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Nt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Co(e,t);},getInstallPath(e,t){return ""}};function Md(e){return {async install(t,r){if(t.origin===ln&&!t.installCommand&&!$n(t.name))return _d(t,r);if(!t.installCommand)try{let o=await De(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Nt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Nt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Ao(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=st(),o=`${t}@${le}`;if(n.plugins[o]){await Co(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function mS(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!be__default.existsSync(t))continue;let r=be__default.readdirSync(t).filter(n=>n.endsWith(".md")&&be__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function fl(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,fl(r)]))}function Dd(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(fl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(fl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Dd(s,o):r[n]=o;}return r}async function Od(e,t,r,n){let o=await sl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],ot(o);}var fS={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=Bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{bt(e.name),s=await Ot(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=mS(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=ns(r);be__default.mkdirSync(l,{recursive:!0});let u=at(e.name);if(a.length===1)be__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=at(basename(d,".md"));be__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Od(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Nt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Ut(s).catch(()=>{});}},async uninstall(e,t){let r=ns(t),n=at(e);if(be__default.existsSync(r))for(let a of be__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))be__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=st(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;ot({...s,plugins:l});}else ot({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(ns(t),`${at(e)}.md`)}},gS={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=Bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{bt(e.name),s=await Ot(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!be__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(be__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=ho();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Dd(m,u);return Ps({...d,hooks:p}),await Od(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Nt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Ut(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ti=class{id="claude-code";name="Claude Code";async isAvailable(){return rn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:pS,skill:Md("skill"),mcp:Md("mcp"),agent:fS,hook:gS}};function ri(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var yS=new Set(["gh"]),wS=ri(yS,"use: gh copilot mcp remove <name>"),ni=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await rn("gh",["--version"])?rn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:wS}};Ke();var SS=new Set(["opencode"]),xS=ri(SS,"use: opencode config remove mcp <name>");function bS(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
112
+ `)}function Ud(){return {async install(e,t){try{bt(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=Bn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Ot(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=rs(t.scope??"user"),a=join(s,".opencode","plugins");if(be__default.existsSync(a)){let l=be__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};be__default.mkdirSync(i,{recursive:!0}),be__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);be__default.existsSync(l)&&be__default.rmSync(l,{recursive:!0,force:!0}),be__default.mkdirSync(l,{recursive:!0}),be__default.cpSync(s,l,{recursive:!0}),be__default.mkdirSync(i,{recursive:!0}),be__default.writeFileSync(join(i,`${e.name}.js`),bS(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await Ut(o).catch(()=>{});}},async uninstall(e,t){bt(e);let r=rs(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);be__default.existsSync(n)&&be__default.rmSync(n,{force:true}),be__default.existsSync(o)&&be__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(rs(t),`${e}.js`)}}}var oi=class{id="opencode";name="OpenCode";async isAvailable(){return rn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:xS,skill:Ud(),bundle:Ud()}};var Bt=new Gs;Bt.register(new ti);Sr()&&(Bt.register(new ni),Bt.register(new oi));function Nd({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Bt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(v=>v.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=zu(g);w?r(w,c):s(false);},[r,c]),y=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(rt,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(rt,{itemName:`${e} \u2014 Choose scope`,actions:Gu,descriptions:Wu,onAction:f,onClose:y},"scope"):jsx(rt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}B();function Fd({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,y)=>{y.upArrow?a(g=>Math.max(0,g-1)):y.downArrow?a(g=>Math.min(d.length-1,g+1)):y.return?d[i]==="Confirm Install"?n():o():y.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let y=h(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:y}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,y)=>jsx(Box,{children:jsxs(Text,{bold:y===i,color:y===i?"cyan":void 0,children:[y===i?"\u203A ":" ",f]})},f))})]}):jsx(rt,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ai({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}B();function Vd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ai({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)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 d=r==="enabled"?"Disable":"Enable",m=o&&h(o),p=m?`Update to v${m}`:"Update";return jsx(rt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function Gd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ai({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(rt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var Kn=x("bundle:installer"),Wd=/already exists/i;async function AS(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Pd(t)){let r=await Td(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Wd.test(n))return;throw new Error(n)}}else {let r=await Ao(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Wd.test(n))return;throw new Error(n)}}}async function RS(e,t){try{await I(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Kn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function $S(e,t,r){try{await I(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Kn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function zd(e,t,r,n){try{await I(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Kn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function LS(e,t,r,n,o){try{await I(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Kn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function ui(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await RS(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let y=f.name??f.flowId,g=f.type??"unknown";if(!f.type){Kn.warn(`Artifact "${y}" has no type \u2014 treated as failed`),l.push({name:y,type:g,reason:"unknown artifact type"}),await zd(i,y,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await AS(f),u++,await $S(i,y,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let v=w instanceof Error?w.message:String(w);Kn.error(`Failed to install artifact "${y}": ${v}`),l.push({name:y,type:g,reason:v}),await zd(i,y,g,v),r?.({index:p+1,total:c,artifact:f,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await LS(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}B();function Zd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,ui(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",h(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ie()})}));B();function Qd({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Ct(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}B();function ep({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Ct(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((y,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:y.danger?"yellow":void 0,dimColor:!w,children:y.label})]},y.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function tp(e){return e.adapter.removable!==false?4:2}K();B();function rp({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",h(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:h(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",h(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",h(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:h(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",h(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",h(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",h(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function op({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function sp({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(T=>r.has(`${T.name}@${o}`)),i=t.filter(T=>!r.has(`${T.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((T,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(_=>Math.max(0,_-1));return}$.downArrow&&u(_=>Math.min(a.length-1,_+1));},{isActive:c===null}),c!==null)return jsx(rp,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Ye/2)),p=Math.min(a.length,m+Ye);p===a.length&&(m=Math.max(0,p-Ye));let f=a.slice(m,p),y=m,g=a.length-p,w=s.length>0&&m<s.length,v=p>s.length,D=f.filter(T=>r.has(`${T.name}@${o}`)),M=f.filter(T=>!r.has(`${T.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:y>0?`\u2191 ${y} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(T=>jsx(op,{item:T,isSelected:a.indexOf(T)===l,isInstalled:true},T.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),M.map(T=>jsx(op,{item:T,isSelected:a.indexOf(T)===l,isInstalled:false},T.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Xa();var BS=/^https?:\/\/.+/;function FS(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function jS(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function cp(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),y=useCallback(async()=>{let g=m.current,w=d.current;if(!BS.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let v=randomUUID(),D=new Dn(v,w,g);try{await D.fetchItems(),await Xt.add({id:v,name:w,source:g}),de.register(new Dn(v,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let T=FS(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":jS(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(T,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){y();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function up(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Xt.remove(o),de.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function pp(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=fe(A=>A.installedItems),[o,s]=useState(()=>de.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,y]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&y("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=de.listAdapters(),N=await Xt.read(),G=new Map(N.map($e=>[$e.id,$e]));s(A.map($e=>({adapter:$e,stored:G.get($e.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let N=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(G=>{N||p({items:G,loading:false,error:null});}).catch(G=>{N||p({items:[],loading:false,error:G instanceof Error?G.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let v=cp(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),y("main");},[w]),{handleRemove:M}=up(D),T=useCallback(async A=>{y("removing"),await M(A);},[M]),$=useCallback(async A=>{try{let N=await A.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),A.stored){let G=new Date().toISOString();await Xt.updateField(A.stored.id,{lastUpdated:G}),w();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[w,r]),_=useCallback(async A=>{if(!A.stored)return;let N=A.stored.autoUpdate!==false;await Xt.updateField(A.stored.id,{autoUpdate:!N}),w();},[w]),O=useCallback(()=>y("browse"),[]),ee=useCallback(A=>{let N=o[i-1];if(!N)return;let G=N.adapter.removable!==false;[O,()=>{$(N);},...G?[()=>{_(N);},()=>{T(N.adapter.id);}]:[]][A]?.();},[o,i,O,$,_,T]),k=useCallback(()=>y("main"),[]),H=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),Q=useCallback(()=>{let A=o[i-1];A&&_(A);},[o,i,_]),j=useCallback(()=>{let A=o[i-1];A&&T(A.adapter.id);},[o,i,T]);if(useInput((A,N)=>{if(N.upArrow){a(G=>Math.max(0,G-1));return}if(N.downArrow){a(G=>Math.min(o.length,G+1));return}(N.return||N.tab)&&(i===0?v.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&v.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,N)=>{if(N.escape||N.tab){u("list");return}if(N.upArrow){d(G=>Math.max(0,G-1));return}if(N.downArrow){let G=o[i-1],$e=G?tp(G)-1:0;d(qo=>Math.min(qo+1,$e));return}N.return&&ee(c);},{isActive:f==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(v.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let N=A.adapter.id??"default",G=new Set(n.filter($e=>$e.marketplace===A.adapter.name).map($e=>`${$e.name}@${N}`));return jsx(sp,{entry:A,items:m?.items??[],installedKeys:G,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let V=o[i-1]??null,z=V?n.filter(A=>A.marketplace===V.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Qd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&V?jsx(ep,{entry:V,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:H,onToggleAutoUpdate:Q,onRemove:j}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:V?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function mp(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=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o-1+ne.length)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}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:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function fp(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function gp(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}}var GS=new Set(ne.filter(e=>e.focus!=="list").map(e=>e.focus));function Bo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Je.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function hp({listLength:e}){let t=S(y=>y.focus),r=S(y=>y.selectedIndex),n=S(y=>y.actionMenuOpen),o=S(y=>y.setFocus),s=S(y=>y.setActionMenuOpen),i=Je(y=>y.query),a=Je(y=>y.setQuery),l=Je(y=>y.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:y,setCursorPosition:g}=Je.getState();g(y.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let y=setTimeout(()=>d(i),300);return ()=>clearTimeout(y)},[i]),useInput((y,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Bo(Ma(y,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((y,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Bo(Ma("",g,{activeTab:w}));},{isActive:GS.has(t)}),useInput((y,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();Bo(mp(y,g,{activeTab:w,selectedIndex:v},u.current));},{isActive:t==="list"}),useInput((y,g)=>{Bo(fp(y,g));},{isActive:t==="actionMenu"}),useInput((y,g)=>{let w=gp(y,g,Je.getState().query),v=w.queryUpdate;if(Bo(w.actions),v==="reset")l(),d("");else if(v!==null){let{query:D,cursorPosition:M,setCursorPosition:T}=Je.getState();if("backspace"in v)M>0&&(a(D.slice(0,M-1)+D.slice(M)),T(M-1));else if("append"in v)a(D.slice(0,M)+v.append+D.slice(M)),T(M+v.append.length);else if("cursorMove"in v){let $=M+v.cursorMove;$>=0&&$<=D.length&&T($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(y=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();y===0?g(0):w>=y&&g(y-1);},[]),f=useCallback(y=>{if(!c)return u.current=y.length,y;let g=c.toLowerCase(),w=y.filter(v=>v.name.toLowerCase().includes(g)||v.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function wp(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=et(a=>a.justAuthenticated),o=et(a=>a.credentials),s=et(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Ne(e,t,r=false){return r?true:!Sl.valid(e)||!Sl.valid(t)?false:Sl.gt(t,e)}K();R();var Qt=x("updater");async function WS(e,t,r,n,o,s){try{await I(b.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Z().interfaceType});}catch(i){Qt.warn(`Failed to send update metrics: ${String(i)}`);}}function zS(e){let t=st(),r=`${e}@${le}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function fi(e,t={}){let r=Date.now(),n=null;try{Qt.debug(`[${e}] Acquiring lock...`),n=await Tr();let o=zS(e);if(!o)throw Qt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Qt.debug(`[${e}] Fetching manifest...`);let u=(await On(e,t.source)).version;if(!i||!Ne(i,u,t.force))throw Qt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Er(e,i??"unknown");Qt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await De(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await WS(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Qt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Qt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Tr();let d=st(),m=`${e}@${le}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,ot(d),Qt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Pr();R();var gi=x("dispatcher");async function XS(e,t,r,n,o){let s=Ln(e);return gi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await ei(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),gi.debug(`[${e}] Retrying install after marketplace add`),Ae(t)}async function Sp(e,t,r,n){let o=Mn(e,n),s=Ln(e);r?.onStatus?.(`Installing ${s}...`),gi.debug(`[${e}] Attempting install: ${o}`);let i=await Ae(o);if(i.exitCode===0)return i;gi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return XS(e,o,a,t,r)}async function xp(e,t,r){let n=e.type??"bundle",o=await Bt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function bp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await xp(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=ie().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Bt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await ko(i,u,a),t();},[e,t]),s=useCallback(async i=>{await fi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}B();R();var yi=x("mcp");function Fo(e,t){e.silent?Qe({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function vp(e,t){e.silent?Te({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(te(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&P(t.stdout));}function qS(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 xl(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Ep(e,t,r){if(!await pe())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Fo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}yi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=qS(e,t,r.transport,r.scope);if(!r.force){let s=h(e),i=h(n);if(!await it(`Install external MCP "${s}"?
113
113
  This will run: ${i}
114
- [y/N] `))return hi.debug(`[${e}] Installation cancelled by user`),P("Operation cancelled."),0}let o=r.silent?void 0:Jl({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await ke(n);return o?.stop(),s.exitCode!==0?(No(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&P(`stdout: ${s.stdout}`),1):(bp(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),No(r,{name:e,action:"add",message:q(s)}),1}}async function vp(e,t){if(!await de())return 1;hi.debug(`[${e}] Starting MCP remove`);let r=wl(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await st(`Remove MCP "${o}"?
114
+ [y/N] `))return yi.debug(`[${e}] Installation cancelled by user`),P("Operation cancelled."),0}let o=r.silent?void 0:Wl({text:`Adding MCP "${h(e)}"...`}).start();try{let s=await Ae(n);return o?.stop(),s.exitCode!==0?(Fo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&P(`stdout: ${s.stdout}`),1):(vp(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Fo(r,{name:e,action:"add",message:q(s)}),1}}async function Pp(e,t){if(!await pe())return 1;yi.debug(`[${e}] Starting MCP remove`);let r=xl(e,t.scope);if(!t.force){let o=h(e),s=h(r);if(!await it(`Remove MCP "${o}"?
115
115
  This will run: ${s}
116
- [y/N] `))return hi.debug(`[${e}] Removal cancelled by user`),P("Operation cancelled."),0}let n=t.silent?void 0:Jl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await ke(r);return n?.stop(),o.exitCode!==0?(No(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&P(`stdout: ${o.stdout}`),1):(bp(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),No(t,{name:e,action:"remove",message:q(o)}),1}}$();function Ep({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(T=>T.setLoading),u=S(T=>T.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Sp(),f=async(T,R,_)=>{l(true,T),n();try{await R(),o(r.length),s(_,"success");}catch(O){let ee=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${ee}`),s(ee,"error");}finally{l(false);}};return {handleInstall:(T,R)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:T,...R!==void 0?{providerId:R}:{},onDownloadProgress:(_,O)=>{let ee=Date.now();(ee-a.current>100||_>=O)&&(a.current=ee,u(_,O));}}),"\u2713 Installed successfully"));},handleUninstall:T=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let R=e.status==="enabled";f(R?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,T),R?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${T}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch(_){if(_ instanceof vr)s(_.message,"info");else {let O=_ instanceof Error?_.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${O}`),s(O,"error");}}finally{l(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let R=T.length;(async()=>{l(true,`Updating ${R} plugin${R>1?"s":""}...`),n();try{let O=[];for(let H of T)O.push(await p(H.name).then(()=>({status:"fulfilled",value:void 0}),Q=>({status:"rejected",reason:Q})));let ee=O.filter(H=>H.status==="fulfilled").length,k=O.map((H,Q)=>H.status==="rejected"?T[Q].name:null).filter(H=>H!==null);o(r.length),k.length===0?s(`\u2713 Updated ${ee}/${R} plugin${R>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${ee}/${R}; failed: ${k.join(", ")}`,ee>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:T=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let R=wl(e.name,T),_=await ke(R);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}xo();$();var Bo=x("api:bundle"),Gn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Fo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},zS=/^[a-zA-Z0-9_-]{1,128}$/;async function Tp(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Bo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new Gn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new Fo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Bo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Cp(e){if(!zS.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Bo.debug(`Fetching bundle by flowId "${e}"`);try{return await Wt().get(`v1/use-cases/${t}`).json()}catch(r){return Tp(r,e)}}async function yi(e){let t=encodeURIComponent(e);Bo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Wt().get(`v1/use-cases/by-name/${t}`).json(),Bo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Tp(n,e)}if(r.length===0)throw new Gn(e);return r[0]}$();var XS=x("tui:bundle-flow");function kp({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();XS.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Cp(d):yi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),fe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}B();V();var jo=["local","project","user"],qS=new Set(["--transport","--scope","-s"]);function Ap(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(qS.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function rn(e,t){return t?`${e}::${t}`:e}function Sl(e){return e===me?Zn:an}function $p(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??Zn,flowId:e.flowId}}function xl(e,t){let r=Sl(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Rp(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 jo.filter(r=>t.has(r)).map(r=>({scope:r,label:Qn[r].label,pathHint:Qn[r].pathHint,items:t.get(r)??[]}))}function Lp(e){let t=r=>{if(!r)return 1/0;let n=jo.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Mp({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>rn(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[rn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(rn(g.name,g.author?.name))??h.get(g.name),v=w?.version,D=!!v&&!!g.version&&Ue(g.version,v);return {...g,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(rn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Ap(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>$p(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>xl(f,f.catalogItem)):a.map(f=>xl(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let h=f.type??"bundle";if(!n.types.has(h))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[rn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(rn(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function bl(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await sd();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,I(b.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function _p(){return {items:fe(t=>t.installedItems)}}$();var tx=x("catalog");function Op(){let e=S(X=>X.bundleInstallFlow),t=S(X=>X.activeTab),r=S(X=>X.notification),n=S(X=>X.loading),o=S(X=>X.loadingMessage),s=S(X=>X.downloadProgress),i=S(X=>X.downloadTotal),a=S(X=>X.catalogError),l=S(X=>X.setCatalogError),u=S(X=>X.catalogFilters),c=Ve(X=>X.query),{catalog:d,isLoading:m,error:p,refetch:f}=bl(),{items:h}=_p(),g=fe(X=>X.loadFromDisk),{items:w,emptyMessage:v,getSelectedCatalogItem:D,outdatedCount:M}=Mp({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:T,closeMenu:R,selectedIndex:_,clampIndex:O,filteredItems:ee}=fp({listLength:w.length}),k=ee(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:Lp(k),[t,k]),Q=useMemo(()=>t==="installed"||t==="updates"?Rp(H):[],[t,H]),j=H[_]??null,K=useMemo(()=>D(j),[D,j]),{notify:z}=hp(),{handleInstall:A,handleUninstall:N,handleToggleStatus:G,handleUpdate:$e,handleBatchUpdate:zo,handleMcpConfigUninstall:rg}=Ep({selectedItem:j,selectedCatalogItem:K,items:w,closeMenu:R,clampIndex:O,notify:z}),{handleBundleInstallStart:ng,handleBundleDetailConfirm:og,handleBundleDetailBack:sg,handleBundleInstallComplete:ig}=kp({closeMenu:R,notify:z}),ag=useCallback(()=>zo(H),[zo,H]);return useEffect(()=>{g();},[]),useEffect(()=>{O(H.length);},[H.length,O]),useEffect(()=>{p&&(tx.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Pn,{}),jsx(Su,{outdatedCount:M}),t==="marketplaces"&&wr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(up,{})}):jsx(Du,{filteredItems:H,groups:Q,emptyMessage:v,onBatchUpdate:ag}),(n||m)&&jsxs(Fragment,{children:[jsx(Fs,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Ks,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Vs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Ou,{message:r.message,type:r.type}),T&&j&&(t==="discover"?K?.type==="bundle"?e?.phase==="installing"?jsx(qd,{bundle:e.bundle,onComplete:ig}):jsx(Nd,{itemName:j.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>ng(j.name,j.flowId),onConfirm:og,onClose:e?.phase==="detail"?sg:R}):jsx(Od,{itemName:j.name,itemType:K?.type,onInstall:A,onClose:R}):j.type==="mcp"?jsx(Hd,{itemName:j.name,itemScope:j.scope??"user",onUninstall:rg,onClose:R}):jsx(jd,{itemName:j.name,itemScope:j.scope??"user",itemStatus:j.status??"enabled",updateAvailable:j.updateAvailable??false,catalogVersion:K?.version,onUninstall:N,onToggleStatus:X=>G(X),onUpdate:$e,onClose:R})),jsx(Bs,{})]})}var L=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",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(fe.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:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},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:"starterKitList"})}));Ie();var ix=3;function Np(){let e=L(c=>c.setStarterKits),t=L(c=>c.setIsLoadingStarterKits),r=L(c=>c.setStarterKitsError),n=L(c=>c.setPluginStatus),o=L(c=>c.setPluginDownloadProgress),s=L(c=>c.setStep),i=L(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await qs();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{fe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=L.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=ix;h++)try{await _e(m.name,{onDownloadProgress:(g,w)=>{let v=Date.now();(v-l.current>100||g>=w)&&(l.current=v,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof He){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Z().interfaceType}).catch(()=>{}));}let d=Kr();jr("summary_review"),I(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),fe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var Ko={cursorDelta:0,confirm:false,back:false};function Bp(e,t){return t.upArrow?{...Ko,cursorDelta:-1}:t.downArrow?{...Ko,cursorDelta:1}:t.escape?{...Ko,back:true}:t.return?{...Ko,confirm:true}:Ko}var ax={cursorDelta:0,select:false};function Fp(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:ax}B();var jp=iy.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:y(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:y(t.description)})})]})});var kl=5;function Kp({onRetry:e}){let t=L(c=>c.starterKits),r=L(c=>c.selectedStarterKitIndex),n=L(c=>c.isLoadingStarterKits),o=L(c=>c.starterKitsError);if(n)return jsx(Fs,{message:"Loading Starter Kits..."});if(o)return jsx(Vs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Tn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(kl/2)),i=Math.min(t.length,s+kl);i===t.length&&(s=Math.max(0,i-kl));let a=t.slice(s,i),l=s,u=t.length-i;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"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(jp,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}B();var Hp=iy.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:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});B();var Rl=8;function Jp(){let e=L(c=>c.selectedStarterKit),t=L(c=>c.plugins),r=L(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,I(b.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(c=>c.installed).length,s=Math.max(0,r-Math.floor(Rl/2)),i=Math.min(t.length,s+Rl);i===t.length&&(s=Math.max(0,i-Rl));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Hp,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}B();var hx=["Retry failed","Continue anyway"];function Gp({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Ks,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Wp({onComplete:e,onRetry:t}){let r=L(u=>u.plugins),n=L(u=>u.step),o=L(u=>u.successCount),s=L(u=>u.failedCount),i=L(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,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:a.map(u=>jsx(Gp,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.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"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(Gp,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:hx.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function zp(){let e=L(k=>k.step),t=L(k=>k.starterKits),r=L(k=>k.selectedStarterKitIndex),n=L(k=>k.setSelectedStarterKitIndex),o=L(k=>k.selectStarterKit),s=L(k=>k.plugins),i=L(k=>k.pluginCursorIndex),a=L(k=>k.setPluginCursorIndex),l=L(k=>k.setStep),u=L(k=>k.summaryActionIndex),c=L(k=>k.setSummaryActionIndex),d=L(k=>k.failedCount),m=L(k=>k.resetForRetry),p=L(k=>k.goBackToList),f=S(k=>k.setScreen),h=S(k=>k.setFocus),g=S(k=>k.focus),w=Qe(k=>k.setJustAuthenticated),v=Qe(k=>k.justAuthenticated),{loadStarterKits:D,installSelected:M}=Np(),T=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),T.current||(T.current=true,jr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let R=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let Q=await Y();Q&&await mr({...Q,starterKit:k.slug});}I(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Kr()}).catch(()=>{});let{successCount:H}=L.getState();I(b.CLI_ONBOARDING_COMPLETED,{duration_ms:gr(),tools_installed_count:H}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),_=useCallback(()=>{m(),M();},[m,M]),O=useCallback(()=>{D();},[D]),ee=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((k,H)=>{if(H.escape)Is("esc"),ee();else if(H.upArrow&&r>0)n(r-1);else if(H.downArrow&&r<t.length-1)n(r+1);else if(H.return&&t.length>0){let Q=Kr();o(t[r]),jr("kit_display"),I(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:Q}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,H)=>{let Q=Bp(k,H);if(Q.cursorDelta!==0){let j=i+Q.cursorDelta;j>=0&&j<s.length&&a(j);}if(Q.confirm){let j=L.getState().selectedStarterKit;j&&(async()=>(await Y())?.starterKit!==j.slug&&I(b.CLI_KIT_ACCEPTED,{bundle_slug:j.slug}).catch(()=>{}))();let K=Kr();jr("kit_confirmation"),I(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:K}).catch(()=>{});let z=Kr();jr("tool_installation"),I(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:z}).catch(()=>{}),l("installing"),M();}if(Q.back){let j=L.getState().selectedStarterKit;j&&I(b.CLI_KIT_REJECTED,{bundle_slug:j.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let Q=Fp(k,H);if(Q.cursorDelta!==0){let j=u+Q.cursorDelta;j>=0&&j<=1&&c(j);}Q.select&&(u===0?_():R());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Pn,{}),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."}),!v&&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==="starterKitList"&&jsx(Kp,{onRetry:O}),e==="starterKitDetail"&&jsx(Jp,{}),(e==="installing"||e==="summary")&&jsx(Wp,{onComplete:R,onRetry:_})]}),jsx(Bs,{})]})}V();var Yp=null;function Zp(){return Yp}async function Pi(){let t=Wr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=se.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Qp(n);(o||s)&&await ht({...r,installedVersion:o,installMethod:s});}}async function Qp(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Mt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function zn(e){let t=await Promise.all(e.map(r=>Sx(r)));return Yp=t,t}async function Sx(e){let t=Xp(e.versionCommand);t==="permission-denied"&&(xx(e.versionCommand[0]),t=Xp(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Mt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!et(e.alias)){let{installedVersion:l,installMethod:u}=await Qp(e);await ht({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Xp(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function xx(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=be__default.realpathSync(r),{mode:o}=be__default.statSync(n);be__default.chmodSync(n,o|73);}catch{}}function vx(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function om(e,t){let[r,n]=useState(()=>vx(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,h=m.upArrow||d==="[A",g=m.downArrow||d==="[B";if(h||g)h&&p>0?s(p-1):g&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let v=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(v+1)%w.availableStrategies.length];n(M=>M.map(T=>T.module.alias===w.module.alias?{...T,selectedStrategy:D}:T));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}B();function im({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=om(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let h=f===a,g=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(tt,{itemName:m,actions:d,onAction:c,onClose:u})]})}var kx=/^https?:\/\/.+/;function am({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&kx.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function $x(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function um(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=$x(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await br(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}V();B();function dm({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function gm({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=um(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{zr().catch(()=>{}),n("list");let w=ie().some(v=>v.name===le);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,v)=>{v.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,h=a-f,g=[];return h>0&&g.push(jsxs(Text,{color:"green",children:[h," installed"]},"i")),f>0&&g.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&g.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&g.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(dm,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,v,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(v),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function ym(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(eu(p)){zr().catch(()=>{}),l("list");let h=ie().some(g=>g.name===le);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=Zp();if(p){c(p);return}zn(se).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(h=>h.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(im,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(am,{onConfirm:m}),e==="installation"&&jsx(gm,{confirmedItems:o,customUrl:i})]})}V();$();var Fx=x("ClaudeMdSuggestion"),jx=[`Install ${le}`,"Skip for now"],Kx=["Retry","Skip for now"];function xm(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{I(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,I(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await _e(le),o("installed");}catch(m){if(m instanceof He){o("installed");return}Fx.warn(`Failed to install ${le}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Kx:jx;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Pn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Sm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",le,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",le," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",le]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",le]}),jsx(Sm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Sm({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var Gx=promisify(execFile),$i="@ciandt-flow/cli";async function bm(){let e=ce;if(yl.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:$i};try{let t=await fetch(`https://registry.npmjs.org/${$i}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:$i}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:$i}}}async function Ri(e){try{return await Gx(Jt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Wx(e){let t=et(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Mt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await ht({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Im(e){let t=await Wx(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function vm(e,t){let r=et(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Mt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ht({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Em(e){let r=et(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Pm(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...se.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([bm(),zn(se),Promise.all(se.map(l=>Im(l)))]);if(Pi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Ri(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=se.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await vm(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:Em(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await zr(),t(l=>({...l,outcome:"done"}));}catch{await zr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}V();function Qx({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Xd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function eb({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function Tm(){let{outcome:e,items:t}=Pm(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=ie().some(i=>i.name===le);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(Qx,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(eb,{outcome:e})})]})}Ie();xn();$();Zi();var ob={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Cm=10;function km(){let[e,t]=useState(Yi());useEffect(()=>yc(()=>{t([...Yi()]);}),[]);let r=e.slice(-Cm);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Cm,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:ob[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var lb=x("app"),cb={auth:du,starterKitSetup:zp,moduleSetup:ym,claudeMdSuggestion:xm,verify:Tm,main:Op};function Rm(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Os(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Lm(){I(b.CLI_SESSION_STARTED,{cli_version:ce,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});}async function _m(){let e=await Y();if(e&&Zc()&&await fr()){e.customUrl&&Ct(e.customUrl);let{clientSecret:n,...o}=e;Qe.getState().setCredentials(o),Lm(),Os(e);return}if(!e){Rm();return}try{e.customUrl&&Ct(e.customUrl),await At();}catch(n){lb.debug(`Token validation failed: ${String(n)}`),Rm();return}Lm();let{clientSecret:t,...r}=e;Qe.getState().setCredentials(r),Os(e);}function Dm(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=cb[r],{pendingExit:o}=Vc(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(km,{}),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]})}Ie();xs();B();V();$();oo();Ie();async function Vl(e,t={}){let r=Ps({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Ts(r),await mr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Et=x("auth");function Um(){Ke.clearFallbackFile(),hs();}var ub=3,Om=3,Nm=` \u2139 The data collected during setup is used solely to improve
116
+ [y/N] `))return yi.debug(`[${e}] Removal cancelled by user`),P("Operation cancelled."),0}let n=t.silent?void 0:Wl({text:`Removing MCP "${h(e)}"...`}).start();try{let o=await Ae(r);return n?.stop(),o.exitCode!==0?(Fo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&P(`stdout: ${o.stdout}`),1):(vp(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Fo(t,{name:e,action:"remove",message:q(o)}),1}}R();function Tp({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(T=>T.setLoading),u=S(T=>T.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=bp(),f=async(T,$,_)=>{l(true,T),n();try{await $(),o(r.length),s(_,"success");}catch(O){let ee=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${ee}`),s(ee,"error");}finally{l(false);}};return {handleInstall:(T,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:T,...$!==void 0?{providerId:$}:{},onDownloadProgress:(_,O)=>{let ee=Date.now();(ee-a.current>100||_>=O)&&(a.current=ee,u(_,O));}}),"\u2713 Installed successfully"));},handleUninstall:T=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,T),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${T}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch(_){if(_ instanceof Er)s(_.message,"info");else {let O=_ instanceof Error?_.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${O}`),s(O,"error");}}finally{l(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let $=T.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let O=[];for(let H of T)O.push(await p(H.name).then(()=>({status:"fulfilled",value:void 0}),Q=>({status:"rejected",reason:Q})));let ee=O.filter(H=>H.status==="fulfilled").length,k=O.map((H,Q)=>H.status==="rejected"?T[Q].name:null).filter(H=>H!==null);o(r.length),k.length===0?s(`\u2713 Updated ${ee}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${ee}/${$}; failed: ${k.join(", ")}`,ee>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:T=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=xl(e.name,T),_=await Ae($);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Io();R();var jo=x("api:bundle"),Wn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Ko=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},QS=/^[a-zA-Z0-9_-]{1,128}$/;async function kp(e,t){if(e instanceof HTTPError){let r=e.response.status;throw jo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new Wn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new Ko:new Error(`Server error (${r}) \u2014 please try again later.`)}throw jo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Ap(e){if(!QS.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);jo.debug(`Fetching bundle by flowId "${e}"`);try{return await zt().get(`v1/use-cases/${t}`).json()}catch(r){return kp(r,e)}}async function wi(e){let t=encodeURIComponent(e);jo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await zt().get(`v1/use-cases/by-name/${t}`).json(),jo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return kp(n,e)}if(r.length===0)throw new Wn(e);return r[0]}R();var ex=x("tui:bundle-flow");function Rp({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();ex.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Ap(d):wi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),fe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}B();K();var Vo=["local","project","user"],tx=new Set(["--transport","--scope","-s"]);function $p(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(tx.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function on(e,t){return t?`${e}::${t}`:e}function bl(e){return e===le?eo:ln}function Lp(e){return {name:h(e.name),version:e.version?h(e.version):e.version,description:e.description?h(e.description):e.description,authorName:e.author?.name?h(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??eo,flowId:e.flowId}}function Il(e,t){let r=bl(e.marketplace);return {name:h(e.name),version:e.version?h(e.version):e.version,description:e.description?h(e.description):e.description,authorName:e.author?.name?h(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Mp(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 Vo.filter(r=>t.has(r)).map(r=>({scope:r,label:to[r].label,pathHint:to[r].pathHint,items:t.get(r)??[]}))}function _p(e){let t=r=>{if(!r)return 1/0;let n=Vo.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Dp({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>on(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[on(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(on(g.name,g.author?.name))??y.get(g.name),v=w?.version,D=!!v&&!!g.version&&Ne(g.version,v);return {...g,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(on(f.name,f.author?.name)))return false;if(f.type==="mcp"){let y=f.installCommand?$p(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||y&&i.has(y))return false}return true}).map(f=>Lp(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>Il(f,f.catalogItem)):a.map(f=>Il(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let y=f.type??"bundle";if(!n.types.has(y))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[on(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(on(g.name,g.authorName))??y.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function vl(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await ad();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,I(b.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Op(){return {items:fe(t=>t.installedItems)}}R();var ix=x("catalog");function Np(){let e=S(X=>X.bundleInstallFlow),t=S(X=>X.activeTab),r=S(X=>X.notification),n=S(X=>X.loading),o=S(X=>X.loadingMessage),s=S(X=>X.downloadProgress),i=S(X=>X.downloadTotal),a=S(X=>X.catalogError),l=S(X=>X.setCatalogError),u=S(X=>X.catalogFilters),c=Je(X=>X.query),{catalog:d,isLoading:m,error:p,refetch:f}=vl(),{items:y}=Op(),g=fe(X=>X.loadFromDisk),{items:w,emptyMessage:v,getSelectedCatalogItem:D,outdatedCount:M}=Dp({catalog:d,installedItems:y,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:T,closeMenu:$,selectedIndex:_,clampIndex:O,filteredItems:ee}=hp({listLength:w.length}),k=ee(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:_p(k),[t,k]),Q=useMemo(()=>t==="installed"||t==="updates"?Mp(H):[],[t,H]),j=H[_]??null,V=useMemo(()=>D(j),[D,j]),{notify:z}=wp(),{handleInstall:A,handleUninstall:N,handleToggleStatus:G,handleUpdate:$e,handleBatchUpdate:qo,handleMcpConfigUninstall:ag}=Tp({selectedItem:j,selectedCatalogItem:V,items:w,closeMenu:$,clampIndex:O,notify:z}),{handleBundleInstallStart:lg,handleBundleDetailConfirm:cg,handleBundleDetailBack:ug,handleBundleInstallComplete:dg}=Rp({closeMenu:$,notify:z}),pg=useCallback(()=>qo(H),[qo,H]);return useEffect(()=>{g();},[]),useEffect(()=>{O(H.length);},[H.length,O]),useEffect(()=>{p&&(ix.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Tn,{}),jsx(bu,{outdatedCount:M}),t==="marketplaces"&&Sr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(pp,{})}):jsx(Uu,{filteredItems:H,groups:Q,emptyMessage:v,onBatchUpdate:pg}),(n||m)&&jsxs(Fragment,{children:[jsx(js,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Vs,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Hs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Nu,{message:r.message,type:r.type}),T&&j&&(t==="discover"?V?.type==="bundle"?e?.phase==="installing"?jsx(Zd,{bundle:e.bundle,onComplete:dg}):jsx(Fd,{itemName:j.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>lg(j.name,j.flowId),onConfirm:cg,onClose:e?.phase==="detail"?ug:$}):jsx(Nd,{itemName:j.name,itemType:V?.type,onInstall:A,onClose:$}):j.type==="mcp"?jsx(Gd,{itemName:j.name,itemScope:j.scope??"user",onUninstall:ag,onClose:$}):jsx(Vd,{itemName:j.name,itemScope:j.scope??"user",itemStatus:j.status??"enabled",updateAvailable:j.updateAvailable??false,catalogVersion:V?.version,onUninstall:N,onToggleStatus:X=>G(X),onUpdate:$e,onClose:$})),jsx(Fs,{})]})}var L=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",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(fe.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:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},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:"starterKitList"})}));Ie();var dx=3;function Fp(){let e=L(c=>c.setStarterKits),t=L(c=>c.setIsLoadingStarterKits),r=L(c=>c.setStarterKitsError),n=L(c=>c.setPluginStatus),o=L(c=>c.setPluginDownloadProgress),s=L(c=>c.setStep),i=L(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await Ys();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{fe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=L.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let y=1;y<=dx;y++)try{await De(m.name,{onDownloadProgress:(g,w)=>{let v=Date.now();(v-l.current>100||g>=w)&&(l.current=v,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof Ge){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),I(b.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Z().interfaceType}).catch(()=>{}));}let d=Hr();Vr("summary_review"),I(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),fe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var Ho={cursorDelta:0,confirm:false,back:false};function jp(e,t){return t.upArrow?{...Ho,cursorDelta:-1}:t.downArrow?{...Ho,cursorDelta:1}:t.escape?{...Ho,back:true}:t.return?{...Ho,confirm:true}:Ho}var px={cursorDelta:0,select:false};function Kp(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:px}B();var Vp=dy.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:h(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:h(t.description)})})]})});var Rl=5;function Hp({onRetry:e}){let t=L(c=>c.starterKits),r=L(c=>c.selectedStarterKitIndex),n=L(c=>c.isLoadingStarterKits),o=L(c=>c.starterKitsError);if(n)return jsx(js,{message:"Loading Starter Kits..."});if(o)return jsx(Hs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Cn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Rl/2)),i=Math.min(t.length,s+Rl);i===t.length&&(s=Math.max(0,i-Rl));let a=t.slice(s,i),l=s,u=t.length-i;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"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Vp,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}B();var Gp=dy.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:[" ",h(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});B();var Ml=8;function Wp(){let e=L(c=>c.selectedStarterKit),t=L(c=>c.plugins),r=L(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,I(b.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(c=>c.installed).length,s=Math.max(0,r-Math.floor(Ml/2)),i=Math.min(t.length,s+Ml);i===t.length&&(s=Math.max(0,i-Ml));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:h(e.name)}),jsx(Text,{dimColor:true,children:h(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Gp,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}B();var bx=["Retry failed","Continue anyway"];function zp({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=h(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Vs,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",h(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Xp({onComplete:e,onRetry:t}){let r=L(u=>u.plugins),n=L(u=>u.step),o=L(u=>u.successCount),s=L(u=>u.failedCount),i=L(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,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:a.map(u=>jsx(zp,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.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"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(zp,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:bx.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function qp(){let e=L(k=>k.step),t=L(k=>k.starterKits),r=L(k=>k.selectedStarterKitIndex),n=L(k=>k.setSelectedStarterKitIndex),o=L(k=>k.selectStarterKit),s=L(k=>k.plugins),i=L(k=>k.pluginCursorIndex),a=L(k=>k.setPluginCursorIndex),l=L(k=>k.setStep),u=L(k=>k.summaryActionIndex),c=L(k=>k.setSummaryActionIndex),d=L(k=>k.failedCount),m=L(k=>k.resetForRetry),p=L(k=>k.goBackToList),f=S(k=>k.setScreen),y=S(k=>k.setFocus),g=S(k=>k.focus),w=et(k=>k.setJustAuthenticated),v=et(k=>k.justAuthenticated),{loadStarterKits:D,installSelected:M}=Fp(),T=useRef(false);useEffect(()=>{e==="starterKitList"?(y("starterKitList"),T.current||(T.current=true,Vr("bundle_selection"))):y(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,y]);let $=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let Q=await Y();Q&&await fr({...Q,starterKit:k.slug});}I(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Hr()}).catch(()=>{});let{successCount:H}=L.getState();I(b.CLI_ONBOARDING_COMPLETED,{duration_ms:hr(),tools_installed_count:H}).catch(()=>{}),w(false),y("verify"),f("verify");},[w,y,f]),_=useCallback(()=>{m(),M();},[m,M]),O=useCallback(()=>{D();},[D]),ee=useCallback(()=>{y("verify"),f("verify");},[y,f]);return useInput((k,H)=>{if(H.escape)vs("esc"),ee();else if(H.upArrow&&r>0)n(r-1);else if(H.downArrow&&r<t.length-1)n(r+1);else if(H.return&&t.length>0){let Q=Hr();o(t[r]),Vr("kit_display"),I(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:Q}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,H)=>{let Q=jp(k,H);if(Q.cursorDelta!==0){let j=i+Q.cursorDelta;j>=0&&j<s.length&&a(j);}if(Q.confirm){let j=L.getState().selectedStarterKit;j&&(async()=>(await Y())?.starterKit!==j.slug&&I(b.CLI_KIT_ACCEPTED,{bundle_slug:j.slug}).catch(()=>{}))();let V=Hr();Vr("kit_confirmation"),I(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:V}).catch(()=>{});let z=Hr();Vr("tool_installation"),I(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:z}).catch(()=>{}),l("installing"),M();}if(Q.back){let j=L.getState().selectedStarterKit;j&&I(b.CLI_KIT_REJECTED,{bundle_slug:j.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let Q=Kp(k,H);if(Q.cursorDelta!==0){let j=u+Q.cursorDelta;j>=0&&j<=1&&c(j);}Q.select&&(u===0?_():$());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Tn,{}),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."}),!v&&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==="starterKitList"&&jsx(Hp,{onRetry:O}),e==="starterKitDetail"&&jsx(Wp,{}),(e==="installing"||e==="summary")&&jsx(Xp,{onComplete:$,onRetry:_})]}),jsx(Fs,{})]})}K();var Qp=null;function em(){return Qp}async function Ti(){let t=Xr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=se.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await tm(n);(o||s)&&await yt({...r,installedVersion:o,installMethod:s});}}async function tm(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await _t(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Xn(e){let t=await Promise.all(e.map(r=>Ex(r)));return Qp=t,t}async function Ex(e){let t=Yp(e.versionCommand);t==="permission-denied"&&(Px(e.versionCommand[0]),t=Yp(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await _t(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!tt(e.alias)){let{installedVersion:l,installMethod:u}=await tm(e);await yt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Yp(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function Px(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=be__default.realpathSync(r),{mode:o}=be__default.statSync(n);be__default.chmodSync(n,o|73);}catch{}}function kx(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function im(e,t){let[r,n]=useState(()=>kx(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,y=m.upArrow||d==="[A",g=m.downArrow||d==="[B";if(y||g)y&&p>0?s(p-1):g&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let v=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(v+1)%w.availableStrategies.length];n(M=>M.map(T=>T.module.alias===w.module.alias?{...T,selectedStrategy:D}:T));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}B();function lm({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=im(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let y=f===a,g=h(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:y?"cyan":void 0,children:[y?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:h(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(rt,{itemName:m,actions:d,onAction:c,onClose:u})]})}var Mx=/^https?:\/\/.+/;function cm({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&Mx.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function Dx(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function pm(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=Dx(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await Ir(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}K();B();function mm({module:e}){let t=h(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:h(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",h(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",h(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function ym({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=pm(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{qr().catch(()=>{}),n("list");let w=ie().some(v=>v.name===ce);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,v)=>{v.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,y=a-f,g=[];return y>0&&g.push(jsxs(Text,{color:"green",children:[y," installed"]},"i")),f>0&&g.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&g.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&g.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(mm,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,v,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(v),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Sm(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(ru(p)){qr().catch(()=>{}),l("list");let y=ie().some(g=>g.name===ce);u(y?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=em();if(p){c(p);return}Xn(se).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(y=>y.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(lm,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(cm,{onConfirm:m}),e==="installation"&&jsx(ym,{confirmedItems:o,customUrl:i})]})}K();R();var Jx=x("ClaudeMdSuggestion"),Gx=[`Install ${ce}`,"Skip for now"],Wx=["Retry","Skip for now"];function Im(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{I(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,I(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await De(ce),o("installed");}catch(m){if(m instanceof Ge){o("installed");return}Jx.warn(`Failed to install ${ce}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Wx:Gx;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Tn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(bm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ce,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ce," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",ce]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ce]}),jsx(bm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function bm({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var Yx=promisify(execFile),$i="@ciandt-flow/cli";async function vm(){let e=ue;if(Sl.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:$i};try{let t=await fetch(`https://registry.npmjs.org/${$i}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:$i}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:$i}}}async function Li(e){try{return await Yx(Gt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Zx(e){let t=tt(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await _t(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await yt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Em(e){let t=await Zx(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function Pm(e,t){let r=tt(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await _t(r.installMethod).update(e,t.currentVersion??"");return o.success?(await yt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Tm(e){let r=tt(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Cm(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...se.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([vm(),Xn(se),Promise.all(se.map(l=>Em(l)))]);if(Ti(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Li(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=se.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await Pm(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:Tm(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await qr(),t(l=>({...l,outcome:"done"}));}catch{await qr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}K();function ob({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Yd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function sb({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function km(){let{outcome:e,items:t}=Cm(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=ie().some(i=>i.name===ce);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(ob,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(sb,{outcome:e})})]})}Ie();bn();R();ea();var cb={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Am=10;function Rm(){let[e,t]=useState(Qi());useEffect(()=>Sc(()=>{t([...Qi()]);}),[]);let r=e.slice(-Am);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Am,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:cb[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var mb=x("app"),fb={auth:mu,starterKitSetup:qp,moduleSetup:Sm,claudeMdSuggestion:Im,verify:km,main:Np};function Mm(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Us(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function _m(){I(b.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:hr(),interface:"tui"}).catch(()=>{});}async function Om(){let e=await Y();if(e&&eu()&&await gr()){e.customUrl&&kt(e.customUrl);let{clientSecret:n,...o}=e;et.getState().setCredentials(o),_m(),Us(e);return}if(!e){Mm();return}try{e.customUrl&&kt(e.customUrl),await Rt();}catch(n){mb.debug(`Token validation failed: ${String(n)}`),Mm();return}_m();let{clientSecret:t,...r}=e;et.getState().setCredentials(r),Us(e);}function Um(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=fb[r],{pendingExit:o}=Jc(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Rm,{}),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]})}Ie();bs();B();K();R();io();Ie();async function Jl(e,t={}){let r=Ts({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Cs(r),await fr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Pt=x("auth");function Bm(){He.clearFallbackFile(),ys();}var gb=3,Nm=3,Fm=` \u2139 The data collected during setup is used solely to improve
117
117
  Flow's internal tools and will not be shared externally.
118
- `;function ir(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
118
+ `;function ar(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
119
119
  `){l(),process.stdout.write(`
120
- `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function db(){let e=Jr();return process.stdout.write(`
121
- `+C.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
122
- `),(await ir(C.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Bm(e,t,r){try{await Vl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof Gr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${Jr()} and retry.`);if(!await db())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Vl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function pb(){if((await ir(C.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await ir(C.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(cn.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${un}. Try again.
123
- `));}}async function mb(){let e=(await ir(C.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await ir(C.cyan(" ? ")+"Enter your email address: ")).trim();if(dn.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${pn}. Try again.
124
- `));}}async function Fm(e,t){process.stdout.write(C.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Ds(e,t);return r?process.stdout.write(C.yellow(` \u26A0 npm install failed. Please contact Flow support.
120
+ `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function hb(){let e=Wr();return process.stdout.write(`
121
+ `+C.yellow(" \u26A0 ")+`${h(e)} contains invalid JSON.
122
+ `),(await ar(C.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function jm(e,t,r){try{await Jl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof zr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${Wr()} and retry.`);if(!await hb())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Jl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function yb(){if((await ar(C.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await ar(C.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(un.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${dn}. Try again.
123
+ `));}}async function wb(){let e=(await ar(C.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await ar(C.cyan(" ? ")+"Enter your email address: ")).trim();if(pn.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${mn}. Try again.
124
+ `));}}async function Km(e,t){process.stdout.write(C.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Os(e,t);return r?process.stdout.write(C.yellow(` \u26A0 npm install failed. Please contact Flow support.
125
125
  `)):o?process.stdout.write(C.yellow(` \u26A0 Unexpected error. Please contact Flow support.
126
126
  `)):n?process.stdout.write(C.yellow(`
127
127
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
128
128
  `)):process.stdout.write(C.green(` done
129
- `)),{initFailed:n}}async function jm(){for(let e=1;e<=Om;e++)try{return await qs()}catch{if(e===Om)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Km(){let e=await jm();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
129
+ `)),{initFailed:n}}async function Vm(){for(let e=1;e<=Nm;e++)try{return await Ys()}catch{if(e===Nm)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Hm(){let e=await Vm();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
130
130
  `+C.cyan(" ? ")+`Starter Kit:
131
- `),e.forEach((t,r)=>{process.stdout.write(` ${C.cyan(`${r+1})`)} ${y(t.name)}
131
+ `),e.forEach((t,r)=>{process.stdout.write(` ${C.cyan(`${r+1})`)} ${h(t.name)}
132
132
  `);}),process.stdout.write(`
133
- `);;){let t=(await ir(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
134
- `));}}async function Vm(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
135
- Starter kit '${y(e.name)}' has no plugins to install.
133
+ `);;){let t=(await ar(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.
134
+ `));}}async function Jm(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
135
+ Starter kit '${h(e.name)}' has no plugins to install.
136
136
  `)),true;process.stdout.write(`
137
- Installing ${e.plugins.length} plugins from '${y(e.name)}'...
138
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(C.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=ub;a++)try{await _e(o),t++,i=!0;break}catch(l){if(l instanceof He){t++,i=true;break}}i?process.stdout.write(C.green(` done
137
+ Installing ${e.plugins.length} plugins from '${h(e.name)}'...
138
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(C.dim(` [${s}/${n}] Installing ${h(o)}...`));let i=false;for(let a=1;a<=gb;a++)try{await De(o),t++,i=!0;break}catch(l){if(l instanceof Ge){t++,i=true;break}}i?process.stdout.write(C.green(` done
139
139
  `)):(r++,process.stdout.write(C.red(` failed
140
- `)));}return r===0?process.stdout.write(C.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
141
- `)):process.stdout.write(C.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
142
- `)),r===0}async function Hm(){process.stdout.write(`
140
+ `)));}return r===0?process.stdout.write(C.green(` \u2713 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed successfully.
141
+ `)):process.stdout.write(C.yellow(` \u26A0 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
142
+ `)),r===0}async function Gm(){process.stdout.write(`
143
143
  `),process.stdout.write(C.bold(` Personalize your Claude Code
144
144
  `)),process.stdout.write(C.dim(` This plugin helps Claude understand your preferences and work style.
145
145
 
146
- `));let e=(await ir(C.cyan(" ? ")+`Install ${le}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){I(b.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(`
146
+ `));let e=(await ar(C.cyan(" ? ")+`Install ${ce}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){I(b.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(`
147
147
  You can always install it later from the catalog.
148
- `));return}I(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(` Installing ${le}...`));try{await _e(le),process.stdout.write(C.green(` done
149
- `));}catch(t){if(t instanceof He)process.stdout.write(C.green(` already installed
150
- `));else {Et.warn(`Failed to install ${le}: ${t instanceof Error?t.message:t}`),process.stdout.write(C.red(` failed
148
+ `));return}I(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(` Installing ${ce}...`));try{await De(ce),process.stdout.write(C.green(` done
149
+ `));}catch(t){if(t instanceof Ge)process.stdout.write(C.green(` already installed
150
+ `));else {Pt.warn(`Failed to install ${ce}: ${t instanceof Error?t.message:t}`),process.stdout.write(C.red(` failed
151
151
  `)),process.stdout.write(C.dim(` You can install it later from the catalog.
152
152
  `));return}}process.stdout.write(`
153
153
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
154
- `),process.stdout.write(C.cyan.bold(` /${le}
154
+ `),process.stdout.write(C.cyan.bold(` /${ce}
155
155
  `)),process.stdout.write(` Claude will guide you through the rest.
156
- `);}async function fb(e){if(Um(),process.stdout.write(`
157
- `+Nm+`
158
- `),e.customUrl!==void 0&&!cn.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${un}.
159
- `)),1;if(e.customEmail!==void 0&&!dn.test(e.customEmail))return process.stderr.write(C.red(` \u2717 ${pn}.
160
- `)),1;let t=e.jwt.trim(),r;try{r=go(t);}catch(o){let s=y(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${s}
161
- `)),1}e.customUrl&&Ct(e.customUrl),Et.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Fr(r);}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return Et.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${s}
162
- `)),1}let{initFailed:n}=await Fm(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await jm(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(C.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
156
+ `);}async function Sb(e){if(Bm(),process.stdout.write(`
157
+ `+Fm+`
158
+ `),e.customUrl!==void 0&&!un.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${dn}.
159
+ `)),1;if(e.customEmail!==void 0&&!pn.test(e.customEmail))return process.stderr.write(C.red(` \u2717 ${mn}.
160
+ `)),1;let t=e.jwt.trim(),r;try{r=yo(t);}catch(o){let s=h(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${s}
161
+ `)),1}e.customUrl&&kt(e.customUrl),Pt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Kr(r);}catch(o){let s=h(o instanceof Error?o.message:"unknown error");return Pt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${s}
162
+ `)),1}let{initFailed:n}=await Km(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Vm(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(C.red(` \u2717 Starter kit '${h(e.starterKit)}' not found.
163
163
  `)),process.stderr.write(` Available starter kits:
164
- `);for(let a of s)process.stderr.write(` - ${y(a.slug)} (${y(a.name)})
165
- `);return 1}o=i;}else o=await Km();return await Bm({...r,starterKit:o.slug,customUrl:e.customUrl},!1,t),await Vm(o),await Hm(),Et.info(`[${r.tenant}] Authentication successful`),process.stdout.write(C.green(`
166
- \u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${Jr()}.
164
+ `);for(let a of s)process.stderr.write(` - ${h(a.slug)} (${h(a.name)})
165
+ `);return 1}o=i;}else o=await Hm();return await jm({...r,starterKit:o.slug,customUrl:e.customUrl},!1,t),await Jm(o),await Gm(),Pt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(C.green(`
166
+ \u2713 Setup complete. Tenant: ${h(r.tenant)}. JWT written to ${Wr()}.
167
167
 
168
168
  `)),n&&process.stdout.write(C.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
169
- `)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return Et.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${s}
170
- `)),1}}async function gb(e,t){Um(),Et.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
171
- `),process.stdout.write(Nm+`
172
- `);let r=(await ir(C.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Et.error("[auth] Validation failed: JWT is required"),process.stderr.write(C.red(` \u2717 JWT is required
173
- `)),1;let n;try{n=go(r);}catch(l){let u=y(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${u}
174
- `)),1}let o=e??await pb(),s=t??await mb();o&&Ct(o),Et.debug(`[${n.tenant}] Authenticating tenant`);try{await Fr(n);}catch(l){let u=y(l instanceof Error?l.message:"unknown error");return Et.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${u}
175
- `)),1}let{initFailed:i}=await Fm(o,s),a=await Km();return await Bm({...n,starterKit:a.slug,customUrl:o??void 0},!0,r),await Vm(a),await Hm(),Et.info(`[${n.tenant}] Authentication successful`),process.stdout.write(C.green(`
176
- \u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${Jr()}.
169
+ `)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=h(o instanceof Error?o.message:"unknown error");return Pt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${s}
170
+ `)),1}}async function xb(e,t){Bm(),Pt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
171
+ `),process.stdout.write(Fm+`
172
+ `);let r=(await ar(C.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Pt.error("[auth] Validation failed: JWT is required"),process.stderr.write(C.red(` \u2717 JWT is required
173
+ `)),1;let n;try{n=yo(r);}catch(l){let u=h(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${u}
174
+ `)),1}let o=e??await yb(),s=t??await wb();o&&kt(o),Pt.debug(`[${n.tenant}] Authenticating tenant`);try{await Kr(n);}catch(l){let u=h(l instanceof Error?l.message:"unknown error");return Pt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${u}
175
+ `)),1}let{initFailed:i}=await Km(o,s),a=await Hm();return await jm({...n,starterKit:a.slug,customUrl:o??void 0},!0,r),await Jm(a),await Gm(),Pt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(C.green(`
176
+ \u2713 Setup complete. Tenant: ${h(n.tenant)}. JWT written to ${Wr()}.
177
177
 
178
178
  `)),i&&process.stdout.write(C.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
179
- `)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return Et.error(`[auth] Unexpected error: ${n}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${n}
180
- `)),1}}async function Hl(e={}){if(e.jwt)return fb({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!cn.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${un}.
181
- `)),1;if(e.customEmail!==void 0&&!dn.test(e.customEmail))return process.stderr.write(C.red(` \u2717 ${pn}.
182
- `)),1;try{return await gb(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
183
- `),130;throw t}}async function hb(){try{return process.stdout.write(`
184
- `),(await ir(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
179
+ `)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=h(r instanceof Error?r.message:"unknown error");return Pt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${n}
180
+ `)),1}}async function Gl(e={}){if(e.jwt)return Sb({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!un.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${dn}.
181
+ `)),1;if(e.customEmail!==void 0&&!pn.test(e.customEmail))return process.stderr.write(C.red(` \u2717 ${mn}.
182
+ `)),1;try{return await xb(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
183
+ `),130;throw t}}async function bb(){try{return process.stdout.write(`
184
+ `),(await ar(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
185
185
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
186
- `),130;throw e}}async function Jm(e){if(!await Y())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
187
- `)),0;if(!e){let t=await hb();if(t!==null)return t}try{return await Ac(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
186
+ `),130;throw e}}async function Wm(e){if(!await Y())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
187
+ `)),0;if(!e){let t=await bb();if(t!==null)return t}try{return await $c(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
188
188
  `)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
189
- `)),1}}async function Gm(){let e=await Y();return e?await fr()?(process.stdout.write(`
189
+ `)),1}}async function zm(){let e=await Y();return e?await gr()?(process.stdout.write(`
190
190
  `+C.bold(` Authenticated
191
- `)),process.stdout.write(C.dim(" Tenant: ")+y(e.tenant)+`
192
- `),process.stdout.write(C.dim(" Client ID: ")+y(e.clientId)+`
193
- `),process.stdout.write(C.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
194
- `),process.stdout.write(C.dim(" Config: ")+y(await $c())+`
191
+ `)),process.stdout.write(C.dim(" Tenant: ")+h(e.tenant)+`
192
+ `),process.stdout.write(C.dim(" Client ID: ")+h(e.clientId)+`
193
+ `),process.stdout.write(C.dim(" Starter Kit: ")+h(e.starterKit??"not set")+`
194
+ `),process.stdout.write(C.dim(" Config: ")+h(await Lc())+`
195
195
  `),process.stdout.write(`
196
- `),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)}B();V();async function yb(e){let t=ie(),r;try{r=await Xt(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(ur(r.map(o=>({...o,installed:n.has(o.name)}))),0):(hn(["","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 wb(e){let t=ie(),r=await Xt(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ue(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(P("All plugins are up to date."),0):e.json?(ur(o),0):(hn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
196
+ `),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)}B();K();Ke();K();var vb=[le,"flow-harness"];function Xm(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Eb(e,t,r=process.env){return Xm(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Xm(r.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:t?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:t?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function qm(e){switch(e.reason){case "env-disabled":return "DISABLE_AUTOUPDATER is set";case "env-forced":return "FORCE_AUTOUPDATE_PLUGINS is set";case "flag":return e.enabled?"autoUpdate: true":"autoUpdate: false";case "default":return "default (no explicit flag)"}}function _i(e=process.env){let t=Ur();if(!be__default.existsSync(t))return [];try{let r=JSON.parse(be__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>Eb(n,o,e))}catch{return []}}function Ym(){let e=Ur(),t={fixed:[],skipped:[]};if(!be__default.existsSync(e))return t;let r;try{r=JSON.parse(be__default.readFileSync(e,"utf-8"));}catch{return t.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),t}let n=false;for(let o of vb){let s=r[o];if(!s){t.skipped.push({name:o,reason:"not registered on this machine"});continue}if("autoUpdate"in s){t.skipped.push({name:o,reason:s.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}s.autoUpdate=true,t.fixed.push(o),n=true;}if(n){let o=`${e}.${randomUUID()}.tmp`;be__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),be__default.renameSync(o,e);}return t}async function Pb(e){let t=ie(),r;try{r=await qt(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(dr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(yn(["","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 Tb(e){let t=ie(),r=await qt(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ne(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(P("All plugins are up to date."),0):e.json?(dr(o),0):(yn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
197
197
  ${o.length} plugin(s) outdated.
198
- `),0)}async function Sb(e){let t=ie();if(I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return P("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return ur(t),0;let r=[];try{r=await Xt(e.source);}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=jo.indexOf(s.scope??"user"),l=jo.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return hn(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??Sl(s.marketplace);return [s.name??"",s.version??"n/a",ln[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",Tt(s.installedAt??"")]})),process.stdout.write(`
198
+ `),0)}async function Cb(e){let t=ie();if(I(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return P("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return dr(t),0;let r=[];try{r=await qt(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(_i().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=Vo.indexOf(i.scope??"user"),u=Vo.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return yn(["Name","Version","Type","Origin","Scope","Status","Auto-Update","Installed at"],s.map(i=>{let a=n.get(i.name),l=a?.type??"bundle",u=a?.origin??bl(i.marketplace),c=i.marketplace?o.get(i.marketplace):void 0,d=c===void 0?"n/a":c?"on":"off";return [i.name??"",i.version??"n/a",cn[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,Ct(i.installedAt??"")]})),process.stdout.write(`
199
199
  ${t.length} plugin(s) installed.
200
- `),0}async function Wm(e){if(!await de())return 1;try{return e.available?await yb(e):e.outdated?await wb(e):await Sb(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}Er();B();V();$();var pe=x("manage");function Mi(e,t){return t?ie().find(r=>r.name===e&&r.scope===t):ie().find(r=>r.name===e)}function xb(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,P(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Jl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function bb(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(Ln(e,r.scope));if(!await st(`${t}Install external plugin "${i}"?
200
+ `),0}async function Zm(e){if(!await pe())return 1;try{return e.available?await Pb(e):e.outdated?await Tb(e):await Cb(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}Pr();B();K();R();var me=x("manage");function Di(e,t){return t?ie().find(r=>r.name===e&&r.scope===t):ie().find(r=>r.name===e)}function kb(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,P(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Wl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Ab(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=h(e),a=h(Mn(e,r.scope));if(!await it(`${t}Install external plugin "${i}"?
201
201
  This will run: ${a}
202
- [y/N] `))return pe.debug(`[${e}] Installation cancelled by user`),r.silent||P(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Jl({text:`${t}Installing ${e}...`}).start());}let s=o?xb(t,o):void 0;try{let i=await yp(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ze({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Pe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):te(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=q(i);return r.silent?Ze({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Ib(e,t,r){let n=r.silent?void 0:Jl({text:`${t}Installing ${e}...`}).start();if($n(e))return bb(e,t,r,n);try{let o=await _e(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=js(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${u})`;}});return n?.stop(),r.silent?Pe({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):te(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof He)return r.silent?Pe({status:"already_installed",plugin:e,message:o.message}):P(`${t}${o.message}`),{name:e,success:true};let s=q(o);return r.silent?Ze({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function vb(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;P(`
203
- Installation summary: ${t} succeeded, ${r} failed`);}async function Eb(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await Xt();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function _i(e,t={}){if(!await de())return 1;let r=[],n=await Eb(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await Ib(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?Pe({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):vb(r)),r.some(o=>!o.success)?1:0}async function zm(e,t){if(!await de())return 1;if(pe.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Mi(e,t.scope);if(!r)return pe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await st(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return pe.debug(`[${e}] Uninstall cancelled by user`),P("Operation cancelled."),0}try{return pe.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Po(e,t.scope),pe.info(`[${e}] Uninstalled successfully`),te("Plugin removed successfully"),0}catch(r){return pe.error(`[${e}] Failed to uninstall: ${q(r)}`),E(q(r)),1}}async function Xm(e,t={}){if(!await de())return 1;pe.debug(`[${e}] Looking up installed plugin`);let r=Mi(e,t.scope);if(!r)return pe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return pe.debug(`[${e}] Already enabled, skipping`),P(`${r.name} is already enabled`),0;try{return pe.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await To(e,"enabled",t.scope),pe.info(`[${e}] Enabled successfully`),te(`${r.name} enabled successfully`),0}catch(n){return pe.error(`[${e}] Failed to enable: ${q(n)}`),E(q(n)),1}}async function qm(e,t={}){if(!await de())return 1;pe.debug(`[${e}] Looking up installed plugin`);let r=Mi(e,t.scope);if(!r)return pe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return pe.debug(`[${e}] Already disabled, skipping`),P(`${r.name} is already disabled`),0;try{return pe.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await To(e,"disabled",t.scope),pe.info(`[${e}] Disabled successfully`),te(`${r.name} disabled successfully`),0}catch(n){return pe.error(`[${e}] Failed to disable: ${q(n)}`),E(q(n)),1}}async function Ym(e,t,r){r.silent||P(`${t}Updating ${e}...`);try{let n=await mi(e,r);return r.silent?Pe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):te(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof vr)return r.silent?Pe({status:"up_to_date",plugin:e,message:n.message}):P(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=q(n);return r.silent?Ze({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Pb(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;P(`
204
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Tb(e,t,r){try{let n=await Dn(e,r.source);Ue(t,n.version,r.force)?P(`Would update ${e}: v${t} \u2192 v${n.version}`):P(`${e} is already up to date (v${t})`);}catch(n){return E(q(n)),1}return 0}function Cb(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function kb(e,t,r){let n=t.get(e.name);return n?e.version&&Ue(e.version,n,r)?(P(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(P(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(P(`Skipping ${e.name}: not found in catalog`),false)}async function Ab(e,t){try{let r=await Xt(t.source),n=Cb(r),o=0;for(let s of e)kb(s,n,t.force)&&o++;o===0&&P("All plugins are up to date");}catch(r){return E(q(r)),1}return 0}async function $b(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Ym(e[n].name,o,t);r.push(s);}return t.silent?Pe({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}:{}}))}):Pb(r),r.some(n=>!n.success)?1:0}async function Zm(e,t={}){if(!await de())return 1;if(e){let o=Mi(e,t.scope);return o?t.dryRun?Tb(e,o.version??"",t):(await Ym(e,"",t)).success?0:1:(t.silent?Ze({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=ie().filter(o=>o.marketplace===me);return n.length===0?(t.silent?Pe({status:"empty",message:"No plugins installed"}):P("No plugins installed"),0):t.dryRun?Ab(n,t):$b(n,t)}B();$();var Go=x("cli:bundle");function Rb(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function Lb(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
205
- Bundle: ${y(e)} (${t.length} artifacts)
206
- `);for(let o of t)process.stdout.write(`${Rb(o)}
202
+ [y/N] `))return me.debug(`[${e}] Installation cancelled by user`),r.silent||P(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Wl({text:`${t}Installing ${e}...`}).start());}let s=o?kb(t,o):void 0;try{let i=await Sp(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Qe({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Te({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):te(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=q(i);return r.silent?Qe({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Rb(e,t,r){let n=r.silent?void 0:Wl({text:`${t}Installing ${e}...`}).start();if($n(e))return Ab(e,t,r,n);try{let o=await De(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=Ks(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${u})`;}});return n?.stop(),r.silent?Te({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):te(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof Ge)return r.silent?Te({status:"already_installed",plugin:e,message:o.message}):P(`${t}${o.message}`),{name:e,success:true};let s=q(o);return r.silent?Qe({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function $b(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;P(`
203
+ Installation summary: ${t} succeeded, ${r} failed`);}async function Lb(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await qt();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function Oi(e,t={}){if(!await pe())return 1;let r=[],n=await Lb(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await Rb(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?Te({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):$b(r)),r.some(o=>!o.success)?1:0}async function Qm(e,t){if(!await pe())return 1;if(me.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Di(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;let n=h(r.name),o=r.version?h(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await it(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return me.debug(`[${e}] Uninstall cancelled by user`),P("Operation cancelled."),0}try{return me.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Co(e,t.scope),me.info(`[${e}] Uninstalled successfully`),te("Plugin removed successfully"),0}catch(r){return me.error(`[${e}] Failed to uninstall: ${q(r)}`),E(q(r)),1}}async function ef(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Di(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return me.debug(`[${e}] Already enabled, skipping`),P(`${r.name} is already enabled`),0;try{return me.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await ko(e,"enabled",t.scope),me.info(`[${e}] Enabled successfully`),te(`${r.name} enabled successfully`),0}catch(n){return me.error(`[${e}] Failed to enable: ${q(n)}`),E(q(n)),1}}async function tf(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Di(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return me.debug(`[${e}] Already disabled, skipping`),P(`${r.name} is already disabled`),0;try{return me.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await ko(e,"disabled",t.scope),me.info(`[${e}] Disabled successfully`),te(`${r.name} disabled successfully`),0}catch(n){return me.error(`[${e}] Failed to disable: ${q(n)}`),E(q(n)),1}}async function rf(e,t,r){r.silent||P(`${t}Updating ${e}...`);try{let n=await fi(e,r);return r.silent?Te({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):te(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Er)return r.silent?Te({status:"up_to_date",plugin:e,message:n.message}):P(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=q(n);return r.silent?Qe({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Mb(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;P(`
204
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function _b(e,t,r){try{let n=await On(e,r.source);Ne(t,n.version,r.force)?P(`Would update ${e}: v${t} \u2192 v${n.version}`):P(`${e} is already up to date (v${t})`);}catch(n){return E(q(n)),1}return 0}function Db(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Ob(e,t,r){let n=t.get(e.name);return n?e.version&&Ne(e.version,n,r)?(P(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(P(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(P(`Skipping ${e.name}: not found in catalog`),false)}async function Ub(e,t){try{let r=await qt(t.source),n=Db(r),o=0;for(let s of e)Ob(s,n,t.force)&&o++;o===0&&P("All plugins are up to date");}catch(r){return E(q(r)),1}return 0}async function Nb(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await rf(e[n].name,o,t);r.push(s);}return t.silent?Te({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):Mb(r),r.some(n=>!n.success)?1:0}async function nf(e,t={}){if(!await pe())return 1;if(e){let o=Di(e,t.scope);return o?t.dryRun?_b(e,o.version??"",t):(await rf(e,"",t)).success?0:1:(t.silent?Qe({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=ie().filter(o=>o.marketplace===le);return n.length===0?(t.silent?Te({status:"empty",message:"No plugins installed"}):P("No plugins installed"),0):t.dryRun?Ub(n,t):Nb(n,t)}B();R();var zo=x("cli:bundle");function Bb(e){let t=h(e.name??e.flowId),r=h(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function Fb(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
205
+ Bundle: ${h(e)} (${t.length} artifacts)
206
+ `);for(let o of t)process.stdout.write(`${Bb(o)}
207
207
  `);process.stdout.write(`
208
208
  ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
209
209
 
210
- `);}async function Qm(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await de())return 1;Go.debug(`Fetching bundle "${e}"`);let r;try{r=await yi(e);}catch(a){return a instanceof Gn||a instanceof Fo?(E(a.message),1):(E(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(Go.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Lb(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await st(`Install ${o.length} artifact(s)? [Y/n] `))return Go.debug("Installation cancelled by user"),0;Go.debug(`Starting installation of ${o.length} artifact(s)`);let i=await ci(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
210
+ `);}async function of(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await pe())return 1;zo.debug(`Fetching bundle "${e}"`);let r;try{r=await wi(e);}catch(a){return a instanceof Wn||a instanceof Ko?(E(a.message),1):(E(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(zo.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Fb(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await it(`Install ${o.length} artifact(s)? [Y/n] `))return zo.debug("Installation cancelled by user"),0;zo.debug(`Starting installation of ${o.length} artifact(s)`);let i=await ui(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=h(u.name??u.flowId),p=h(u.type??"unknown"),f=c?"\u2713":`\u2717 (${h(d??"failed")})`;a===1&&process.stdout.write(`
211
211
  `),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
212
212
  `),a===l&&process.stdout.write(`
213
- `);}});if(Go.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&te(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");P(`${i.skipped} unavailable: ${a}`);}return 0}Er();B();$();var ef=x("marketplace");function _b(e){return `claude plugin marketplace add ${e}`}async function tf(e,t){if(!await de())return 1;let r;try{r=Xs(e);}catch(s){let i=q(s);return t.silent?Ze({status:"error",source:e,message:i}):E(i),1}ef.debug(`[marketplace] Adding marketplace source: ${r}`);let n=_b(r);if(!t.force){let s=y(r),i=y(n);if(!await st(`Add marketplace "${s}"?
213
+ `);}});if(zo.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&te(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${h(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>h(l.name??l.flowId)).join(", ");P(`${i.skipped} unavailable: ${a}`);}return 0}Pr();B();R();var sf=x("marketplace");function Kb(e){return `claude plugin marketplace add ${e}`}async function af(e,t){if(!await pe())return 1;let r;try{r=qs(e);}catch(s){let i=q(s);return t.silent?Qe({status:"error",source:e,message:i}):E(i),1}sf.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Kb(r);if(!t.force){let s=h(r),i=h(n);if(!await it(`Add marketplace "${s}"?
214
214
  This will run: ${i}
215
- [y/N] `))return ef.debug("[marketplace] Operation cancelled by user"),P("Operation cancelled."),0}let o=t.silent?void 0:Jl({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await ke(n);return o?.stop(),s.exitCode!==0?(t.silent?Ze({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&P(`stdout: ${s.stdout}`)),1):(t.silent?Pe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(te(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&P(s.stdout)),0)}catch(s){o?.stop();let i=q(s);return t.silent?Ze({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}Ie();B();async function Nb(){return await Y()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Bb(){let e=Date.now();try{await Xt();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 Fb(){return await fr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function jb(){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 rf(){process.stdout.write(`
215
+ [y/N] `))return sf.debug("[marketplace] Operation cancelled by user"),P("Operation cancelled."),0}let o=t.silent?void 0:Wl({text:`Adding marketplace "${h(r)}"...`}).start();try{let s=await Ae(n);return o?.stop(),s.exitCode!==0?(t.silent?Qe({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&P(`stdout: ${s.stdout}`)),1):(t.silent?Te({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(te(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&P(s.stdout)),0)}catch(s){o?.stop();let i=q(s);return t.silent?Qe({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}Ie();B();async function Gb(){return await Y()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Wb(){let e=Date.now();try{await qt();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 zb(){return await gr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Xb(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function qb(){let e=_i();if(e.length!==0){process.stdout.write(`
216
+ `+C.bold(` Marketplace Auto-Update
217
+
218
+ `));for(let t of e){let r=t.enabled?C.green("[ON] "):C.dim("[OFF]"),n=h(t.name).padEnd(20),o=h(qm(t));process.stdout.write(` ${r} ${n} ${C.dim(o)}
219
+ `);}}}function Yb(){process.stdout.write(`
220
+ `+C.bold(` FlowSetup CLI \u2014 Auto-Update Fix
221
+
222
+ `));let e=Ym();for(let t of e.fixed)process.stdout.write(` ${C.green("[FIXED]")} ${h(t)} \u2014 autoUpdate: true set
223
+ `);for(let{name:t,reason:r}of e.skipped)process.stdout.write(` ${C.dim("[SKIP] ")} ${h(t)} \u2014 ${h(r)}
224
+ `);return process.stdout.write(`
225
+ `),e.fixed.length===0?process.stdout.write(C.dim(` Nothing to fix \u2014 all set.
226
+
227
+ `)):process.stdout.write(C.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
228
+
229
+ `)),0}async function lf(e={}){if(e.fix)return Yb();process.stdout.write(`
216
230
  `+C.bold(` FlowSetup CLI Diagnostics
217
231
 
218
- `));let e=[{name:"Credentials",fn:Nb},{name:"Prompt Manager",fn:Bb},{name:"Valid Token",fn:Fb},{name:"Claude Code",fn:jb}],t=true;for(let r of e){let n=await r.fn(),o="",s=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),s=C.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
219
- `);}return process.stdout.write(`
220
- `),t?(process.stdout.write(C.green(` \u2713 All checks passed!
232
+ `));let t=[{name:"Credentials",fn:Gb},{name:"Prompt Manager",fn:Wb},{name:"Valid Token",fn:zb},{name:"Claude Code",fn:Xb}],r=true;for(let n of t){let o=await n.fn(),s="",i=C.green;o.passed?s=C.green("[OK] "):(s=C.red("[FAIL]"),i=C.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${h(o.message)}`;process.stdout.write(a+`
233
+ `);}return qb(),process.stdout.write(`
234
+ `),r?(process.stdout.write(C.green(` \u2713 All checks passed!
221
235
 
222
236
  `)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
223
237
 
224
- `)),1)}Ie();Br();V();async function nf(e){let t=await Y(),r=kt("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Vt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await Qu.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}xn();Ss();Ie();B();$();var Vb=x("commands:usage"),Di=20,of="EMAIL",sf="MONTHLY CONSUMPTION (USD)",af="STATUS";function Hb(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Di),n=Di-r,o=C.green;return t>=90?o=C.red:t>=70&&(o=C.yellow),o("\u2588".repeat(r))+C.dim("\u2591".repeat(n))}function lf(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Jb(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?C.green(`\u2299 ${n}`):t==="warning"?C.yellow(`\u26A0 ${n}`):t==="blocked"?C.red("\u2717 Budget limit reached"):C.red(`\u2717 ${n}`)}function Gb(e){let t=Tt(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function Wb(e){try{let t=await wn();if(t?.email)return y(t.email);let r=Sn(e);return y(r.email??"")}catch(t){return Vb.debug(`JWT email decode failed: ${String(t)}`),""}}async function cf(e){if(!await de())return 1;let r;try{r=await At();}catch(g){return E(`Authentication error: ${q(g)}`),1}let n;try{n=await nf(r);}catch(g){return E(`Failed to fetch usage data: ${q(g)}`),1}if(e.json)return ur(n),0;let o=await Wb(r)||y(n.user_id),s=lf(n.consumed_usd),i=lf(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(of.length,o.length+2),c=Math.max(sf.length,Di+2+l.length),d=` ${of.padEnd(u)} ${sf.padEnd(c)} ${af}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(af.length)}`,p=`${C.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${Hb(n.percentage)} ${l.padEnd(c-Di-2)}`,h=` ${C.dim("Resets")} ${Gb(n.renewal_date)}`;return process.stdout.write(`
238
+ `)),1)}Ie();jr();K();async function cf(e){let t=await Y(),r=At("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Ht.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await td.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}bn();xs();Ie();B();R();var Qb=x("commands:usage"),Ui=20,uf="EMAIL",df="MONTHLY CONSUMPTION (USD)",pf="STATUS";function eI(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Ui),n=Ui-r,o=C.green;return t>=90?o=C.red:t>=70&&(o=C.yellow),o("\u2588".repeat(r))+C.dim("\u2591".repeat(n))}function mf(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function tI(e){let t=e.toLowerCase(),r=h(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?C.green(`\u2299 ${n}`):t==="warning"?C.yellow(`\u26A0 ${n}`):t==="blocked"?C.red("\u2717 Budget limit reached"):C.red(`\u2717 ${n}`)}function rI(e){let t=Ct(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function nI(e){try{let t=await Sn();if(t?.email)return h(t.email);let r=xn(e);return h(r.email??"")}catch(t){return Qb.debug(`JWT email decode failed: ${String(t)}`),""}}async function ff(e){if(!await pe())return 1;let r;try{r=await Rt();}catch(g){return E(`Authentication error: ${q(g)}`),1}let n;try{n=await cf(r);}catch(g){return E(`Failed to fetch usage data: ${q(g)}`),1}if(e.json)return dr(n),0;let o=await nI(r)||h(n.user_id),s=mf(n.consumed_usd),i=mf(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(uf.length,o.length+2),c=Math.max(df.length,Ui+2+l.length),d=` ${uf.padEnd(u)} ${df.padEnd(c)} ${pf}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(pf.length)}`,p=`${C.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${eI(n.percentage)} ${l.padEnd(c-Ui-2)}`,y=` ${C.dim("Resets")} ${rI(n.renewal_date)}`;return process.stdout.write(`
225
239
  `),process.stdout.write(C.dim(d)+`
226
240
  `),process.stdout.write(C.dim(m)+`
227
- `),process.stdout.write(` ${p} ${f} ${Jb(n.status)}
228
- `),process.stdout.write(h+`
241
+ `),process.stdout.write(` ${p} ${f} ${tI(n.status)}
242
+ `),process.stdout.write(y+`
229
243
  `),process.stdout.write(`
230
- `),0}var qb=["github.com","www.github.com"],Yb=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Zb=/^([^@]+)@(.+)$/;function Qb(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Gl(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 eI(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 s=t.slice(4).join("/");o.subpath=Gl(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Gl(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Oi(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Qb(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:")&&qb.includes(r.hostname))return eI(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 s={type:"git",url:r};return n&&(s.ref=n),s}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let s=r.match(Yb);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(Zb);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=Gl(m));}return d}}return {type:"git",url:t}}function Ui(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}}function uf(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 zl=new Set(["node_modules",".git","dist","build","__pycache__"]);function mf(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function sI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Wl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Wo(e){try{let t=await readFile(e,"utf-8"),{data:r}=uf(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 ff(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Wl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!zl.has(a.name)).map(a=>ff(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Fi(e,t){let r=[],n=new Set;if(t&&!sI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Wl(o)){let i=await Wo(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let u=join(i,l.name);if(await Wl(u)){let c=await Wo(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await ff(o);for(let a of i){let l=await Wo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function gf(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}qe();var Sf=1,dI={retries:5,minTimeout:50};async function xf(e,t){mkdirSync(dirname(e),{recursive:true});let r=await kh.lock(e+".lock",{realpath:false,retries:dI});try{return await t()}finally{await r();}}function hf(){return {version:Sf,skills:{}}}async function ji(e){let t=to(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Sf?hf():n}catch{return hf()}}function pI(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function bf(e,t){let r=to(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:pI(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
231
- `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function If(e,t,r){let n=to(r);await xf(n,async()=>{let o=await ji(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await bf(o,r);});}async function vf(e,t){let r=to(t);await xf(r,async()=>{let n=await ji(t);e in n.skills&&(delete n.skills[e],await bf(n,t));});}qe();$();var Ef=x("skillInstaller");async function xI(e,t,r,n){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Z().interfaceType});}catch(o){Ef.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function bI(e,t){try{await I(b.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:Z().interfaceType});}catch(r){Ef.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function II(e,t){await cp(e,t,{recursive:true,dereference:false,filter:r=>{if(zl.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function vI(e,t,r){let n=it(e.name),o=Or(t),s=join(o,n);if(!mf(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await II(e.path,s);let a=Ui(r)??r.url;return await If(n,{source:a,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:s}}catch(i){return {skill:e.name,success:false,path:s,error:i instanceof Error?i.message:String(i)}}}async function Pf(e,t){let r=Oi(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 Dt(r.url,r.ref),o=n;let s=await Fi(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?gf(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await vI(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await xI(c.name,t.scope,u,p):await bI(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await Ot(n).catch(()=>{});}}qe();B();$();var kI=x("skills");async function AI(e){try{await I(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Z().interfaceType});}catch(t){kI.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function $I(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function RI(e){let t=Oi(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else P(`Fetching skills from ${y(e)}...`),r=await Dt(t.url,t.ref),n=r;let o=await Fi(n,t.subpath);if(o.length===0)return P("No skills found in this source."),0;let i=Ui(t)??y(e);P(`Found ${o.length} skill(s) in ${i}:
232
- `);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${C.bold(l)} ${C.dim(u)}
244
+ `),0}var iI=["github.com","www.github.com"],aI=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,lI=/^([^@]+)@(.+)$/;function cI(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function zl(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 uI(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 s=t.slice(4).join("/");o.subpath=zl(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=zl(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Ni(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(cI(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:")&&iI.includes(r.hostname))return uI(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 s={type:"git",url:r};return n&&(s.ref=n),s}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let s=r.match(aI);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(lI);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=zl(m));}return d}}return {type:"git",url:t}}function Bi(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}}function gf(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 ql=new Set(["node_modules",".git","dist","build","__pycache__"]);function wf(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function gI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Xl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Xo(e){try{let t=await readFile(e,"utf-8"),{data:r}=gf(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 Sf(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Xl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!ql.has(a.name)).map(a=>Sf(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ki(e,t){let r=[],n=new Set;if(t&&!gI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Xl(o)){let i=await Xo(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let u=join(i,l.name);if(await Xl(u)){let c=await Xo(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Sf(o);for(let a of i){let l=await Xo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function xf(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}Ke();var Ef=1,bI={retries:5,minTimeout:50};async function Pf(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Mh.lock(e+".lock",{realpath:false,retries:bI});try{return await t()}finally{await r();}}function bf(){return {version:Ef,skills:{}}}async function Vi(e){let t=no(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Ef?bf():n}catch{return bf()}}function II(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Tf(e,t){let r=no(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:II(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
245
+ `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Cf(e,t,r){let n=no(r);await Pf(n,async()=>{let o=await Vi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Tf(o,r);});}async function kf(e,t){let r=no(t);await Pf(r,async()=>{let n=await Vi(t);e in n.skills&&(delete n.skills[e],await Tf(n,t));});}Ke();R();var Af=x("skillInstaller");async function RI(e,t,r,n){try{await I(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Z().interfaceType});}catch(o){Af.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function $I(e,t){try{await I(b.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:Z().interfaceType});}catch(r){Af.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function LI(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(ql.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function MI(e,t,r){let n=at(e.name),o=Nr(t),s=join(o,n);if(!wf(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await LI(e.path,s);let a=Bi(r)??r.url;return await Cf(n,{source:a,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:s}}catch(i){return {skill:e.name,success:false,path:s,error:i instanceof Error?i.message:String(i)}}}async function Rf(e,t){let r=Ni(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 Ot(r.url,r.ref),o=n;let s=await Ki(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?xf(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await MI(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await RI(c.name,t.scope,u,p):await $I(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await Ut(n).catch(()=>{});}}Ke();B();R();var NI=x("skills");async function BI(e){try{await I(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Z().interfaceType});}catch(t){NI.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function FI(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${h(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function jI(e){let t=Ni(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else P(`Fetching skills from ${h(e)}...`),r=await Ot(t.url,t.ref),n=r;let o=await Ki(n,t.subpath);if(o.length===0)return P("No skills found in this source."),0;let i=Bi(t)??h(e);P(`Found ${o.length} skill(s) in ${i}:
246
+ `);for(let a of o){let l=h(a.name),u=h(a.description);process.stdout.write(` ${C.bold(l)} ${C.dim(u)}
233
247
  `);}return process.stdout.write(`
234
- `),0}catch(n){return n instanceof Cr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await Ot(r).catch(()=>{});}}function LI(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);te(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
235
- `);let t=e.source;e.installed>0&&P(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&E(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?P("No skills found in this source."):e.results.length===0&&e.discovered>0&&P(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Cf(e,t){if(t.list)return RI(e);let r=t.global?"global":"project";try{let n=await Pf(e,{scope:r,skillFilter:t.skill,yes:t.yes});return LI(n),n.failed>0?1:0}catch(n){return n instanceof Cr?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function kf(e){let t=Or(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=join(t,o.name),i=join(s,"SKILL.md");try{if(!(await stat(i)).isFile())continue}catch{continue}let a=await Wo(i);a?r.push({name:a.name,description:a.description,path:s}):r.push({name:o.name,description:"(no metadata)",path:s});}}catch{}return r}async function Af(e){let t=e.global?"global":"project",r=await kf(t),n=await ji(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[it(i.name)]?.source}));return ur(s),0}if(r.length===0)return P(`No skills installed (${t==="global"?"global":"project"} scope).`),0;P(`${t==="global"?"Global":"Project"} skills (${r.length}):
236
- `);for(let s of r){let i=n.skills[it(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?C.dim(` (${i})`):"";process.stdout.write(` ${C.bold(a)}${c}
248
+ `),0}catch(n){return n instanceof kr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await Ut(r).catch(()=>{});}}function KI(e){for(let r of e.results){let n=h(r.skill);if(r.success){let o=relative(process.cwd(),r.path);te(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${h(r.error??"unknown error")}`);}process.stdout.write(`
249
+ `);let t=e.source;e.installed>0&&P(`Installed ${e.installed} of ${e.discovered} skill(s) from ${h(t)}`),e.failed>0&&E(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?P("No skills found in this source."):e.results.length===0&&e.discovered>0&&P(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Lf(e,t){if(t.list)return jI(e);let r=t.global?"global":"project";try{let n=await Rf(e,{scope:r,skillFilter:t.skill,yes:t.yes});return KI(n),n.failed>0?1:0}catch(n){return n instanceof kr?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function Mf(e){let t=Nr(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=join(t,o.name),i=join(s,"SKILL.md");try{if(!(await stat(i)).isFile())continue}catch{continue}let a=await Xo(i);a?r.push({name:a.name,description:a.description,path:s}):r.push({name:o.name,description:"(no metadata)",path:s});}}catch{}return r}async function _f(e){let t=e.global?"global":"project",r=await Mf(t),n=await Vi(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[at(i.name)]?.source}));return dr(s),0}if(r.length===0)return P(`No skills installed (${t==="global"?"global":"project"} scope).`),0;P(`${t==="global"?"Global":"Project"} skills (${r.length}):
250
+ `);for(let s of r){let i=n.skills[at(s.name)]?.source,a=h(s.name),l=h(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?C.dim(` (${i})`):"";process.stdout.write(` ${C.bold(a)}${c}
237
251
  `),process.stdout.write(` ${C.dim(u)}
238
252
 
239
- `);}return 0}async function $f(e,t){let r=t.global?"global":"project";if(!e){let i=await kf(r);if(i.length===0)return P("No skills installed."),0;P("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
253
+ `);}return 0}async function Df(e,t){let r=t.global?"global":"project";if(!e){let i=await Mf(r);if(i.length===0)return P("No skills installed."),0;P("Installed skills:");for(let a of i)process.stdout.write(` - ${h(a.name)}
240
254
  `);return process.stdout.write(`
241
- `),P("Specify a skill name to remove: flow skills remove <name>"),1}let n=it(e),o=Or(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await $I(`Remove skill "${y(n)}"?`))return P("Cancelled."),0;try{return await rm(s,{recursive:!0,force:!0}),await vf(n,r),await AI(n),te(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}B();$();V();var Ki=x("transfer"),ql=1;function MI(e){return e.marketplace&&e.marketplace!==me?`${e.name}@${e.marketplace}`:e.name}function _I(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&P(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),P(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Mf(e){let t=xe__default.resolve(e.output);try{let r=ie(),n={version:ql,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return be__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),te(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=q(r);return Ki.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function _f(e,t={}){if(!await de())return 1;let r;try{let a=be__default.readFileSync(xe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${q(a)}`),1}if(r.version!==ql)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${ql}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return P("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;Ki.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Ki.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&P(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(ie().map(l=>l.name));_I(n,a);}if(t.dryRun)return P("Dry-run mode: no plugins were installed"),0;if(n.length===0){P(`
242
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}P(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=MI(a);Ki.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await _i([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}P(`
243
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}$();B();function F(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}B();$();var OI=x("moduleProxy");function UI(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Df(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await I(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{OI.warn(`Failed to emit proxy executed event: ${String(s)}`);}),F(o);}async function Uf(e,t){let r=se.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),F(1);return}if(!await Rt(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),F(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Mt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),F(1);return}if(await UI("Would you like to install it now? [Y/n] ")){await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await br(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),F(1);return}await Df(r,t);}else P(`To install manually, run: flow modules install ${e}`),await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),F(1);return}await Df(r,t);}B();var jI=promisify(execFile);async function KI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await jI(Jt(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ce}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(n.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let o=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t.signal,headers:n});return o.ok?(await o.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(r);}}catch{return null}}function VI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ue(t,r)?"outdated":"installed"}async function Yl(){let e=await Promise.all(se.map(async t=>{let[r,n]=await Promise.all([Rt(t.binaryName),KI(t)]),s=et(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=VI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return hn(["Name","Alias","Version","Status","Platform"],e),0}async function Ff(e){let t=se.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await zn([t]);if(r.alreadyInstalled){let i=et(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return P(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Jl({text:`Installing ${t.name}...`}).start(),s;try{s=await br(t,"on_demand",n);}finally{o.stop();}return s.success?(te(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function Nf(e,t){let r=Jl({text:`Updating ${e.name}...`}).start(),n;try{n=await Ms(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function jf(e){if(e!==null){let n=se.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=et(n.alias);return o?.installMethod?await Nf(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Wr().filter(n=>n.installMethod!==null);if(t.length===0)return P("No installed modules to update."),0;let r=0;for(let n of t){let o=se.find(i=>i.alias===n.alias);if(!o)continue;await Nf(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var Kf="b10864926258503a01a6afc980d3f4216004ee41",Vf=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
255
+ `),P("Specify a skill name to remove: flow skills remove <name>"),1}let n=at(e),o=Nr(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${h(e)}" is not installed.`),1}if(!t.force&&!await FI(`Remove skill "${h(n)}"?`))return P("Cancelled."),0;try{return await rm(s,{recursive:!0,force:!0}),await kf(n,r),await BI(n),te(`Skill "${h(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}B();R();K();var Hi=x("transfer"),Zl=1;function VI(e){return e.marketplace&&e.marketplace!==le?`${e.name}@${e.marketplace}`:e.name}function HI(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&P(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),P(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Nf(e){let t=xe__default.resolve(e.output);try{let r=ie(),n={version:Zl,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return be__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),te(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=q(r);return Hi.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function Bf(e,t={}){if(!await pe())return 1;let r;try{let a=be__default.readFileSync(xe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${q(a)}`),1}if(r.version!==Zl)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Zl}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return P("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;Hi.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Hi.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&P(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(ie().map(l=>l.name));HI(n,a);}if(t.dryRun)return P("Dry-run mode: no plugins were installed"),0;if(n.length===0){P(`
256
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}P(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=VI(a);Hi.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await Oi([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}P(`
257
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();B();function F(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}B();R();var GI=x("moduleProxy");function WI(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=al.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Ff(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await I(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{GI.warn(`Failed to emit proxy executed event: ${String(s)}`);}),F(o);}async function Kf(e,t){let r=se.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),F(1);return}if(!await Lt(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),F(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await _t(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),F(1);return}if(await WI("Would you like to install it now? [Y/n] ")){await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Ir(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),F(1);return}await Ff(r,t);}else P(`To install manually, run: flow modules install ${e}`),await I(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),F(1);return}await Ff(r,t);}B();var YI=promisify(execFile);async function ZI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await YI(Gt(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ue}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(n.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let o=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t.signal,headers:n});return o.ok?(await o.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(r);}}catch{return null}}function QI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ne(t,r)?"outdated":"installed"}async function Ql(){let e=await Promise.all(se.map(async t=>{let[r,n]=await Promise.all([Lt(t.binaryName),ZI(t)]),s=tt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=QI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return yn(["Name","Alias","Version","Status","Platform"],e),0}async function Jf(e){let t=se.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await Xn([t]);if(r.alreadyInstalled){let i=tt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return P(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Wl({text:`Installing ${t.name}...`}).start(),s;try{s=await Ir(t,"on_demand",n);}finally{o.stop();}return s.success?(te(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function Vf(e,t){let r=Wl({text:`Updating ${e.name}...`}).start(),n;try{n=await _s(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function Gf(e){if(e!==null){let n=se.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=tt(n.alias);return o?.installMethod?await Vf(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Xr().filter(n=>n.installMethod!==null);if(t.length===0)return P("No installed modules to update."),0;let r=0;for(let n of t){let o=se.find(i=>i.alias===n.alias);if(!o)continue;await Vf(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var Wf="b10864926258503a01a6afc980d3f4216004ee41",zf=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
244
258
  title: "0-current-state \u2014 Index"
245
259
  type: index
246
260
  domain: platform
@@ -502,26 +516,26 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
502
516
  **6. Source code never in monitored folders.**
503
517
  If you create a folder with app or script source code, keep it out of the 5 numbered folders
504
518
  entirely (e.g. \`prototypes/\`).
505
- `},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];var Hf=".flow-harness-lock";function Jf(e){if(!existsSync(e))return {};try{let t=readFileSync(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return {}}}function Gf(e,t){return e.files?.[t]?.sha256}function Wf(e,t,r,n){let o={...t.files??{}};for(let[i,a]of Object.entries(r))o[i]={sha256:a};let s={...t,files:o,strategy_context:true,strategy_context_source:`@ciandt-flow/cli@${ce}`,strategy_context_harness_commit:n};"core_commit"in t||(s.core_commit=""),writeFileSync(e,JSON.stringify(s,null,2)+`
506
- `,"utf8");}B();function QI(e){return createHash("sha256").update(e,"utf8").digest("hex")}function ev(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function Xf(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??rv,i=join(t,Hf),a=Jf(i),l=[],u=ev(),c={};for(let m of Vf){let p=join(t,m.path),f=await tv({dstPath:p,template:m,existingLockHash:Gf(a,m.path),force:n,isInteractive:o,confirmOverwrite:h=>s(h)});l.push({path:m.path,status:f.status}),u[f.status]++,f.write&&!r&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8")),f.recordHash&&!r&&(c[m.path]=f.recordHash);}!r&&Object.keys(c).length>0&&Wf(i,a,c,Kf);let d=u.divergent>0||u.declined>0;return {files:l,counts:u,hasUnresolved:d}}async function tv(e){let{dstPath:t,template:r,existingLockHash:n,force:o,isInteractive:s,confirmOverwrite:i}=e;if(!existsSync(t))return {status:"new",write:true,recordHash:r.sha256};let a=QI(readFileSync(t,"utf8"));return a===r.sha256?{status:"unchanged",write:false,recordHash:r.sha256}:n!==void 0&&a===n?o?{status:"clean",write:true,recordHash:r.sha256}:s?await i(r.path)?{status:"clean",write:true,recordHash:r.sha256}:{status:"declined",write:false,recordHash:void 0}:{status:"declined",write:false,recordHash:void 0}:o?{status:"divergent",write:true,recordHash:r.sha256}:(P(`divergent, kept local (customized): ${r.path}`),{status:"divergent",write:false,recordHash:a})}async function rv(e){return st(` Overwrite ${e} with the updated template? [y/N] `)}B();$();Ie();Br();$();var Zl=x("lib:otelMetrics"),ov="flow-plugins-cli",sv="1.0.0",iv=5e3;function av(){return kt("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function lv(e,t){return typeof t=="number"?{key:e,value:{intValue:String(t)}}:typeof t=="boolean"?{key:e,value:{boolValue:t}}:{key:e,value:{stringValue:t}}}function cv(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:ov,version:sv},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>lv(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Ql(e,t={}){try{let[r,n]=await Promise.all([wn(),Y()]),o=r?.email,s=n?.tenant;if(!o||!s){Zl.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=cv(e,t);await Qu.post(av(),{json:i,timeout:iv,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Zl.debug(`OTel metric sent: ${e}`);}catch(r){Zl.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var ec=x("cli:init");function uv(e){switch(e){case "new":return "new";case "unchanged":return "unchanged";case "clean":return "updated";case "divergent":return "kept (customized)";case "declined":return "pending (declined)"}}function dv(e,t,r,n){I(b.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_updated:e.clean,files_divergent:e.divergent,files_declined:e.declined,dry_run:t,duration_ms:n,exit_code:r}).catch(o=>{ec.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),Ql("flow_cli.strategy_init",{dry_run:t,files_new:e.new,files_updated:e.clean,exit_code:r}).catch(()=>{});}function pv(e,t){I(b.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{ec.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),Ql("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function qf(e){ec.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let t=Date.now(),r;try{r=await Xf({targetDir:e.path,dryRun:e.dryRun,force:e.force});}catch(c){throw pv(c instanceof Error?c.message:String(c),Date.now()-t),c}let n=r.hasUnresolved?2:0;if(dv(r.counts,!!e.dryRun,n,Date.now()-t),e.json)return Pe({dryRun:!!e.dryRun,counts:r.counts,files:r.files,exitCode:n}),n;let o=e.dryRun?"[dry-run] ":"";process.stdout.write(`
507
- `);for(let c of r.files)process.stdout.write(` ${o}${uv(c.status)}: ${c.path}
519
+ `},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];var Xf=".flow-harness-lock";function qf(e){if(!existsSync(e))return {};try{let t=readFileSync(e,"utf8"),r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}catch{return {}}}function Yf(e,t){return e.files?.[t]?.sha256}function Zf(e,t,r,n){let o={...t.files??{}};for(let[i,a]of Object.entries(r))o[i]={sha256:a};let s={...t,files:o,strategy_context:true,strategy_context_source:`@ciandt-flow/cli@${ue}`,strategy_context_harness_commit:n};"core_commit"in t||(s.core_commit=""),writeFileSync(e,JSON.stringify(s,null,2)+`
520
+ `,"utf8");}B();function cv(e){return createHash("sha256").update(e,"utf8").digest("hex")}function uv(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function eg(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??pv,i=join(t,Xf),a=qf(i),l=[],u=uv(),c={};for(let m of zf){let p=join(t,m.path),f=await dv({dstPath:p,template:m,existingLockHash:Yf(a,m.path),force:n,isInteractive:o,confirmOverwrite:y=>s(y)});l.push({path:m.path,status:f.status}),u[f.status]++,f.write&&!r&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8")),f.recordHash&&!r&&(c[m.path]=f.recordHash);}!r&&Object.keys(c).length>0&&Zf(i,a,c,Wf);let d=u.divergent>0||u.declined>0;return {files:l,counts:u,hasUnresolved:d}}async function dv(e){let{dstPath:t,template:r,existingLockHash:n,force:o,isInteractive:s,confirmOverwrite:i}=e;if(!existsSync(t))return {status:"new",write:true,recordHash:r.sha256};let a=cv(readFileSync(t,"utf8"));return a===r.sha256?{status:"unchanged",write:false,recordHash:r.sha256}:n!==void 0&&a===n?o?{status:"clean",write:true,recordHash:r.sha256}:s?await i(r.path)?{status:"clean",write:true,recordHash:r.sha256}:{status:"declined",write:false,recordHash:void 0}:{status:"declined",write:false,recordHash:void 0}:o?{status:"divergent",write:true,recordHash:r.sha256}:(P(`divergent, kept local (customized): ${r.path}`),{status:"divergent",write:false,recordHash:a})}async function pv(e){return it(` Overwrite ${e} with the updated template? [y/N] `)}B();R();Ie();jr();R();var ec=x("lib:otelMetrics"),fv="flow-plugins-cli",gv="1.0.0",hv=5e3;function yv(){return At("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function wv(e,t){return typeof t=="number"?{key:e,value:{intValue:String(t)}}:typeof t=="boolean"?{key:e,value:{boolValue:t}}:{key:e,value:{stringValue:t}}}function Sv(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:fv,version:gv},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>wv(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function tc(e,t={}){try{let[r,n]=await Promise.all([Sn(),Y()]),o=r?.email,s=n?.tenant;if(!o||!s){ec.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=Sv(e,t);await td.post(yv(),{json:i,timeout:hv,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),ec.debug(`OTel metric sent: ${e}`);}catch(r){ec.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var rc=x("cli:init");function xv(e){switch(e){case "new":return "new";case "unchanged":return "unchanged";case "clean":return "updated";case "divergent":return "kept (customized)";case "declined":return "pending (declined)"}}function bv(e,t,r,n){I(b.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_updated:e.clean,files_divergent:e.divergent,files_declined:e.declined,dry_run:t,duration_ms:n,exit_code:r}).catch(o=>{rc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),tc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,files_updated:e.clean,exit_code:r}).catch(()=>{});}function Iv(e,t){I(b.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{rc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),tc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function tg(e){rc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let t=Date.now(),r;try{r=await eg({targetDir:e.path,dryRun:e.dryRun,force:e.force});}catch(c){throw Iv(c instanceof Error?c.message:String(c),Date.now()-t),c}let n=r.hasUnresolved?2:0;if(bv(r.counts,!!e.dryRun,n,Date.now()-t),e.json)return Te({dryRun:!!e.dryRun,counts:r.counts,files:r.files,exitCode:n}),n;let o=e.dryRun?"[dry-run] ":"";process.stdout.write(`
521
+ `);for(let c of r.files)process.stdout.write(` ${o}${xv(c.status)}: ${c.path}
508
522
  `);process.stdout.write(`
509
- `);let{new:s,unchanged:i,clean:a,divergent:l,declined:u}=r.counts;return te(`${s} new, ${i} unchanged, ${a} updated, ${l} kept (customized)`+(u>0?`, ${u} pending confirmation`:"")),l>0&&P("Some files were kept as-is because they differ from what this command last wrote. Re-run with --force to overwrite them."),u>0&&P("Some updates were declined or skipped (no TTY). Re-run with --force to apply them."),n!==0&&E("flow setup strategy finished with unresolved files \u2014 see above."),n}function Yf(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ce}`,"-V, --version","Display the CLI version").addHelpText("after",`
523
+ `);let{new:s,unchanged:i,clean:a,divergent:l,declined:u}=r.counts;return te(`${s} new, ${i} unchanged, ${a} updated, ${l} kept (customized)`+(u>0?`, ${u} pending confirmation`:"")),l>0&&P("Some files were kept as-is because they differ from what this command last wrote. Re-run with --force to overwrite them."),u>0&&P("Some updates were declined or skipped (no TTY). Re-run with --force to apply them."),n!==0&&E("flow setup strategy finished with unresolved files \u2014 see above."),n}function rg(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ue}`,"-V, --version","Display the CLI version").addHelpText("after",`
510
524
  Without arguments, opens the interactive interface (TUI).
511
525
  Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
512
526
  Examples:
513
- $ flow setup init`).action(async()=>{let c=await Hl();F(c);}),r.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addHelpText("after",`
527
+ $ flow setup init`).action(async()=>{let c=await Gl();F(c);}),r.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addHelpText("after",`
514
528
  Examples:
515
529
  $ flow setup strategy
516
530
  $ flow setup strategy --dry-run
517
531
  $ flow setup strategy --force
518
- $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await qf({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path});F(d);}),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).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
532
+ $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await tg({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path});F(d);}),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).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
519
533
  Examples:
520
534
  $ flow plugin list
521
535
  $ flow plugin list --available
522
536
  $ flow plugin list --outdated
523
537
  $ flow plugin list --json
524
- $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await Wm(c);F(d);}),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").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
538
+ $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await Zm(c);F(d);}),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").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
525
539
  Examples:
526
540
  $ flow plugin install flow-adr-writer
527
541
  $ flow plugin install flow-adr-writer --scope project
@@ -530,11 +544,11 @@ Examples:
530
544
  $ flow plugin install flow-adr-writer --silent
531
545
  $ flow plugin install superpowers@claude-plugins-official
532
546
  $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
533
- $ flow plugin install runbook-design --source flow-harness`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){E("No valid plugin names provided"),F(1);return}je("cli",{verbose:d.verbose,silent:d.silent});let p=await _i(m,d);F(p);}),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",`
547
+ $ flow plugin install runbook-design --source flow-harness`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){E("No valid plugin names provided"),F(1);return}Ve("cli",{verbose:d.verbose,silent:d.silent});let p=await Oi(m,d);F(p);}),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",`
534
548
  Examples:
535
549
  $ flow plugin uninstall flow-adr-writer
536
550
  $ flow plugin uninstall flow-adr-writer --scope project
537
- $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await zm(c,d);F(m);}),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",`
551
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await Qm(c,d);F(m);}),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",`
538
552
  Examples:
539
553
  $ flow plugin update flow-adr-writer
540
554
  $ flow plugin update flow-adr-writer --scope project
@@ -543,78 +557,79 @@ Examples:
543
557
  $ flow plugin update flow-adr-writer --verbose
544
558
  $ flow plugin update flow-adr-writer --silent
545
559
  $ flow plugin update
546
- $ flow plugin update --dry-run`).action(async(c,d)=>{je("cli",{verbose:d.verbose,silent:d.silent});let m=await Zm(c??null,d);F(m);}),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",`
560
+ $ flow plugin update --dry-run`).action(async(c,d)=>{Ve("cli",{verbose:d.verbose,silent:d.silent});let m=await nf(c??null,d);F(m);}),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",`
547
561
  Examples:
548
562
  $ flow plugin enable flow-adr-writer
549
- $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{je("cli");let m=await Xm(c,d);F(m);}),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",`
563
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Ve("cli");let m=await ef(c,d);F(m);}),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",`
550
564
  Examples:
551
565
  $ flow plugin disable flow-adr-writer
552
- $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{je("cli");let m=await qm(c,d);F(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
566
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Ve("cli");let m=await tf(c,d);F(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
553
567
  Examples:
554
568
  $ flow plugin export
555
- $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Mf(c);F(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
569
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Nf(c);F(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
556
570
  Examples:
557
571
  $ flow plugin import flow-plugins.json
558
572
  $ flow plugin import flow-plugins.json --scope user
559
573
  $ flow plugin import flow-plugins.json --force
560
574
  $ flow plugin import flow-plugins.json --dry-run
561
- $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await _f(c,d);F(m);});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",`
575
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Bf(c,d);F(m);});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",`
562
576
  Examples:
563
577
  $ flow plugin marketplace add anthropics/claude-code
564
578
  $ flow plugin marketplace add https://github.com/owner/repo
565
579
  $ flow plugin marketplace add anthropics/claude-code --force
566
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{je("cli",{verbose:d.verbose,silent:d.silent});let m=await tf(c,d);F(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.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",`
580
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Ve("cli",{verbose:d.verbose,silent:d.silent});let m=await af(c,d);F(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.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",`
567
581
  Examples:
568
582
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
569
583
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
570
584
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
571
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{je("cli",{verbose:m.verbose,silent:m.silent});let p=await Ip(c,d,m);F(p);}),s.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",`
585
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Ve("cli",{verbose:m.verbose,silent:m.silent});let p=await Ep(c,d,m);F(p);}),s.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",`
572
586
  Examples:
573
587
  $ flow mcp remove notion
574
588
  $ flow mcp remove notion --scope project
575
- $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{je("cli",{verbose:d.verbose,silent:d.silent});let m=await vp(c,d);F(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
589
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Ve("cli",{verbose:d.verbose,silent:d.silent});let m=await Pp(c,d);F(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
576
590
  Examples:
577
591
  $ flow auth login
578
592
  $ flow auth login --jwt <token>
579
593
  $ flow auth login --jwt <token> --starter-kit dev
580
594
  $ flow auth login --jwt <token> --custom-email name@example.com
581
- $ flow auth login --verbose`).action(async c=>{je("cli",{verbose:c.verbose});let d=await Hl(c);F(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
595
+ $ flow auth login --verbose`).action(async c=>{Ve("cli",{verbose:c.verbose});let d=await Gl(c);F(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
582
596
  Examples:
583
597
  $ flow auth logout
584
- $ flow auth logout --force`).action(async c=>{let d=await Jm(c.force);F(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
598
+ $ flow auth logout --force`).action(async c=>{let d=await Wm(c.force);F(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
585
599
  Examples:
586
- $ flow auth status`).action(async()=>{let c=await Gm();F(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.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",`
600
+ $ flow auth status`).action(async()=>{let c=await zm();F(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.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",`
587
601
  Examples:
588
602
  $ flow skills add vercel-labs/agent-skills
589
603
  $ flow skills add owner/repo -g
590
604
  $ flow skills add owner/repo --skill pr-review commit
591
605
  $ flow skills add ./local/skills -y
592
- $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Cf(c,d);F(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
606
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Lf(c,d);F(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
593
607
  Examples:
594
608
  $ flow skills list
595
609
  $ flow skills list -g
596
- $ flow skills list --json`).action(async c=>{let d=await Af(c);F(d);}),a.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",`
610
+ $ flow skills list --json`).action(async c=>{let d=await _f(c);F(d);}),a.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",`
597
611
  Examples:
598
612
  $ flow skills remove pr-review
599
- $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await $f(c,d);F(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
613
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Df(c,d);F(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
600
614
  Examples:
601
615
  $ flow bundle install "My React Kit"
602
616
  $ flow bundle install "Squad Setup Bundle"
603
- $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{je("cli",{verbose:d.verbose});let m=await Qm(c);F(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
617
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Ve("cli",{verbose:d.verbose});let m=await of(c);F(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").option("--fix","Retroactively set autoUpdate: true on already-registered Flow-curated marketplaces (FLWP-71702)").addHelpText("after",`
604
618
  Examples:
605
- $ flow health`).action(async()=>{let c=await rf();F(c);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
619
+ $ flow health
620
+ $ flow health --fix`).action(async c=>{let d=await lf(c);F(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
606
621
  Examples:
607
622
  $ flow usage
608
- $ flow usage --json`).action(async c=>{let d=await cf(c);F(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Yl();F(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
623
+ $ flow usage --json`).action(async c=>{let d=await ff(c);F(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Ql();F(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
609
624
  Examples:
610
- $ flow modules list`).action(async()=>{let c=await Yl();F(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
625
+ $ flow modules list`).action(async()=>{let c=await Ql();F(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
611
626
  Examples:
612
627
  $ flow modules install metrics
613
- $ flow modules install dashboard`).action(async c=>{let d=await Ff(c);F(d);}),u.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
628
+ $ flow modules install dashboard`).action(async c=>{let d=await Jf(c);F(d);}),u.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
614
629
  Examples:
615
630
  $ flow modules update
616
- $ flow modules update metrics`).action(async c=>{let d=await jf(c??null);F(d);}),t.addCommand(u);for(let c of se)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Uf(c.alias,d);});return t.hook("preAction",()=>{Pi();}),t}$();function gv(){return xe__default.join(Re__default.homedir(),".claude","settings.json")}function Qf(){let e=gv();try{if(!be__default.existsSync(e))return !0;let r=JSON.parse(be__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}$();var bv=x("updateChecker"),Iv=promisify(execFile),vv=1440*60*1e3,eg=3e4;function Ev(){let e=process.env.FLOW_HOME??xe__default.join(Re__default.homedir(),".flow");return xe__default.join(e,"update.lock")}async function tg(e){try{let{stdout:t}=await Iv(Jt(),["view",e,"version"],{timeout:eg,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Pv(e){let t=new AbortController,r=setTimeout(()=>t.abort(),eg);try{let n=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:t.signal});return n.ok?(await n.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(r);}}async function Tv(e){return e.versionCheck.type==="npm-registry"?tg(e.versionCheck.package):Pv(e.versionCheck.repo)}async function Cv(){let e=await tg("@ciandt-flow/cli");return e&&Ue(ce,e)?(Ri({currentVersion:ce,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function kv(){let e=Wr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=se.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<vv)return;let s=await Tv(r);try{await ht({...t,lastChecked:new Date().toISOString()});}catch(i){bv.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ue(t.installedVersion,s)&&Ms(r,"background").catch(()=>{});}));}async function rc(){let e=Qf();if(e===false)return;let t=Ev();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=null;try{r=await kh.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await Cv().catch(()=>null);n&&process.stdout.write(`
631
+ $ flow modules update metrics`).action(async c=>{let d=await Gf(c??null);F(d);}),t.addCommand(u);for(let c of se)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Kf(c.alias,d);});return t.hook("preAction",()=>{Ti();}),t}R();function Pv(){return xe__default.join(Le__default.homedir(),".claude","settings.json")}function og(){let e=Pv();try{if(!be__default.existsSync(e))return !0;let r=JSON.parse(be__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var $v=x("updateChecker"),Lv=promisify(execFile),Mv=1440*60*1e3,sg=3e4;function _v(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"update.lock")}async function ig(e){try{let{stdout:t}=await Lv(Gt(),["view",e,"version"],{timeout:sg,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Dv(e){let t=new AbortController,r=setTimeout(()=>t.abort(),sg);try{let n=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:t.signal});return n.ok?(await n.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(r);}}async function Ov(e){return e.versionCheck.type==="npm-registry"?ig(e.versionCheck.package):Dv(e.versionCheck.repo)}async function Uv(){let e=await ig("@ciandt-flow/cli");return e&&Ne(ue,e)?(Li({currentVersion:ue,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function Nv(){let e=Xr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=se.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<Mv)return;let s=await Ov(r);try{await yt({...t,lastChecked:new Date().toISOString()});}catch(i){$v.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ne(t.installedVersion,s)&&_s(r,"background").catch(()=>{});}));}async function oc(){let e=og();if(e===false)return;let t=_v();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=null;try{r=await Mh.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await Uv().catch(()=>null);n&&process.stdout.write(`
617
632
  \u26A0 @ciandt-flow/cli v${n} installing in background.
618
633
  Restart flow to apply the update.
619
634
 
620
- `);}await kv().catch(()=>{});}finally{await r().catch(()=>{});}}var $v=x("cli"),nc=Yf(async()=>{je("tui"),Nc("tui"),Bc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();io("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();io("sigterm",t,r).finally(()=>process.exit(143));}),await rc().catch(()=>{}),await nd().catch(t=>{$v.error(`Failed to init catalog registry: ${String(t)}`);}),await _m();let{waitUntilExit:e}=render(jsx(Dm,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});nc.hook("preAction",async(e,t)=>{t!==nc&&await rc().catch(()=>{});});nc.parse();
635
+ `);}await Nv().catch(()=>{});}finally{await r().catch(()=>{});}}var Fv=x("cli"),sc=rg(async()=>{Ve("tui"),Fc("tui"),jc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();lo("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();lo("sigterm",t,r).finally(()=>process.exit(143));}),await oc().catch(()=>{}),await sd().catch(t=>{Fv.error(`Failed to init catalog registry: ${String(t)}`);}),await Om();let{waitUntilExit:e}=render(jsx(Um,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});sc.hook("preAction",async(e,t)=>{t!==sc&&await oc().catch(()=>{});});sc.parse();