@ciandt-flow/cli 2.9.0-beta.24 → 2.9.0-beta.26

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 +143 -135
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import*as gn 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 T from'chalk';import*as cl from'readline';import {createInterface}from'readline';import ha from'conf';import nd,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import yy,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Ch from'jsonwebtoken';import Bh from'proper-lockfile';import ly from'ink-big-text';import tp 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 hw from'unzipper';import {simpleGit}from'simple-git';import bl from'semver';import Xl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var Sg=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 lc=(e,t)=>{for(var r in t)Sg(e,r,{get:t[r],enumerable:true});};var ur,le,Gi,no,cn,un,cc,Wi,dr,ce,Qe,Jt,Qo,dn,pn,mn,fn,j=J(()=>{"use strict";ur="FLOW",le="flow-skills",Gi="flow-cli",no="internal",cn="external",un={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"}},cc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Wi=new Set(["internal","external"]),dr={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",Qe=5,Jt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Qo="https://flow.ciandt.com",dn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,pn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",mn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,fn="Must be a valid email address (e.g. name@example.com)";});var es,bg,dc,oo,zi=J(()=>{"use strict";es="aes-256-gcm",bg=16,dc=16,oo=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=gn.randomBytes(bg),n=gn.createCipheriv(es,this.key,r,{authTagLength:dc}),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:es}}decrypt(t){if(t.algorithm!==es)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=gn.createDecipheriv(es,this.key,Buffer.from(t.iv,"hex"),{authTagLength:dc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Xi(e){return e.replace(Pg,"").replace(Tg,"").replace(Cg,"").replace(Ig,"Bearer ***").replace(vg,"***").replace(Eg,"***").replace(/\r\n|\r|\n/g,"\\n")}var Ig,vg,Eg,Pg,Tg,Cg,qi=J(()=>{"use strict";Ig=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,vg=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Eg=/[A-Za-z0-9+/]{40,}={0,2}/g,Pg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Tg=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Cg=/\x1b/g;});function rs(e){return e||le}function pc(e,t,r){return Zi(rs(r),e,t)}function Yi(e,t){return xe.join(Le.homedir(),Ur,"plugins","marketplaces",rs(t),"plugins","native",e)}function ns(e){return xe.join(Le.homedir(),Ur,"plugins","marketplaces",rs(e),".claude-plugin","marketplace.json")}function Nr(){return xe.join(Le.homedir(),Ur,"plugins","known_marketplaces.json")}function mc(e){return xe.join(Le.homedir(),Ur,"plugins","marketplaces",rs(e))}function fc(){return xe.join(Le.homedir(),ts,"cache","install.lock")}function gc(){return xe.join(Le.homedir(),ts,"logs","flowsetup.log")}function Zi(e,t,r){return xe.join(Le.homedir(),Ur,"plugins","cache",e,t,r)}function Br(e){let t=e==="global"?Le.homedir():process.cwd();return xe.join(t,".claude","skills")}function so(e){let t=e==="global"?Le.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function os(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join(Le.homedir(),".config","opencode","plugins")}function hc(){return xe.join(Le.homedir(),ts,"flow-catalogs.json")}function yc(){let e=process.env.FLOW_HOME??xe.join(Le.homedir(),ts);return xe.join(e,"config.json")}function ss(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Ur,"agents"):xe.join(Le.homedir(),Ur,"agents")}var Ur,ts,He=J(()=>{"use strict";j();Ur=".claude",ts=".flow";});var kg,Ag,is,wc=J(()=>{"use strict";He();kg=5*1024*1024,Ag=3,is=class{filePath;constructor(){this.filePath=gc(),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>kg){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(Ag))be.unlinkSync(xe.join(t,o));}catch{}}};});var as,Sc=J(()=>{"use strict";as=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 ls,xc=J(()=>{"use strict";ls=class{write(t){process.stdout.write(t.message+`
5
- `);}};});function ea(){return cs}function bc(e){return Qi.add(e),()=>{Qi.delete(e);}}var cs,Qi,us,ta=J(()=>{"use strict";cs=[],Qi=new Set;us=class{write(t){cs.push(t),cs.length>100&&cs.shift();for(let r of Qi)r();}};});function $g(){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=$g();jr={context:e,transports:[new us,new is],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?jr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?jr={context:e,transports:[new as("cli")],minLevel:"debug",debugModules:null}:jr={context:e,transports:[new ls],minLevel:"info",debugModules:null};}function Ic(){return jr.transports}function vc(e,t){let{debugModules:r,minLevel:n}=jr;return jr.context==="tui"&&r&&r!=="all"?r.has(t)?hn[e]>=hn.debug:hn[e]>=hn.warn:hn[e]>=hn[n]}var hn,jr,ra=J(()=>{"use strict";wc();Sc();xc();ta();hn={debug:0,info:1,warn:2,error:3},jr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function ds(e,t,r){if(!vc(e,t))return;let n={level:e,module:t,message:Xi(r),timestamp:new Date};for(let o of Ic())o.write(n);}function x(e){let t=Ec.get(e);if(t)return t;let r={debug:n=>ds("debug",e,n),info:n=>ds("info",e,n),warn:n=>ds("warn",e,n),error:n=>ds("error",e,n)};return Ec.set(e,r),r}var Ec,Pc=J(()=>{"use strict";qi();ra();Ec=new Map;});var $=J(()=>{"use strict";Pc();ra();qi();});function Rg(e){return typeof e=="object"&&e!==null&&oa in e&&e[oa]===true}function sa(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[oa]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return na.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Rg(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return na.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return na.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var na,oa,ia=J(()=>{"use strict";$();na=x("encryption"),oa="__encrypted__";});var aa,_g,ft,yn,la=J(()=>{"use strict";$();aa=promisify(execFile),_g=promisify(exec),ft=x("encryption:macos-keyvault"),yn=class{static async isAvailable(){try{let{stdout:t}=await _g("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 aa("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 aa("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 aa("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(T.green(` \u2713 ${h(e)}
2
+ import*as hn from'crypto';import {randomUUID,createHash}from'crypto';import*as Me from'os';import Me__default,{tmpdir,homedir}from'os';import*as be from'path';import be__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ve from'fs';import ve__default,{readFileSync,mkdirSync,writeFileSync,rmSync,existsSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as ml from'readline';import {createInterface}from'readline';import xa from'conf';import pd,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Fy,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import qh from'jsonwebtoken';import ly from'proper-lockfile';import $y from'ink-big-text';import cp from'ink-spinner';import*as Dt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Bw from'unzipper';import {simpleGit}from'simple-git';import Pl from'semver';import Ql from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Kg=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 yc=(e,t)=>{for(var r in t)Kg(e,r,{get:t[r],enumerable:true});};var dr,le,qi,oo,un,dn,wc,Yi,Gt,ce,Qe,Wt,es,pn,mn,fn,gn,j=J(()=>{"use strict";dr="FLOW",le="flow-skills",qi="flow-cli",oo="internal",un="external",dn={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"}},wc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Yi=new Set(["internal","external"]),Gt={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},ce="flow-claude-md-setup",Qe=5,Wt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,es="https://flow.ciandt.com",pn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,mn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",fn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,gn="Must be a valid email address (e.g. name@example.com)";});var ts,Hg,xc,so,Zi=J(()=>{"use strict";ts="aes-256-gcm",Hg=16,xc=16,so=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=hn.randomBytes(Hg),n=hn.createCipheriv(ts,this.key,r,{authTagLength:xc}),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:ts}}decrypt(t){if(t.algorithm!==ts)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=hn.createDecipheriv(ts,this.key,Buffer.from(t.iv,"hex"),{authTagLength:xc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Qi(e){return e.replace(zg,"").replace(Xg,"").replace(qg,"").replace(Jg,"Bearer ***").replace(Gg,"***").replace(Wg,"***").replace(/\r\n|\r|\n/g,"\\n")}var Jg,Gg,Wg,zg,Xg,qg,ea=J(()=>{"use strict";Jg=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Gg=/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,zg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Xg=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,qg=/\x1b/g;});function ns(e){return e||le}function bc(e,t,r){return ra(ns(r),e,t)}function ta(e,t){return be.join(Me.homedir(),Nr,"plugins","marketplaces",ns(t),"plugins","native",e)}function os(e){return be.join(Me.homedir(),Nr,"plugins","marketplaces",ns(e),".claude-plugin","marketplace.json")}function Br(){return be.join(Me.homedir(),Nr,"plugins","known_marketplaces.json")}function Ic(e){return be.join(Me.homedir(),Nr,"plugins","marketplaces",ns(e))}function vc(){return be.join(Me.homedir(),rs,"cache","install.lock")}function Ec(){return be.join(Me.homedir(),rs,"logs","flowsetup.log")}function ra(e,t,r){return be.join(Me.homedir(),Nr,"plugins","cache",e,t,r)}function Fr(e){let t=e==="global"?Me.homedir():process.cwd();return be.join(t,".claude","skills")}function io(e){let t=e==="global"?Me.homedir():process.cwd();return be.join(t,".claude","skills-lock.json")}function ss(e="user"){return e==="project"?be.join(process.cwd(),".opencode","plugins"):be.join(Me.homedir(),".config","opencode","plugins")}function Pc(){return be.join(Me.homedir(),rs,"flow-catalogs.json")}function Tc(){let e=process.env.FLOW_HOME??be.join(Me.homedir(),rs);return be.join(e,"config.json")}function is(e="user"){return e==="project"||e==="local"?be.join(process.cwd(),Nr,"agents"):be.join(Me.homedir(),Nr,"agents")}var Nr,rs,He=J(()=>{"use strict";j();Nr=".claude",rs=".flow";});var Yg,Zg,as,Cc=J(()=>{"use strict";He();Yg=5*1024*1024,Zg=3,as=class{filePath;constructor(){this.filePath=Ec(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{ve.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=be.dirname(this.filePath);ve.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ve.statSync(this.filePath).size>Yg){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ve.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=be.dirname(this.filePath),r=be.basename(this.filePath,".log"),n=ve.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Zg))ve.unlinkSync(be.join(t,o));}catch{}}};});var ls,kc=J(()=>{"use strict";ls=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 cs,Ac=J(()=>{"use strict";cs=class{write(t){process.stdout.write(t.message+`
5
+ `);}};});function oa(){return us}function Rc(e){return na.add(e),()=>{na.delete(e);}}var us,na,ds,sa=J(()=>{"use strict";us=[],na=new Set;ds=class{write(t){us.push(t),us.length>100&&us.shift();for(let r of na)r();}};});function Qg(){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=Qg();Kr={context:e,transports:[new ds,new as],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Kr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Kr={context:e,transports:[new ls("cli")],minLevel:"debug",debugModules:null}:Kr={context:e,transports:[new cs],minLevel:"info",debugModules:null};}function $c(){return Kr.transports}function Lc(e,t){let{debugModules:r,minLevel:n}=Kr;return Kr.context==="tui"&&r&&r!=="all"?r.has(t)?yn[e]>=yn.debug:yn[e]>=yn.warn:yn[e]>=yn[n]}var yn,Kr,ia=J(()=>{"use strict";Cc();kc();Ac();sa();yn={debug:0,info:1,warn:2,error:3},Kr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function ps(e,t,r){if(!Lc(e,t))return;let n={level:e,module:t,message:Qi(r),timestamp:new Date};for(let o of $c())o.write(n);}function x(e){let t=Mc.get(e);if(t)return t;let r={debug:n=>ps("debug",e,n),info:n=>ps("info",e,n),warn:n=>ps("warn",e,n),error:n=>ps("error",e,n)};return Mc.set(e,r),r}var Mc,_c=J(()=>{"use strict";ea();ia();Mc=new Map;});var R=J(()=>{"use strict";_c();ia();ea();});function eh(e){return typeof e=="object"&&e!==null&&la in e&&e[la]===true}function ca(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[la]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return aa.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(eh(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return aa.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return aa.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var aa,la,ua=J(()=>{"use strict";R();aa=x("encryption"),la="__encrypted__";});var da,nh,ft,wn,pa=J(()=>{"use strict";R();da=promisify(execFile),nh=promisify(exec),ft=x("encryption:macos-keyvault"),wn=class{static async isAvailable(){try{let{stdout:t}=await nh("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 da("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 da("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 da("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 q(e){process.stdout.write(T.green(` \u2713 ${h(e)}
6
6
  `));}function P(e){process.stderr.write(T.red(` \u2717 ${h(e)}
7
- `));}function I(e){process.stdout.write(T.cyan(` \u2139 ${h(e)}
8
- `));}function wn(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(`
7
+ `));}function b(e){process.stdout.write(T.cyan(` \u2139 ${h(e)}
8
+ `));}function Sn(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(` ${T.bold(i(e))}
10
10
  `),process.stdout.write(` ${T.dim(s)}
11
11
  `);for(let a of r)process.stdout.write(` ${i(a)}
12
12
  `);process.stdout.write(`
13
13
  `);}function pr(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function Te(e){process.stdout.write(JSON.stringify(e)+`
14
+ `);}function we(e){process.stdout.write(JSON.stringify(e)+`
15
15
  `);}function tt(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 Bg(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 Fg(e){let t=cl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var ca,ua,Ng,re,mr,da=J(()=>{"use strict";$();B();ca=promisify(execFile),ua=promisify(exec),Ng=[{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");mr=class e{static async isAvailable(){try{let{stdout:t}=await ua("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 ca("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 Ng)try{return await ua(`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 Fg(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return re.info(`Running: ${t.command}`),await Bg("Installing secret-tool...",()=>ua(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 ca("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 ca("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 ma(e,t){return `${e}:${t}`}function ao(e){return e.replace(/'/g,"''")}function ps(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Wg(e){return `Add-Type -TypeDefinition @'
17
- ${fa}
16
+ `);}function Y(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 F=J(()=>{"use strict";});async function lh(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 ch(e){let t=ml.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var ma,fa,ah,re,mr,ga=J(()=>{"use strict";R();F();ma=promisify(execFile),fa=promisify(exec),ah=[{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");mr=class e{static async isAvailable(){try{let{stdout:t}=await fa("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 ma("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 ah)try{return await fa(`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 ch(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return re.info(`Running: ${t.command}`),await lh("Installing secret-tool...",()=>fa(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 ma("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 ma("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 ya(e,t){return `${e}:${t}`}function lo(e){return e.replace(/'/g,"''")}function ms(e){return ["-NoProfile","-NonInteractive","-Command",e]}function hh(e){return `Add-Type -TypeDefinition @'
17
+ ${wa}
18
18
  '@
19
- [FlowCredManager]::Read('${ao(e)}')`}function zg(e,t,r){return `Add-Type -TypeDefinition @'
20
- ${fa}
19
+ [FlowCredManager]::Read('${lo(e)}')`}function yh(e,t,r){return `Add-Type -TypeDefinition @'
20
+ ${wa}
21
21
  '@
22
- [FlowCredManager]::Write('${ao(e)}', '${ao(t)}', '${ao(r)}')`}function Xg(e){return `Add-Type -TypeDefinition @'
23
- ${fa}
22
+ [FlowCredManager]::Write('${lo(e)}', '${lo(t)}', '${lo(r)}')`}function wh(e){return `Add-Type -TypeDefinition @'
23
+ ${wa}
24
24
  '@
25
- [FlowCredManager]::Delete('${ao(e)}')`}async function ms(e){return Vg("powershell.exe",e)}var Vg,gt,pa,Hg,Jg,Gg,fa,Sn,ga=J(()=>{"use strict";$();Vg=promisify(execFile),gt=x("encryption:windows-keyvault"),pa=1,Hg=1,Jg=2,Gg=3;fa=`
25
+ [FlowCredManager]::Delete('${lo(e)}')`}async function fs(e){return ph("powershell.exe",e)}var ph,gt,ha,mh,fh,gh,wa,xn,Sa=J(()=>{"use strict";R();ph=promisify(execFile),gt=x("encryption:windows-keyvault"),ha=1,mh=1,fh=2,gh=3;wa=`
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, ${pa}, 0, out credPtr)) return "";
61
+ if (!CredRead(target, ${ha}, 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[] { ${Jg}, ${Gg}, ${Hg} };
75
+ int[] persistLevels = new int[] { ${fh}, ${gh}, ${mh} };
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 = ${pa};
83
+ cred.Type = ${ha};
84
84
  cred.TargetName = targetPtr;
85
85
  cred.CredentialBlobSize = bytes.Length;
86
86
  cred.CredentialBlob = blobPtr;
@@ -98,60 +98,59 @@ public class FlowCredManager {
98
98
  }
99
99
 
100
100
  public static bool Delete(string target) {
101
- return CredDelete(target, ${pa}, 0);
101
+ return CredDelete(target, ${ha}, 0);
102
102
  }
103
103
  }
104
- `;Sn=class{static async isAvailable(){try{let{stdout:t}=await ms(ps('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=ma(t,r);gt.debug(`Looking up secret: target=${n}`);let o=Wg(n),{stdout:s}=await ms(ps(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=ma(t,r);gt.debug(`Storing secret: target=${o}`);let s=zg(o,n,r),{stdout:i}=await ms(ps(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=ma(t,r);gt.debug(`Deleting secret: target=${n}`);let o=Xg(n),{stdout:s}=await ms(ps(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 Qg(){let e=`${Le.hostname()}${Le.userInfo().username}`;return gn.scryptSync(e,Yg,qg)}function eh(){let e=Qg(),t=new oo(e),r=sa(t);return new ha({projectName:ya,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function fs(){return gs||(gs=eh()),gs}var qg,Yg,ya,Zg,gs,Ge,lo=J(()=>{"use strict";zi();ia();qg=32,Yg="flow-plugins-cli-fallback",ya="flow-plugins-cli-fallback",Zg={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)"};gs=null;Ge=class{warned=!1;async getSecret(t,r){return fs().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Zg[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
104
+ `;xn=class{static async isAvailable(){try{let{stdout:t}=await fs(ms('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=ya(t,r);gt.debug(`Looking up secret: target=${n}`);let o=hh(n),{stdout:s}=await fs(ms(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=ya(t,r);gt.debug(`Storing secret: target=${o}`);let s=yh(o,n,r),{stdout:i}=await fs(ms(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=ya(t,r);gt.debug(`Deleting secret: target=${n}`);let o=wh(n),{stdout:s}=await fs(ms(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 Ih(){let e=`${Me.hostname()}${Me.userInfo().username}`;return hn.scryptSync(e,xh,Sh)}function vh(){let e=Ih(),t=new so(e),r=ca(t);return new xa({projectName:ba,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function gs(){return hs||(hs=vh()),hs}var Sh,xh,ba,bh,hs,Ge,co=J(()=>{"use strict";Zi();ua();Sh=32,xh="flow-plugins-cli-fallback",ba="flow-plugins-cli-fallback",bh={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)"};hs=null;Ge=class{warned=!1;async getSecret(t,r){return gs().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=bh[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;}fs().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=fs(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return fs().path}static hasExistingData(){try{let t=new ha({projectName:ya});return be.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ha({projectName:ya});be.rmSync(t.path,{force:!0});}catch{}gs=null;}};});async function wa(){if(Ge.hasExistingData())return new Ge;switch(process.platform){case "darwin":return await yn.isAvailable()?new yn:new Ge;case "linux":return await mr.isAvailable()?new mr:await mr.ensureInstalled()?new mr:new Ge;case "win32":return await Sn.isAvailable()?new Sn:new Ge;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var $c=J(()=>{"use strict";la();da();ga();lo();});var Rc=J(()=>{"use strict";zi();ia();$c();la();da();ga();lo();});async function fr(){return ws||(ws=wa()),ws}function Ss(){ws=null;}async function Y(){let t=await(await fr()).getSecret(Gt,Sa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function gr(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 Lc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await fr()).setSecret(Gt,Sa,JSON.stringify(e));}async function Mc(){let e=await fr();await e.deleteSecret(Gt,Sa),await e.deleteSecret(Gt,xa),await e.deleteSecret(Gt,ba);}async function _c(){return (await fr()).getStoragePath()}async function Dc(e){await(await fr()).setSecret(Gt,xa,JSON.stringify(e));}async function xs(){let t=await(await fr()).getSecret(Gt,xa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function bs(e){await(await fr()).setSecret(Gt,ba,JSON.stringify(e));}async function xn(){let t=await(await fr()).getSecret(Gt,ba);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function hr(){let e=await xs();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/`,Lc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Lc,Gt,Sa,xa,ba,ws,Ie=J(()=>{"use strict";Rc();$();Lc=x("config:credentials"),Gt="flow-plugins-cli",Sa="credentials",xa="token-cache",ba="user-info",ws=null;});function bn(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 Is=J(()=>{"use strict";});function th(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 Ia(e){if(Oc.some(r=>r.test(e)))return true;let t=th(e);return !!(t&&Oc.some(r=>r.test(t)))}function rh(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=rh(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&&Ia(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Oc,Kr=J(()=>{"use strict";Oc=[/^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 sh(e){if(!Jt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function ih(e){if(e instanceof HTTPError){let t=e.response.status;va.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&&Uc[r]?new Error(Uc[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?(va.debug(`Non-HTTP error during authentication: ${e.message}`),e):(va.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Vr(e){let t=At("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");sh(e.tenant);let r;try{r=await nd.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await ih(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await gr(e),await Dc({accessToken:r.access_token,expiresAt:n});let o=bn(r.access_token);await bs({sub:o.sub,name:o.name,email:o.email});}var va,Uc,vs=J(()=>{"use strict";Ie();Is();Kr();$();j();va=x("api:auth");Uc={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 $t(){if(await hr()){let n=await xs();if(n)return n.accessToken}Nc.debug("Token expired or missing, re-authenticating...");let t=await Y();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ge.clearFallbackFile(),Ss(),await Vr(t);let r=await xs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Nc.debug("Token refreshed successfully"),r.accessToken}var Nc,In=J(()=>{"use strict";Ie();vs();lo();$();Nc=x("lib:tokenProvider");});function Xt(){return nd.create({prefix:At("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await $t();e.headers.set("Authorization",`Bearer ${t}`);let r=await Y();r?.tenant&&Jt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Eo=J(()=>{"use strict";Kr();Ie();In();j();});function $n(e,t){let r=Xt();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 Ga=J(()=>{"use strict";Eo();});function Po(e){if(!e||!ow.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Ln(e){return sw.test(e)}function Mn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function za(e){if(!iw.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 _n(e,t){let r=Mn(e);za(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function Zs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!aw.test(t)&&!lw.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var ow,sw,iw,aw,lw,Tr=J(()=>{"use strict";ow=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;sw=/^[^@]+@[^@]+$/;iw=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;aw=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,lw=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Qu={};lc(Qu,{FlowApiAdapter:()=>Dn});var cw,Dn,Xa=J(()=>{"use strict";Eo();Ga();$();Tr();cw=x("catalog.flow-api"),Dn=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 $n("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){Po(t);try{return await $n(`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 Xt().head("v1/plugins/catalog"),cw.debug("ping ok"),!0}catch{return !1}}};});function dw(){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 td(){return ed??=dw(),ed}var ed,rd=J(()=>{"use strict";});var sd={};lc(sd,{GitRepoAdapter:()=>On});function od(e,t){if(!pw.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var pw,On,qa=J(()=>{"use strict";rd();Kr();pw=/^[a-zA-Z0-9_.-]+$/;On=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(Ia(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return od(a,"owner"),od(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 nd.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 nd.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 td();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}}};});j();var uc=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(uc),origins:new Set(Wi)},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(uc)},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(Wi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ie();In();Is();j();Kr();$();var Es=x("api:metrics");function Bc(){return At("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Fc(e,t,r){return nd.post(e,{json:t,headers:r})}async function lh(e){let t=await xn();if(t)return t;let r=bn(e),n={sub:r.sub,name:r.name,email:r.email};return await bs(n),n}async function v(e,t){let r=await $t(),n=await lh(r),o=await Y();if(!Jt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Gi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Fc(Bc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Es.debug(`Metrics event sent: ${e}`);}catch(i){throw Es.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function jc(e,t,r){try{let n=r&&Jt.test(r)?r:"unknown",o={action:e,booster:Gi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Fc(Bc(),o,{FlowTenant:n}),Es.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Es.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 ch={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ht={...ch};function Kc(e){let t=Date.now();ht={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Hr(e){ht.currentStep=e,ht.stepStart=Date.now();}function Z(){return {...ht}}function yr(){return ht.sessionStart===0?0:Date.now()-ht.sessionStart}function Jr(){return ht.stepStart===0?0:Date.now()-ht.stepStart}function Vc(){ht.tuiSessionStart=Date.now();}function Hc(){return ht.tuiSessionStart===0?0:Date.now()-ht.tuiSessionStart}$();var uh=3e3,dh=x("abandonment");async function Ps(e){let{currentStep:t,sessionStart:r}=Z();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:yr()};try{await Promise.race([v(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),uh))]);}catch(o){dh.warn(`Abandonment event failed: ${String(o)}`);}}function Jc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}$();var ph=3e3,mh=x("session-end");async function uo(e,t,r){let n=Hc(),s=[v(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Ps(e));try{await Jc(Promise.all(s).then(()=>{}),ph);}catch(i){mh.warn(`Session end event failed: ${String(i)}`);}}var yh=2e3;function Wc(){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),uo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},yh);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var bh=16;function zc({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(bh)}),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]})})]})}j();function Xc({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();mn.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:fn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}j();function qc({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"})]})]})}j();function Yc(){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 rt=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})}));vs();j();function zr(){return xe__default.join(Le__default.homedir(),".claude","settings.json")}function Qc(e){return `${(e&&e.trim().length>0?e.trim():Qo).replace(/\/+$/,"")}/flow-litellm/`}function wo(){let e=zr();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 Cs(e){let t=zr();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 eu(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 $a(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 tu(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 kh=3600,Xr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function So(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 Ah(e){return Ch.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:kh})}function ks(e,t={}){let r=wo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Xr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?$a(r.settings):null,s=r.status==="ok"?tu(r.settings):null,i=t.jwtOverride??Ah(e),a=Qc(e.customUrl),l=eu(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function As(e){Cs(e.merged);}function ru(){let e=wo();return e.status!=="ok"?false:$a(e.settings)!==null}Ie();He();function $h(){let e=yc();if(!be__default.existsSync(e))return {};try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ra=null;function Rh(){return Ra===null&&(Ra=$h()),Ra}function xr(){return !!Rh().ENABLE_EXPERIMENTAL_BETAS}j();function Dh(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function ou(e){let t=Dh();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var $s={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??Qo),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"}},Oh={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=xr()?[$s,Oh]:[$s];Ie();$();var Fh=x("moduleState");function Ls(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var jh={retries:5,minTimeout:50};async function su(e,t){be__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await Bh.lock(e+".lock",{realpath:false,retries:jh});try{return await t()}finally{await r();}}function iu(){let e=Ls();if(!be__default.existsSync(e))return [];try{let t=JSON.parse(be__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Fh.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 qr(){return iu()}function au(e){let t=Ls();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 nt(e){return qr().find(t=>t.alias===e)??null}async function yt(e){let t=Ls();await su(t,async()=>{let r=iu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,au(r);});}async function Yr(){let e=Ls();be__default.existsSync(e)||await su(e,async()=>{be__default.existsSync(e)||au([]);});}var Hh=promisify(execFile);function br(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 Hh(t,[e]),!0}catch{return false}}function Wt(){return process.platform==="win32"?"npm.cmd":"npm"}var lu=promisify(execFile),En=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=br(t,"npm");if(!r)return null;try{let{stdout:n}=await lu(Wt(),["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=br(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 lu(Wt(),["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 Ms=promisify(execFile),Xh=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,_s=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=br(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=br(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 Ms("brew",["tap",o.tap]),await Ms("brew",["trust",o.tap])),await Ms("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 Ms("brew",["list","--versions",t]),n=r.trim().match(Xh);return n?n[2]:null}catch{return null}}};var Pn=promisify(execFile),uu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function du(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ds=class{type="curl";async isAvailable(){return Lt("curl")}async install(t){let r=Date.now(),n=br(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(du(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Pn(n,["--version"]),s=o.match(uu);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 Pn("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 Pn("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=du(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(be__default.mkdirSync(s,{recursive:!0}),a=!0,await Pn("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 Pn(i,["--version"]),c=u.match(uu);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 Pn("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 pu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(pu=e.version);}catch{}var ue=pu;var Ce=x("moduleInstaller");function _t(e){switch(e){case "npm":return new En;case "homebrew":return new _s;case "curl":return new Ds}}async function xo(e,t,r){try{await v(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 vr(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 xo(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 xo(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 xo(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 xo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await v(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 v(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 ry(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await xo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function ry(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 Os(e,t){let r=Date.now(),n=nt(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 v(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 v(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 v(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 v(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}$();var Us=x("flowAiObsSetup");async function Ns(e,t){try{if(!await new En().isAvailable().catch(()=>!1))return Us.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await vr($s,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Us.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Us.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Us.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}$();function mu(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 ny=x("useAuthSetup");function fu(){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:E}=rt(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},M=()=>{v(b.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:yr(),interface:"tui"}).catch(()=>{});},C=async V=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{V&&As(V),await gr(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),E(true),M(),await Ns(n.current,o.current).catch(G=>ny.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Bs({starterKit:N.starterKit});},R=async()=>C(),_=async V=>C(V),O=V=>{try{let z={...r.current,customUrl:n.current??void 0};return ks(z,{allowOverwriteMalformed:V,jwtOverride:e.trim()})}catch(z){return z instanceof Xr?(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=So(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,K();},K=async()=>{let V=n.current;V&&kt(V),c(true),l(null),y.current+=1;try{await Vr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),jc(b.CLI_AUTH_FAILED,{error_code:mu(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:R,planPersistOverwrite:ee}}j();B();function gu(){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}=fu(),[g,w]=useState("confirm"),[E,D]=useState(""),M=useRef(""),[C,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?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&&dn.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:[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:E}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:pn}),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(Xc,{onConfirm:m})]}):o==="preview"&&s?jsx(qc,{plan:s}):o==="malformedConfirm"?jsx(Yc,{}):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(zc,{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 Cn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(ly,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ue]})})]})}var Su=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ne=xr()?Su:Su.slice(0,3);function cy(e){return ne.findIndex(t=>t.id===e)}function _a(e,t,r){let n=cy(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 Iu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function vu({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?`${Iu[r]} (${e})`:Iu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var We=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Pu(){let e=S(i=>i.focus),t=We(i=>i.query),r=We(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..."})]})}j();var my=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...un[e]})),fy=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...cc[e]}));function Tu(){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"]})]}),my.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"]})]}),fy.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)})]})}j();function Cu({type:e}){let{label:t,color:r}=un[e];return jsx(Text,{color:r,children:t})}j();function $u({origin:e}){return e===no?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}B();var js=yy.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(Cu,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx($u,{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 kn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}j();function Mu({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(kn,{message:t});let n=Math.max(0,r-Math.floor(Qe/2)),o=Math.min(e.length,n+Qe);o===e.length&&(n=Math.max(0,o-Qe));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(js,{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 Ou({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}j();function Nu({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(kn,{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(Qe/2)),u=Math.min(n.length,l+Qe);u===n.length&&(l=Math.max(0,u-Qe));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(Ou,{label:p.label,pathHint:p.pathHint},p.key):jsx(js,{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 Py={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Ty({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Pu,{}),jsx(Tu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Py[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Nu,{groups:n,emptyMessage:r}):jsx(Mu,{items:e,emptyMessage:r})]})}function Bu({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(Ty,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Ay={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 Ks(){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:[Ay[e],t?" | Ctrl+D: debug log":""]})})}B();function Fu({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 Vs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(tp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function ja(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Hu=20;function Hs(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Hu),s="\u2588".repeat(o)+"\u2591".repeat(Hu-o),i=`${ja(e)} / ${ja(t)}`;return {bar:s,percent:n,label:i}}function Js({received:e,total:t}){let{bar:r,percent:n,label:o}=Hs(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Gs({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 ot({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))})]})}j();var Ja=Object.entries(dr),zu=[...Ja.map(([,e])=>e.actionLabel),"Cancel"],Xu=Object.fromEntries(Ja.map(([,e])=>[e.actionLabel,e.description]));function qu(e){let t=Ja.find(([,r])=>r.actionLabel===e);return t?t[0]:null}$();var Hy=x("provider.registry"),Jy=3e4,zs=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()+Jy}),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"&&Hy.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 Gy={user:"global",project:"project",local:"local"};function Xs(e){return e?Gy[e]:"global"}var ze=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},Pr=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};Eo();Ga();$();var Xy=x("catalog.registry"),qs=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);Xy.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()]}};He();var nw={retries:5,minTimeout:50};async function Wa(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bh.lock(e+".lock",{realpath:false,retries:nw});try{return await t()}finally{await r();}}var Ys=class{filePath;constructor(t){this.filePath=t??hc();}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 Wa(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 Wa(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Wa(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));});}};Xa();var de=new qs,qt=new Ys,mw=["flow-harness"];function fw(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?mw:e.split(",").map(t=>t.trim()).filter(Boolean)}de.register(new Dn);for(let e of fw())de.register(new Dn(e));var id=false;async function ad(){if(id)return;id=true;let e=await qt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(qa(),sd));for(let r of e)de.register(new t(r.id,r.name,r.source));}Tr();var ld=2;async function Yt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Xa(),Qu));return new t(e).fetchItems()}return de.fetchAll()}async function cd(){return de.fetchAllWithErrors()}async function Un(e,t){Po(e);try{return await $n(`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 ud(e,t,r){Po(e);try{let n=await $n(`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*ld)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*ld}`);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 Qs(){try{let{profiles:e}=await Xt().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}}He();He();async function dd(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 hw.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 Ya(e){await Dt.rm(e,{recursive:true,force:true});}async function Cr(){let e=fc();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 Bh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}He();j();function Sw(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 fd(e){let t=ns(e);if(!be__default.existsSync(t))return null;try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return null}}function xw(e){let t=fd(e);if(t)return t;let r=Sw(e),n=ns(e);return be__default.mkdirSync(xe__default.dirname(n),{recursive:true}),Za(r,e),r}function Za(e,t){let r=ns(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 bw(e){let t=e||le,r=Nr(),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:mc(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 gd(e,t,r){bt(e.name),bw(r);let n=Yi(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=xw(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}),Za(o,r));}function Qa(e,t){bt(e);let r=Yi(e,t);try{be__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=fd(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Za(n,t);}B();$();var vw=x("mcpConfigReader"),Ew=500,Pw=512;function Tw(){return xe__default.join(Le__default.homedir(),".claude.json")}function Cw(){return xe__default.join(process.cwd(),".mcp.json")}function yd(e){if(!be__default.existsSync(e))return null;try{return JSON.parse(be__default.readFileSync(e,"utf-8"))}catch{return vw.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function To(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function el(e){if(!To(e))return {};let t=e.mcpServers;return To(t)?t:{}}function tl(e,t){return Object.keys(e).slice(0,Ew).map(n=>({name:h(n.slice(0,Pw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Sd(){let e=[],t=Tw(),r=yd(t);if(To(r)){let a=r,l=el(a);e.push(...tl(l,"user"));let u=process.cwd();if(To(a.projects)){let c=a.projects[u];if(To(c)){let d=el(c);e.push(...tl(d,"local"));}}}let n=Cw(),o=yd(n),s=el(o);e.push(...tl(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 st=x("storage");async function Aw(e,t,r){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Z().interfaceType});}catch(n){st.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function $w(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:Z().interfaceType}).catch(o=>st.warn(`Failed to send ${t} metrics: ${String(o)}`));}function sl(){return xe__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function Rw(){return xe__default.join(Le__default.homedir(),".claude","plugins")}function ei(e){let t;try{t=be__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(Rw()),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 bd(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 De(){let e=sl();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 il(){let e=sl();try{let t=await be__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Lw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Id(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 Lw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function it(e){Id(sl(),e);}function Co(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Mw(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 al(e="user"){let t=bd(e);if(!be__default.existsSync(t))return {};try{return JSON.parse(be__default.readFileSync(t,"utf-8"))}catch{return {}}}function vd(e,t="user"){Id(bd(t),e);}function _w(e,t){let{name:r,marketplace:n}=Co(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Co(i).name===r)[0],!o)throw st.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Dw(e,t){let{name:r,marketplace:n}=Co(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Co(i).name===r)[0],o?{key:o,name:r}:null}function rl(e="user"){return al(e).enabledPlugins??{}}function nl(e,t="user"){let r=al(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,vd(r,t);}function ko(e,t,r="user"){let n=al(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},vd(n,r);}function Ow(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=De(),t=rl(),r=rl("project"),n=rl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=Co(u),p=c.map(y=>y.scope==="managed"?{...y,scope:"user"}:y);return Ow(p).map(y=>{let g=Mw(y.installPath,d),E=(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:E===false?"disabled":"enabled"}})}),i=Sd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function xd(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Ao(e,t){st.debug(`[${e}] Acquiring lock to uninstall`);let r=await Cr();try{let n=De(),o=Dw(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`);st.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),ei(l.installPath);let u=xe__default.dirname(l.installPath);ei(u),st.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;it({...n,plugins:m}),nl(s,t),Qa(i,xd(s));}else n.plugins[s]=c,it(n),nl(s,t);}else {st.debug(`[${i}] Resolved key: ${s}`);for(let c of a){ei(c.installPath);let d=xe__default.dirname(c.installPath);ei(d),st.debug(`[${i}] Removing directory: ${d}`),be__default.rmSync(d,{recursive:!0,force:!0}),nl(s,c.scope);}Qa(i,xd(s));let{[s]:l,...u}=n.plugins;it({...n,plugins:u});}await Aw(i,a[0].origin??"internal",a[0].type??"skill"),st.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function $o(e,t,r){st.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Cr();try{let o=De(),{key:s,name:i}=_w(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";st.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),ko(s,t==="enabled",l),$w(i,t,u),st.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}j();$();var Uw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Nw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function bt(e){if(!Uw.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Bw(e){if(!Nw.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 kr=x("installer");function Fw(e,t,r){let n=`${e}@${r||le}`,s=De().plugins[n];if(s&&!t)throw new ze(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function jw(e,t,r){r&&await Ya(t);try{kr.debug(`[${t}] Extracting archive...`),await dd(e,t);}catch(n){throw await Ya(t),n}}function Kw(e,t,r,n,o,s="claude-code",i){let a=De(),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],it(a),ko(e,true,n);}async function Vw(e,t,r,n,o,s){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Z().interfaceType});}catch(i){kr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Hw(e,t,r,n){try{await v(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){kr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Oe(e,t={}){let r=Date.now(),n=null;try{kr.debug(`[${e}] Acquiring lock...`),n=await Cr();let{pluginKey:o,alreadyInstalled:s}=Fw(e,t.force,t.source),{source:i}=t;kr.debug(`[${e}] Fetching manifest...`);let a=await Un(e,i);bt(a.name),Bw(a.version),kr.debug(`[${e}] Downloading archive...`);let l=await ud(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=pc(a.name,a.version,t.source);await jw(l,d,!!s&&!!t.force),Kw(o,d,a.version,u,"internal",t.providerId,c),gd(a,d,t.source);let m=Date.now()-r;kr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await Vw(a.name,a.version,m,Xs(u),"internal",c),p}catch(o){throw await Hw(e,o,"internal",t.type??"skill"),kr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}$();B();Ie();In();$();var Jw=x("commands:helpers");async function pe(){let e=await Y();if(!e)return P("Not authenticated. Run: flow auth login"),false;e.customUrl&&kt(e.customUrl);try{await $t();}catch(t){return Jw.debug(`Token validation failed: ${String(t)}`),P("Session expired. Run: flow auth login"),false}return true}async function Ue(e){let t=cl.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 Ed(e){let t=cl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim());});})}var Gw="\x1B[A",Ww="\x1B[B";function Pd(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function zw(e,t){return e.map((r,n)=>Pd(r,n===t)).join(`
111
- `)}async function Td(e,t){if(t.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((r,n)=>{let o=0;process.stdout.write(`${h(e)}
112
- `),process.stdout.write(zw(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
110
+ `),this.warned=!0;}gs().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=gs(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return gs().path}static hasExistingData(){try{let t=new xa({projectName:ba});return ve.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new xa({projectName:ba});ve.rmSync(t.path,{force:!0});}catch{}hs=null;}};});async function Ia(){if(Ge.hasExistingData())return new Ge;switch(process.platform){case "darwin":return await wn.isAvailable()?new wn:new Ge;case "linux":return await mr.isAvailable()?new mr:await mr.ensureInstalled()?new mr:new Ge;case "win32":return await xn.isAvailable()?new xn:new Ge;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Bc=J(()=>{"use strict";pa();ga();Sa();co();});var Fc=J(()=>{"use strict";Zi();ua();Bc();pa();ga();Sa();co();});async function fr(){return Ss||(Ss=Ia()),Ss}function xs(){Ss=null;}async function Z(){let t=await(await fr()).getSecret(zt,va);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function gr(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 jc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await fr()).setSecret(zt,va,JSON.stringify(e));}async function Kc(){let e=await fr();await e.deleteSecret(zt,va),await e.deleteSecret(zt,Ea),await e.deleteSecret(zt,Pa);}async function Vc(){return (await fr()).getStoragePath()}async function Hc(e){await(await fr()).setSecret(zt,Ea,JSON.stringify(e));}async function bs(){let t=await(await fr()).getSecret(zt,Ea);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Is(e){await(await fr()).setSecret(zt,Pa,JSON.stringify(e));}async function bn(){let t=await(await fr()).getSecret(zt,Pa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function hr(){let e=await bs();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/`,jc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var jc,zt,va,Ea,Pa,Ss,Ee=J(()=>{"use strict";Fc();R();jc=x("config:credentials"),zt="flow-plugins-cli",va="credentials",Ea="token-cache",Pa="user-info",Ss=null;});function In(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 vs=J(()=>{"use strict";});function Eh(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 Ta(e){if(Jc.some(r=>r.test(e)))return true;let t=Eh(e);return !!(t&&Jc.some(r=>r.test(t)))}function Ph(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=Ph(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&&Ta(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Jc,Vr=J(()=>{"use strict";Jc=[/^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 kh(e){if(!Wt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Ah(e){if(e instanceof HTTPError){let t=e.response.status;Ca.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&&Gc[r]?new Error(Gc[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?(Ca.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Ca.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Hr(e){let t=At("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");kh(e.tenant);let r;try{r=await pd.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Ah(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await gr(e),await Hc({accessToken:r.access_token,expiresAt:n});let o=In(r.access_token);await Is({sub:o.sub,name:o.name,email:o.email});}var Ca,Gc,Es=J(()=>{"use strict";Ee();vs();Vr();R();j();Ca=x("api:auth");Gc={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 hr()){let n=await bs();if(n)return n.accessToken}Wc.debug("Token expired or missing, re-authenticating...");let t=await Z();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ge.clearFallbackFile(),xs(),await Hr(t);let r=await bs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Wc.debug("Token refreshed successfully"),r.accessToken}var Wc,vn=J(()=>{"use strict";Ee();Es();co();R();Wc=x("lib:tokenProvider");});function Yt(){return pd.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 Z();r?.tenant&&Wt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Po=J(()=>{"use strict";Vr();Ee();vn();j();});function $n(e,t){let r=Yt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function Ln(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 qa=J(()=>{"use strict";Po();});function To(e){if(!e||!Cw.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Mn(e){return kw.test(e)}function _n(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Za(e){if(!Aw.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 Dn(e,t){let r=_n(e);Za(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(!Rw.test(t)&&!$w.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Cw,kw,Aw,Rw,$w,Tr=J(()=>{"use strict";Cw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;kw=/^[^@]+@[^@]+$/;Aw=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;Rw=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,$w=/^https:\/\/[\w./:@?&=+#%-]+$/;});var ld={};yc(ld,{FlowApiAdapter:()=>On});var Lw,On,Qa=J(()=>{"use strict";Po();qa();R();Tr();Lw=x("catalog.flow-api"),On=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 $n("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 Ln(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){To(t);try{return await $n(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Ln(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 Yt().head("v1/plugins/catalog"),Lw.debug("ping ok"),!0}catch{return !1}}};});function _w(){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 ud(){return cd??=_w(),cd}var cd,dd=J(()=>{"use strict";});var fd={};yc(fd,{GitRepoAdapter:()=>Un});function md(e,t){if(!Dw.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Dw,Un,el=J(()=>{"use strict";dd();Vr();Dw=/^[a-zA-Z0-9_.-]+$/;Un=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(Ta(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return md(a,"owner"),md(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 pd.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 pd.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 ud();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}}};});j();var Sc=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(Sc),origins:new Set(Yi)},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(Sc)},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(Yi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ee();vn();vs();j();Vr();R();var Ps=x("api:metrics");function zc(){return At("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Xc(e,t,r){return pd.post(e,{json:t,headers:r})}async function $h(e){let t=await bn();if(t)return t;let r=In(e),n={sub:r.sub,name:r.name,email:r.email};return await Is(n),n}async function v(e,t){let r=await Rt(),n=await $h(r),o=await Z();if(!Wt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:qi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Xc(zc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Ps.debug(`Metrics event sent: ${e}`);}catch(i){throw Ps.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function qc(e,t,r){try{let n=r&&Wt.test(r)?r:"unknown",o={action:e,booster:qi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Xc(zc(),o,{FlowTenant:n}),Ps.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Ps.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var I={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 Lh={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ht={...Lh};function Yc(e){let t=Date.now();ht={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Jr(e){ht.currentStep=e,ht.stepStart=Date.now();}function Q(){return {...ht}}function yr(){return ht.sessionStart===0?0:Date.now()-ht.sessionStart}function Gr(){return ht.stepStart===0?0:Date.now()-ht.stepStart}function Zc(){ht.tuiSessionStart=Date.now();}function Qc(){return ht.tuiSessionStart===0?0:Date.now()-ht.tuiSessionStart}R();var Mh=3e3,_h=x("abandonment");async function Ts(e){let{currentStep:t,sessionStart:r}=Q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:yr()};try{await Promise.race([v(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Mh))]);}catch(o){_h.warn(`Abandonment event failed: ${String(o)}`);}}function eu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var Dh=3e3,Oh=x("session-end");async function po(e,t,r){let n=Qc(),s=[v(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Ts(e));try{await eu(Promise.all(s).then(()=>{}),Dh);}catch(i){Oh.warn(`Session end event failed: ${String(i)}`);}}var Fh=2e3;function ru(){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),po("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Fh);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Hh=16;function nu({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(Hh)}),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]})})]})}j();function ou({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();fn.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:gn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}j();function su({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[dr," \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"})]})]})}j();function iu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[dr," \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 rt=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})}));Es();j();function Xr(){return be__default.join(Me__default.homedir(),".claude","settings.json")}function lu(e){return `${(e&&e.trim().length>0?e.trim():es).replace(/\/+$/,"")}/flow-litellm/`}function So(){let e=Xr();if(!ve__default.existsSync(e))return {status:"missing"};let t=ve__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 ks(e){let t=Xr();ve__default.mkdirSync(be__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,t);}function cu(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 _a(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 uu(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,qr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function xo(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 Zh(e){return qh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Yh})}function As(e,t={}){let r=So();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new qr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?_a(r.settings):null,s=r.status==="ok"?uu(r.settings):null,i=t.jwtOverride??Zh(e),a=lu(e.customUrl),l=cu(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Rs(e){ks(e.merged);}function du(){let e=So();return e.status!=="ok"?false:_a(e.settings)!==null}Ee();He();function Qh(){let e=Tc();if(!ve__default.existsSync(e))return {};try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return {}}}var Da=null;function ey(){return Da===null&&(Da=Qh()),Da}function xr(){return !!ey().ENABLE_EXPERIMENTAL_BETAS}j();function oy(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function mu(e){let t=oy();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var $s={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=be__default.join(Me__default.homedir(),".claude","settings.json"),r=ve__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??es),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"}},sy={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=xr()?[$s,sy]:[$s];Ee();R();var cy=x("moduleState");function Ms(){let e=process.env.FLOW_HOME??be__default.join(Me__default.homedir(),".flow");return be__default.join(e,"modules.json")}var uy={retries:5,minTimeout:50};async function fu(e,t){ve__default.mkdirSync(be__default.dirname(e),{recursive:true});let r=await ly.lock(e+".lock",{realpath:false,retries:uy});try{return await t()}finally{await r();}}function gu(){let e=Ms();if(!ve__default.existsSync(e))return [];try{let t=JSON.parse(ve__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(cy.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ve__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ve__default.rmSync(e,{force:true}),[]}}function Yr(){return gu()}function hu(e){let t=Ms();ve__default.mkdirSync(be__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ve__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,t);}function nt(e){return Yr().find(t=>t.alias===e)??null}async function yt(e){let t=Ms();await fu(t,async()=>{let r=gu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,hu(r);});}async function Zr(){let e=Ms();ve__default.existsSync(e)||await fu(e,async()=>{ve__default.existsSync(e)||hu([]);});}var my=promisify(execFile);function br(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 my(t,[e]),!0}catch{return false}}function Xt(){return process.platform==="win32"?"npm.cmd":"npm"}var yu=promisify(execFile),Pn=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=br(t,"npm");if(!r)return null;try{let{stdout:n}=await yu(Xt(),["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=br(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 yu(Xt(),["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),wy=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Ds=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=br(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=br(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(wy);return n?n[2]:null}catch{return null}}};var Tn=promisify(execFile),Su=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function xu(){let e=process.env.FLOW_HOME??be__default.join(Me__default.homedir(),".flow");return be__default.join(e,"bin")}var Os=class{type="curl";async isAvailable(){return Lt("curl")}async install(t){let r=Date.now(),n=br(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=be__default.join(xu(),be__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Tn(n,["--version"]),s=o.match(Su);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=be__default.join(Me__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Tn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ve__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ve__default.chmodSync(s,448),await Tn("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{ve__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=xu(),i=be__default.join(s,be__default.basename(n.binaryName)),a=false;try{if(ve__default.mkdirSync(s,{recursive:!0}),a=!0,await Tn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ve__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ve__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Tn(i,["--version"]),c=u.match(Su);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ve__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=be__default.join(Me__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Tn("curl",["-L","--fail","-o",n,r]);let o=ve__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ve__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{ve__default.unlinkSync(n);}catch{}}}};R();var bu="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(bu=e.version);}catch{}var ue=bu;var ke=x("moduleInstaller");function _t(e){switch(e){case "npm":return new Pn;case "homebrew":return new Ds;case "curl":return new Os}}async function bo(e,t,r){try{await v(I.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){ke.warn(`Failed to emit install failed event: ${String(n)}`);}}async function vr(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"){ke.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 bo(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 bo(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 bo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=_t(r),u=false;try{u=await l.isAvailable();}catch(d){ke.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 bo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:t});}catch(d){ke.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);ke.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 v(I.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){ke.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Py(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await bo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Py(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 Z(),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 ke.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,ke.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&ke.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&ke.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Us(e,t){let r=Date.now(),n=nt(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 v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:"command"});}catch(a){ke.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);ke.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 v(I.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){ke.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(I.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){ke.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await v(I.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){ke.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var Ns=x("flowAiObsSetup");async function Bs(e,t){try{if(!await new Pn().isAvailable().catch(()=>!1))return Ns.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await vr($s,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Ns.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Ns.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Ns.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function Iu(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 Ty=x("useAuthSetup");function vu(){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:E}=rt(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},M=()=>{v(I.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:yr(),interface:"tui"}).catch(()=>{});},C=async V=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{V&&Rs(V),await gr(z);}catch(G){l(G instanceof Error?G.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:A,...B}=z;w(B),E(true),M(),await Bs(n.current,o.current).catch(G=>Ty.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Fs({starterKit:B.starterKit});},$=async()=>C(),_=async V=>C(V),O=V=>{try{let z={...r.current,customUrl:n.current??void 0};return As(z,{allowOverwriteMalformed:V,jwtOverride:e.trim()})}catch(z){return z instanceof qr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},te=()=>{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=xo(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");},ee=V=>{o.current=V,K();},K=async()=>{let V=n.current;V&&kt(V),c(true),l(null),y.current+=1;try{await Hr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),qc(I.CLI_AUTH_FAILED,{error_code:Iu(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:ee,commitAndProceed:_,skipJwtAndProceed:$,planPersistOverwrite:te}}j();F();function Eu(){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}=vu(),[g,w]=useState("confirm"),[E,D]=useState(""),M=useRef(""),[C,$]=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 te=M.current.trim();te.length>0&&pn.test(te)?($(false),d(te)):te.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:[dr," \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:E}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:mn}),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:[dr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(ou,{onConfirm:m})]}):o==="preview"&&s?jsx(su,{plan:s}):o==="malformedConfirm"?jsx(iu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[dr," \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(nu,{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 kn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx($y,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ue]})})]})}var ku=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ne=xr()?ku:ku.slice(0,3);function Ly(e){return ne.findIndex(t=>t.id===e)}function Na(e,t,r){let n=Ly(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 $u={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Lu({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?`${$u[r]} (${e})`:$u[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var We=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function _u(){let e=S(i=>i.focus),t=We(i=>i.query),r=We(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..."})]})}j();var Oy=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...dn[e]})),Uy=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...wc[e]}));function Du(){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"]})]}),Oy.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"]})]}),Uy.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)})]})}j();function Ou({type:e}){let{label:t,color:r}=dn[e];return jsx(Text,{color:r,children:t})}j();function Bu({origin:e}){return e===oo?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}F();var Ks=Fy.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(Ou,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Bu,{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 An({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}j();function Ku({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(An,{message:t});let n=Math.max(0,r-Math.floor(Qe/2)),o=Math.min(e.length,n+Qe);o===e.length&&(n=Math.max(0,o-Qe));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(Ks,{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 Ju({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}j();function Wu({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(An,{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(Qe/2)),u=Math.min(n.length,l+Qe);u===n.length&&(l=Math.max(0,u-Qe));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(Ju,{label:p.label,pathHint:p.pathHint},p.key):jsx(Ks,{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 zy={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(_u,{}),jsx(Du,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:zy[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Wu,{groups:n,emptyMessage:r}):jsx(Ku,{items:e,emptyMessage:r})]})}function zu({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 Zy={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 Vs(){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:[Zy[e],t?" | Ctrl+D: debug log":""]})})}F();function Xu({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 Hs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(cp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Ja(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Qu=20;function Js(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Qu),s="\u2588".repeat(o)+"\u2591".repeat(Qu-o),i=`${Ja(e)} / ${Ja(t)}`;return {bar:s,percent:n,label:i}}function Gs({received:e,total:t}){let{bar:r,percent:n,label:o}=Js(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Ws({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 ot({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))})]})}j();var Xa=Object.entries(Gt),nd=[...Xa.map(([,e])=>e.actionLabel),"Cancel"],od=Object.fromEntries(Xa.map(([,e])=>[e.actionLabel,e.description]));function sd(e){let t=Xa.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var mw=x("provider.registry"),fw=3e4,Xs=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()+fw}),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"&&mw.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 gw={user:"global",project:"project",local:"local"};function qs(e){return e?gw[e]:"global"}var ze=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},Pr=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};Po();qa();R();var ww=x("catalog.registry"),Ys=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);ww.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()]}};He();var Tw={retries:5,minTimeout:50};async function Ya(e,t){mkdirSync(dirname(e),{recursive:true});let r=await ly.lock(e+".lock",{realpath:false,retries:Tw});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 Ya(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 Ya(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ya(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));});}};Qa();var de=new Ys,Zt=new Zs,Ow=["flow-harness"];function Uw(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?Ow:e.split(",").map(t=>t.trim()).filter(Boolean)}de.register(new On);for(let e of Uw())de.register(new On(e));var gd=false;async function hd(){if(gd)return;gd=true;let e=await Zt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(el(),fd));for(let r of e)de.register(new t(r.id,r.name,r.source));}Tr();var yd=2;async function Qt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Qa(),ld));return new t(e).fetchItems()}return de.fetchAll()}async function wd(){return de.fetchAllWithErrors()}async function Nn(e,t){To(e);try{return await $n(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Ln(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 Sd(e,t,r){To(e);try{let n=await $n(`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*yd)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*yd}`);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 Ln(n);throw o?new Error(o):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`):n}}async function ei(){try{let{profiles:e}=await Yt().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}}He();He();async function xd(e,t){let r=be.resolve(t);await Dt.mkdir(r,{recursive:true});let n=be.join(be.dirname(r),`${randomUUID()}.zip`);try{await Dt.writeFile(n,e);let o=await Bw.Open.file(n),s=be.normalize(r+be.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=be.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(be.resolve(be.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 tl(e){await Dt.rm(e,{recursive:true,force:true});}async function Cr(){let e=vc();await Dt.mkdir(be.dirname(e),{recursive:true});try{await Dt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await ly.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}He();j();function Kw(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 vd(e){let t=os(e);if(!ve__default.existsSync(t))return null;try{return JSON.parse(ve__default.readFileSync(t,"utf-8"))}catch{return null}}function Vw(e){let t=vd(e);if(t)return t;let r=Kw(e),n=os(e);return ve__default.mkdirSync(be__default.dirname(n),{recursive:true}),rl(r,e),r}function rl(e,t){let r=os(t),n=`${r}.${randomUUID()}.tmp`;ve__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(n,r);}function Hw(e){let t=e||le,r=Br(),n={};try{ve__default.existsSync(r)&&(n=JSON.parse(ve__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:Ic(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;ve__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(o,r);}function Ed(e,t,r){bt(e.name),Hw(r);let n=ta(e.name,r);ve__default.mkdirSync(be__default.dirname(n),{recursive:true});try{ve__default.lstatSync(n),ve__default.rmSync(n,{recursive:!0,force:!0});}catch{}ve__default.cpSync(t,n,{recursive:true,dereference:true});let o=Vw(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}),rl(o,r));}function nl(e,t){bt(e);let r=ta(e,t);try{ve__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=vd(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&rl(n,t);}F();R();var Gw=x("mcpConfigReader"),Ww=500,zw=512;function Xw(){return be__default.join(Me__default.homedir(),".claude.json")}function qw(){return be__default.join(process.cwd(),".mcp.json")}function Td(e){if(!ve__default.existsSync(e))return null;try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return Gw.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Co(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ol(e){if(!Co(e))return {};let t=e.mcpServers;return Co(t)?t:{}}function sl(e,t){return Object.keys(e).slice(0,Ww).map(n=>({name:h(n.slice(0,zw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function kd(){let e=[],t=Xw(),r=Td(t);if(Co(r)){let a=r,l=ol(a);e.push(...sl(l,"user"));let u=process.cwd();if(Co(a.projects)){let c=a.projects[u];if(Co(c)){let d=ol(c);e.push(...sl(d,"local"));}}}let n=qw(),o=Td(n),s=ol(o);e.push(...sl(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 st=x("storage");async function Zw(e,t,r){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Q().interfaceType});}catch(n){st.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Qw(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:Q().interfaceType}).catch(o=>st.warn(`Failed to send ${t} metrics: ${String(o)}`));}function cl(){return be__default.join(Me__default.homedir(),".claude","plugins","installed_plugins.json")}function eS(){return be__default.join(Me__default.homedir(),".claude","plugins")}function ti(e){let t;try{t=ve__default.realpathSync(e);}catch{t=be__default.resolve(e);}let r=be__default.resolve(eS()),n=be__default.resolve(be__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+be__default.sep),s=t.startsWith(n+be__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Rd(e="user"){return e==="local"?be__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?be__default.join(process.cwd(),".claude","settings.json"):be__default.join(Me__default.homedir(),".claude","settings.json")}function Oe(){let e=cl();if(!ve__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function ul(){let e=cl();try{let t=await ve__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function tS(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function $d(e,t){try{ve__default.mkdirSync(be__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,e);}catch(r){throw tS(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function it(e){$d(cl(),e);}function ko(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function rS(e,t){let r=be__default.join(e,".claude-plugin"),n=be__default.join(r,"plugin.json");if(ve__default.existsSync(n))try{return JSON.parse(ve__default.readFileSync(n,"utf-8"))}catch{return null}let o=be__default.join(r,"marketplace.json");if(ve__default.existsSync(o))try{let s=JSON.parse(ve__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function dl(e="user"){let t=Rd(e);if(!ve__default.existsSync(t))return {};try{return JSON.parse(ve__default.readFileSync(t,"utf-8"))}catch{return {}}}function Ld(e,t="user"){$d(Rd(t),e);}function nS(e,t){let{name:r,marketplace:n}=ko(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>ko(i).name===r)[0],!o)throw st.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function oS(e,t){let{name:r,marketplace:n}=ko(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>ko(i).name===r)[0],o?{key:o,name:r}:null}function il(e="user"){return dl(e).enabledPlugins??{}}function al(e,t="user"){let r=dl(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Ld(r,t);}function Ao(e,t,r="user"){let n=dl(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Ld(n,r);}function sS(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=Oe(),t=il(),r=il("project"),n=il("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=ko(u),p=c.map(y=>y.scope==="managed"?{...y,scope:"user"}:y);return sS(p).map(y=>{let g=rS(y.installPath,d),E=(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:E===false?"disabled":"enabled"}})}),i=kd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Ad(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Ro(e,t){st.debug(`[${e}] Acquiring lock to uninstall`);let r=await Cr();try{let n=Oe(),o=oS(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`);st.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),ti(l.installPath);let u=be__default.dirname(l.installPath);ti(u),st.debug(`[${i}] Removing directory: ${u}`),ve__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;it({...n,plugins:m}),al(s,t),nl(i,Ad(s));}else n.plugins[s]=c,it(n),al(s,t);}else {st.debug(`[${i}] Resolved key: ${s}`);for(let c of a){ti(c.installPath);let d=be__default.dirname(c.installPath);ti(d),st.debug(`[${i}] Removing directory: ${d}`),ve__default.rmSync(d,{recursive:!0,force:!0}),al(s,c.scope);}nl(i,Ad(s));let{[s]:l,...u}=n.plugins;it({...n,plugins:u});}await Zw(i,a[0].origin??"internal",a[0].type??"skill"),st.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function $o(e,t,r){st.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Cr();try{let o=Oe(),{key:s,name:i}=nS(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";st.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Ao(s,t==="enabled",l),Qw(i,t,u),st.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}j();R();var iS=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,aS=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function bt(e){if(!iS.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function lS(e){if(!aS.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 kr=x("installer");function cS(e,t,r){let n=`${e}@${r||le}`,s=Oe().plugins[n];if(s&&!t)throw new ze(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function uS(e,t,r){r&&await tl(t);try{kr.debug(`[${t}] Extracting archive...`),await xd(e,t);}catch(n){throw await tl(t),n}}function dS(e,t,r,n,o,s="claude-code",i){let a=Oe(),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],it(a),Ao(e,true,n);}async function pS(e,t,r,n,o,s){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Q().interfaceType});}catch(i){kr.warn(`Failed to send install metrics: ${String(i)}`);}}async function mS(e,t,r,n){try{await v(I.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:Q().interfaceType});}catch(o){kr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ue(e,t={}){let r=Date.now(),n=null;try{kr.debug(`[${e}] Acquiring lock...`),n=await Cr();let{pluginKey:o,alreadyInstalled:s}=cS(e,t.force,t.source),{source:i}=t;kr.debug(`[${e}] Fetching manifest...`);let a=await Nn(e,i);bt(a.name),lS(a.version),kr.debug(`[${e}] Downloading archive...`);let l=await Sd(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=bc(a.name,a.version,t.source);await uS(l,d,!!s&&!!t.force),dS(o,d,a.version,u,"internal",t.providerId,c),Ed(a,d,t.source);let m=Date.now()-r;kr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await pS(a.name,a.version,m,qs(u),"internal",c),p}catch(o){throw await mS(e,o,"internal",t.type??"skill"),kr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();F();Ee();vn();R();var fS=x("commands:helpers");async function pe(){let e=await Z();if(!e)return P("Not authenticated. Run: flow auth login"),false;e.customUrl&&kt(e.customUrl);try{await Rt();}catch(t){return fS.debug(`Token validation failed: ${String(t)}`),P("Session expired. Run: flow auth login"),false}return true}async function Ie(e){let t=ml.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 Ar(e){let t=ml.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim());});})}var gS="\x1B[A",hS="\x1B[B";function Md(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function yS(e,t){return e.map((r,n)=>Md(r,n===t)).join(`
111
+ `)}async function _d(e,t){if(t.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((r,n)=>{let o=0;process.stdout.write(`${h(e)}
112
+ `),process.stdout.write(yS(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
113
113
  `){l(),process.stdout.write(`
114
- `),r(t[o].value);return}if(s===Gw){o=(o-1+t.length)%t.length,a(),s="";return}if(s===Ww){o=(o+1)%t.length,a(),s="";return}s.startsWith("\x1B")&&s.length<3||(s="");};function a(){process.stdout.write(`\x1B[${t.length-1}A`);for(let c=0;c<t.length;c++)process.stdout.write(`\r\x1B[2K${Pd(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
115
- `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),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",i);})}Tr();var Bn=x("claudeProxy"),ml="claude ",Cd="flow ",ul=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Nn=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";}},Xw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,qw=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Yw={"--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}$/},Zw=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Qw=/^(flow|claude)\s+auth\s+login(\s|$)/,kd=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Ad(e){return kd.test(e.trim())}function eS(e){return kd.exec(e.trim())?.[2]??""}async function $d(e){let t=eS(e);za(t);let r=Date.now();Bn.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 fl(n)?new dl:n}}function tS(e){Rd(e);let t=e.slice(ml.length);if(!Xw.test(t))throw new Nn(e)}var ti=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},dl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Rd(e){if(!e||!/^claude /.test(e))throw new ul(e)}function rS(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!qw.test(r))throw new Nn(`Unexpected flag: ${r}`);let n=Yw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Nn(`Flag ${r} requires a value`);if(!n.test(o))throw new Nn(`Unsafe value for flag ${r}`);t++;}}}async function Ae(e){Rd(e);let t=e.slice(ml.length).split(/\s+/).filter(Boolean);rS(t);let r=nS(t);Bn.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 Bn.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 fl(o)?new ti:o}}function nS(e){return e.length>=3?e[2]:e.join(" ")}function fl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function oS(e){return e.startsWith(Cd)?ml+e.slice(Cd.length):e}function sS(e){return Zw.test(e)||Qw.test(e)}function iS(e){let t=0;for(;t<e.length&&sS(e[t]);)t++;return e.slice(t)}var aS=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function lS(e,t){return !t||e.includes("--scope")||!aS.test(e)?e:`${e} --scope ${t}`}async function Ro(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=iS(r).map(i=>oS(i)).map(i=>lS(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)tS(i);Bn.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 ri(e,t,r){let n=Mn(e),o=t?.trim();if(!o&&(o=(await Ed(`Plugin "${n}" could not be installed.
116
- 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=Zs(o),r?.(),Bn.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"}`);Bn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw fl(s)?new ti:s}}Tr();j();He();$();var mS=6e4,Ar=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:mS}}).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 Ar("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Ar(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Ar(`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 nn(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 gS(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function hS(e){return typeof e=="object"&&e!==null&&e.source==="url"}function yS(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Fn(e,t){let r=e.source;if(gS(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(hS(r))return {cloneUrl:r.url,subPath:"."};if(yS(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 xS(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=Nr();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 Nd(e,t){let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=Fn(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=xS(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Zi(s,e.name,"external"):a=join(Br(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 il(),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],it(d),ko(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 gl(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Xs(n),version:"unknown",duration_ms:t,interface:Z().interfaceType});}catch(o){Nt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Od(e,t,r){try{await v(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 bS={async install(e,t){if(e.origin===cn&&!e.installCommand&&!Ln(e.name))return Nd(e,t);if(e.origin===cn&&e.installCommand){let r=e.type??"skill",n=await Ro(e.installCommand,t.scope);return n.exitCode===0?(await gl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Od(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Ln(e.name)){let r=e.type??"skill",n=_n(e.name,t.scope);Nt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Ae(n);if(o.exitCode===0)return await gl(e.name,o.duration_ms,r,t.scope),{success:true};Nt.debug(`[${e.name}] First attempt failed, adding marketplace`),await ri(e.name,t.marketplaceSource,()=>{});let s=await Ae(n);return s.exitCode===0?(await gl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Od(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 Oe(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 Ao(e,t);},getInstallPath(e,t){return ""}};function Ud(e){return {async install(t,r){if(t.origin===cn&&!t.installCommand&&!Ln(t.name))return Nd(t,r);if(!t.installCommand)try{let o=await Oe(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 Ro(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=De(),o=`${t}@${le}`;if(n.plugins[o]){await Ao(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 IS(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 hl(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,hl(r)]))}function Bd(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(hl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(hl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Bd(s,o):r[n]=o;}return r}async function Fd(e,t,r,n){let o=await il(),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],it(o);}var vS={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=Fn(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=IS(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=ss(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 Fd(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=ss(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=De(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;it({...s,plugins:l});}else it({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(ss(t),`${at(e)}.md`)}},ES={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=Fn(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=wo();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=Bd(m,u);return Cs({...d,hooks:p}),await Fd(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 ""}},ni=class{id="claude-code";name="Claude Code";async isAvailable(){return nn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:bS,skill:Ud("skill"),mcp:Ud("mcp"),agent:vS,hook:ES}};function oi(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 TS=new Set(["gh"]),CS=oi(TS,"use: gh copilot mcp remove <name>"),si=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await nn("gh",["--version"])?nn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:CS}};He();var kS=new Set(["opencode"]),AS=oi(kS,"use: opencode config remove mcp <name>");function $S(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(`
117
- `)}function jd(){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=Fn(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=os(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`),$S(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=os(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(os(t),`${e}.js`)}}}var ii=class{id="opencode";name="OpenCode";async isAvailable(){return nn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:AS,skill:jd(),bundle:jd()}};var Bt=new zs;Bt.register(new ni);xr()&&(Bt.register(new si),Bt.register(new ii));function Kd({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(E=>E.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=qu(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(ot,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ot,{itemName:`${e} \u2014 Choose scope`,actions:zu,descriptions:Xu,onAction:f,onClose:y},"scope"):jsx(ot,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}B();function Hd({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(ot,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ci({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 Wd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ci({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(ot,{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 qd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ci({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(ot,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}$();var Vn=x("bundle:installer"),Yd=/already exists/i;async function NS(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Ad(t)){let r=await $d(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Yd.test(n))return;throw new Error(n)}}else {let r=await Ro(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Yd.test(n))return;throw new Error(n)}}}async function BS(e,t){try{await v(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Vn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function FS(e,t,r){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Vn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Zd(e,t,r,n){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Vn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function jS(e,t,r,n,o){try{await v(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Vn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function pi(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 BS(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){Vn.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 NS(f),u++,await FS(i,y,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let E=w instanceof Error?w.message:String(w);Vn.error(`Failed to install artifact "${y}": ${E}`),l.push({name:y,type:g,reason:E}),await Zd(i,y,g,E),r?.({index:p+1,total:c,artifact:f,success:false,error:E});}}let d=Date.now()-a,m=l.length;return await jS(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}B();function rp({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,pi(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(tp,{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(tp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ie()})}));B();function np({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 op({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 sp(e){return e.adapter.removable!==false?4:2}j();B();function ip({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 lp({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 cp({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,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(ip,{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(Qe/2)),p=Math.min(a.length,m+Qe);p===a.length&&(m=Math.max(0,p-Qe));let f=a.slice(m,p),y=m,g=a.length-p,w=s.length>0&&m<s.length,E=p>s.length,D=f.filter(C=>r.has(`${C.name}@${o}`)),M=f.filter(C=>!r.has(`${C.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(C=>jsx(lp,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),E&&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(C=>jsx(lp,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.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"})})]})}qa();var zS=/^https?:\/\/.+/;function XS(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function qS(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function mp(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(!zS.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let E=randomUUID(),D=new On(E,w,g);try{await D.fetchItems(),await qt.add({id:E,name:w,source:g}),de.register(new On(E,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let C=XS(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":qS(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(C,"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 fp(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await qt.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 hp(){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 qt.read(),G=new Map(N.map(Re=>[Re.id,Re]));s(A.map(Re=>({adapter:Re,stored:G.get(Re.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 E=mp(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),y("main");},[w]),{handleRemove:M}=fp(D),C=useCallback(async A=>{y("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 qt.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 qt.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,()=>{R(N);},...G?[()=>{_(N);},()=>{C(N.adapter.id);}]:[]][A]?.();},[o,i,O,R,_,C]),k=useCallback(()=>y("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,_]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);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?E.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&E.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],Re=G?sp(G)-1:0;d(Zo=>Math.min(Zo+1,Re));return}N.return&&ee(c);},{isActive:f==="main"&&E.phase==="idle"&&l==="detail"&&e==="marketplaces"}),E.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:E.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.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(E.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:E.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:E.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:E.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(E.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(Re=>Re.marketplace===A.adapter.name).map(Re=>`${Re.name}@${N}`));return jsx(cp,{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(np,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&V?jsx(op,{entry:V,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:H,onToggleAutoUpdate:Q,onRemove:K}):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 yp(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 wp(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Sp(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 tx=new Set(ne.filter(e=>e.focus!=="list").map(e=>e.focus));function jo(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}=We.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 xp({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=We(y=>y.query),a=We(y=>y.setQuery),l=We(y=>y.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:y,setCursorPosition:g}=We.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:E,actionMenuOpen:D}=S.getState();jo(_a(y,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((y,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:E,actionMenuOpen:D}=S.getState();jo(_a("",g,{activeTab:w}));},{isActive:tx.has(t)}),useInput((y,g)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:D}=S.getState();jo(yp(y,g,{activeTab:w,selectedIndex:E},u.current));},{isActive:t==="list"}),useInput((y,g)=>{jo(wp(y,g));},{isActive:t==="actionMenu"}),useInput((y,g)=>{let w=Sp(y,g,We.getState().query),E=w.queryUpdate;if(jo(w.actions),E==="reset")l(),d("");else if(E!==null){let{query:D,cursorPosition:M,setCursorPosition:C}=We.getState();if("backspace"in E)M>0&&(a(D.slice(0,M-1)+D.slice(M)),C(M-1));else if("append"in E)a(D.slice(0,M)+E.append+D.slice(M)),C(M+E.append.length);else if("cursorMove"in E){let R=M+E.cursorMove;R>=0&&R<=D.length&&C(R);}}},{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(E=>E.name.toLowerCase().includes(g)||E.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Ip(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=rt(a=>a.justAuthenticated),o=rt(a=>a.credentials),s=rt(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 Fe(e,t,r=false){return r?true:!bl.valid(e)||!bl.valid(t)?false:bl.gt(t,e)}j();$();var er=x("updater");async function rx(e,t,r,n,o,s){try{await v(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){er.warn(`Failed to send update metrics: ${String(i)}`);}}function nx(e){let t=De(),r=`${e}@${le}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function hi(e,t={}){let r=Date.now(),n=null;try{er.debug(`[${e}] Acquiring lock...`),n=await Cr();let o=nx(e);if(!o)throw er.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;er.debug(`[${e}] Fetching manifest...`);let u=(await Un(e,t.source)).version;if(!i||!Fe(i,u,t.force))throw er.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Pr(e,i??"unknown");er.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Oe(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await rx(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),er.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){er.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Cr();let d=De(),m=`${e}@${le}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,it(d),er.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Tr();$();var yi=x("dispatcher");async function ox(e,t,r,n,o){let s=Mn(e);return yi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await ri(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),yi.debug(`[${e}] Retrying install after marketplace add`),Ae(t)}async function vp(e,t,r,n){let o=_n(e,n),s=Mn(e);r?.onStatus?.(`Installing ${s}...`),yi.debug(`[${e}] Attempting install: ${o}`);let i=await Ae(o);if(i.exitCode===0)return i;yi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return ox(e,o,a,t,r)}async function Ep(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 Pp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Ep(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 $o(i,u,a),t();},[e,t]),s=useCallback(async i=>{await hi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}B();$();var Si=x("mcp");function Ko(e,t){e.silent?tt({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):P(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Cp(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&&I(t.stdout));}function sx(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 Il(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 kp(e,t,r){if(!await pe())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Ko(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Si.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=sx(e,t,r.transport,r.scope);if(!r.force){let s=h(e),i=h(n);if(!await Ue(`Install external MCP "${s}"?
114
+ `),r(t[o].value);return}if(s===gS){o=(o-1+t.length)%t.length,a(),s="";return}if(s===hS){o=(o+1)%t.length,a(),s="";return}s.startsWith("\x1B")&&s.length<3||(s="");};function a(){process.stdout.write(`\x1B[${t.length-1}A`);for(let c=0;c<t.length;c++)process.stdout.write(`\r\x1B[2K${Md(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
115
+ `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),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",i);})}Tr();var Fn=x("claudeProxy"),yl="claude ",Dd="flow ",fl=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Bn=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";}},wS=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,SS=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,xS={"--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}$/},bS=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,IS=/^(flow|claude)\s+auth\s+login(\s|$)/,Od=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Ud(e){return Od.test(e.trim())}function vS(e){return Od.exec(e.trim())?.[2]??""}async function Nd(e){let t=vS(e);Za(t);let r=Date.now();Fn.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 wl(n)?new gl:n}}function ES(e){Bd(e);let t=e.slice(yl.length);if(!wS.test(t))throw new Bn(e)}var ri=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},gl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Bd(e){if(!e||!/^claude /.test(e))throw new fl(e)}function PS(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!SS.test(r))throw new Bn(`Unexpected flag: ${r}`);let n=xS[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Bn(`Flag ${r} requires a value`);if(!n.test(o))throw new Bn(`Unsafe value for flag ${r}`);t++;}}}async function Re(e){Bd(e);let t=e.slice(yl.length).split(/\s+/).filter(Boolean);PS(t);let r=TS(t);Fn.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 Fn.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 wl(o)?new ri:o}}function TS(e){return e.length>=3?e[2]:e.join(" ")}function wl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function CS(e){return e.startsWith(Dd)?yl+e.slice(Dd.length):e}function kS(e){return bS.test(e)||IS.test(e)}function AS(e){let t=0;for(;t<e.length&&kS(e[t]);)t++;return e.slice(t)}var RS=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function $S(e,t){return !t||e.includes("--scope")||!RS.test(e)?e:`${e} --scope ${t}`}async function Lo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=AS(r).map(i=>CS(i)).map(i=>$S(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)ES(i);Fn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Re(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Re(o[i]),s.exitCode!==0)return s;return s}async function ni(e,t,r){let n=_n(e),o=t?.trim();if(!o&&(o=(await Ar(`Plugin "${n}" could not be installed.
116
+ 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?.(),Fn.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"}`);Fn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw wl(s)?new ri:s}}Tr();j();He();R();var OS=6e4,Rr=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$1(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 Rr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Rr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Rr(`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$1(e,{recursive:true,force:true});}async function on(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 NS(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function BS(e){return typeof e=="object"&&e!==null&&e.source==="url"}function FS(e){return typeof e=="object"&&e!==null&&e.source==="github"}function jn(e,t){let r=e.source;if(NS(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(BS(r))return {cloneUrl:r.url,subPath:"."};if(FS(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 VS(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=Br();if(!ve__default.existsSync(s))return r;try{let i=JSON.parse(ve__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 Gd(e,t){let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=jn(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=VS(e.catalogId,r?.source),i=t.scope??"user",a;o?a=ra(s,e.name,"external"):a=join(Fr(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(ve__default.existsSync(a)&&ve__default.rmSync(a,{recursive:!0,force:!0}),ve__default.mkdirSync(dirname(a),{recursive:!0}),ve__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await ul(),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],it(d),Ao(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 Sl(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:qs(n),version:"unknown",duration_ms:t,interface:Q().interfaceType});}catch(o){Nt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Hd(e,t,r){try{await v(I.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:Q().interfaceType});}catch(n){Nt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var HS={async install(e,t){if(e.origin===un&&!e.installCommand&&!Mn(e.name))return Gd(e,t);if(e.origin===un&&e.installCommand){let r=e.type??"skill",n=await Lo(e.installCommand,t.scope);return n.exitCode===0?(await Sl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Hd(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Mn(e.name)){let r=e.type??"skill",n=Dn(e.name,t.scope);Nt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Re(n);if(o.exitCode===0)return await Sl(e.name,o.duration_ms,r,t.scope),{success:true};Nt.debug(`[${e.name}] First attempt failed, adding marketplace`),await ni(e.name,t.marketplaceSource,()=>{});let s=await Re(n);return s.exitCode===0?(await Sl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Hd(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 Ue(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 Ro(e,t);},getInstallPath(e,t){return ""}};function Jd(e){return {async install(t,r){if(t.origin===un&&!t.installCommand&&!Mn(t.name))return Gd(t,r);if(!t.installCommand)try{let o=await Ue(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 Lo(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=Oe(),o=`${t}@${le}`;if(n.plugins[o]){await Ro(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 JS(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ve__default.existsSync(t))continue;let r=ve__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ve__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function xl(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,xl(r)]))}function Wd(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(xl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(xl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Wd(s,o):r[n]=o;}return r}async function zd(e,t,r,n){let o=await ul(),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],it(o);}var GS={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=jn(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=JS(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=is(r);ve__default.mkdirSync(l,{recursive:!0});let u=at(e.name);if(a.length===1)ve__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=at(basename(d,".md"));ve__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await zd(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=is(t),n=at(e);if(ve__default.existsSync(r))for(let a of ve__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ve__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Oe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;it({...s,plugins:l});}else it({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(is(t),`${at(e)}.md`)}},WS={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=jn(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(!ve__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ve__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=So();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=Wd(m,u);return ks({...d,hooks:p}),await zd(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 ""}},oi=class{id="claude-code";name="Claude Code";async isAvailable(){return on("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:HS,skill:Jd("skill"),mcp:Jd("mcp"),agent:GS,hook:WS}};function si(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 XS=new Set(["gh"]),qS=si(XS,"use: gh copilot mcp remove <name>"),ii=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await on("gh",["--version"])?on("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:qS}};He();var YS=new Set(["opencode"]),ZS=si(YS,"use: opencode config remove mcp <name>");function QS(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(`
117
+ `)}function Xd(){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=jn(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=ss(t.scope??"user"),a=join(s,".opencode","plugins");if(ve__default.existsSync(a)){let l=ve__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/"};ve__default.mkdirSync(i,{recursive:!0}),ve__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ve__default.existsSync(l)&&ve__default.rmSync(l,{recursive:!0,force:!0}),ve__default.mkdirSync(l,{recursive:!0}),ve__default.cpSync(s,l,{recursive:!0}),ve__default.mkdirSync(i,{recursive:!0}),ve__default.writeFileSync(join(i,`${e.name}.js`),QS(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=ss(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ve__default.existsSync(n)&&ve__default.rmSync(n,{force:true}),ve__default.existsSync(o)&&ve__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(ss(t),`${e}.js`)}}}var ai=class{id="opencode";name="OpenCode";async isAvailable(){return on("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:ZS,skill:Xd(),bundle:Xd()}};var Bt=new Xs;Bt.register(new oi);xr()&&(Bt.register(new ii),Bt.register(new ai));function qd({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(E=>E.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=sd(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(ot,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ot,{itemName:`${e} \u2014 Choose scope`,actions:nd,descriptions:od,onAction:f,onClose:y},"scope"):jsx(ot,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}F();function Zd({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(ot,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ui({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")}}F();function tp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ui({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(ot,{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 op({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ui({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(ot,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var Hn=x("bundle:installer"),sp=/already exists/i;async function ax(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Ud(t)){let r=await Nd(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(sp.test(n))return;throw new Error(n)}}else {let r=await Lo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(sp.test(n))return;throw new Error(n)}}}async function lx(e,t){try{await v(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Hn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function cx(e,t,r){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Hn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function ip(e,t,r,n){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Hn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function ux(e,t,r,n,o){try{await v(I.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Hn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function mi(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 lx(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){Hn.warn(`Artifact "${y}" has no type \u2014 treated as failed`),l.push({name:y,type:g,reason:"unknown artifact type"}),await ip(i,y,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await ax(f),u++,await cx(i,y,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let E=w instanceof Error?w.message:String(w);Hn.error(`Failed to install artifact "${y}": ${E}`),l.push({name:y,type:g,reason:E}),await ip(i,y,g,E),r?.({index:p+1,total:c,artifact:f,success:false,error:E});}}let d=Date.now()-a,m=l.length;return await ux(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}F();function up({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,mi(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(cp,{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(cp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ie()})}));F();function dp({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)})]})}F();function pp({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 mp(e){return e.adapter.removable!==false?4:2}j();F();function fp({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 hp({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 yp({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,$)=>{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(fp,{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(Qe/2)),p=Math.min(a.length,m+Qe);p===a.length&&(m=Math.max(0,p-Qe));let f=a.slice(m,p),y=m,g=a.length-p,w=s.length>0&&m<s.length,E=p>s.length,D=f.filter(C=>r.has(`${C.name}@${o}`)),M=f.filter(C=>!r.has(`${C.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(C=>jsx(hp,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),E&&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(C=>jsx(hp,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.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"})})]})}el();var yx=/^https?:\/\/.+/;function wx(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Sx(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function bp(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(!yx.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let E=randomUUID(),D=new Un(E,w,g);try{await D.fetchItems(),await Zt.add({id:E,name:w,source:g}),de.register(new Un(E,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let C=wx(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Sx(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(C,"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 Ip(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Zt.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 Ep(){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(),B=await Zt.read(),G=new Map(B.map(Le=>[Le.id,Le]));s(A.map(Le=>({adapter:Le,stored:G.get(Le.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 B=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(G=>{B||p({items:G,loading:false,error:null});}).catch(G=>{B||p({items:[],loading:false,error:G instanceof Error?G.message:"Failed to load catalog"});}),()=>{B=true;}},[i]);let E=bp(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),y("main");},[w]),{handleRemove:M}=Ip(D),C=useCallback(async A=>{y("removing"),await M(A);},[M]),$=useCallback(async A=>{try{let B=await A.adapter.fetchItems();if(p({items:B,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(B){r(B instanceof Error?B.message:"Update failed","error");}},[w,r]),_=useCallback(async A=>{if(!A.stored)return;let B=A.stored.autoUpdate!==false;await Zt.updateField(A.stored.id,{autoUpdate:!B}),w();},[w]),O=useCallback(()=>y("browse"),[]),te=useCallback(A=>{let B=o[i-1];if(!B)return;let G=B.adapter.removable!==false;[O,()=>{$(B);},...G?[()=>{_(B);},()=>{C(B.adapter.id);}]:[]][A]?.();},[o,i,O,$,_,C]),k=useCallback(()=>y("main"),[]),H=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),ee=useCallback(()=>{let A=o[i-1];A&&_(A);},[o,i,_]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);if(useInput((A,B)=>{if(B.upArrow){a(G=>Math.max(0,G-1));return}if(B.downArrow){a(G=>Math.min(o.length,G+1));return}(B.return||B.tab)&&(i===0?E.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&E.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,B)=>{if(B.escape||B.tab){u("list");return}if(B.upArrow){d(G=>Math.max(0,G-1));return}if(B.downArrow){let G=o[i-1],Le=G?mp(G)-1:0;d(Qo=>Math.min(Qo+1,Le));return}B.return&&te(c);},{isActive:f==="main"&&E.phase==="idle"&&l==="detail"&&e==="marketplaces"}),E.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:E.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.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(E.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:E.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:E.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),E.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:E.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(E.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 B=A.adapter.id??"default",G=new Set(n.filter(Le=>Le.marketplace===A.adapter.name).map(Le=>`${Le.name}@${B}`));return jsx(yp,{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(dp,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&V?jsx(pp,{entry:V,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:H,onToggleAutoUpdate:ee,onRemove:K}):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 Pp(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 Tp(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Cp(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 Ex=new Set(ne.filter(e=>e.focus!=="list").map(e=>e.focus));function Ko(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}=We.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 kp({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=We(y=>y.query),a=We(y=>y.setQuery),l=We(y=>y.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:y,setCursorPosition:g}=We.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:E,actionMenuOpen:D}=S.getState();Ko(Na(y,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((y,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:E,actionMenuOpen:D}=S.getState();Ko(Na("",g,{activeTab:w}));},{isActive:Ex.has(t)}),useInput((y,g)=>{let{activeTab:w,selectedIndex:E,actionMenuOpen:D}=S.getState();Ko(Pp(y,g,{activeTab:w,selectedIndex:E},u.current));},{isActive:t==="list"}),useInput((y,g)=>{Ko(Tp(y,g));},{isActive:t==="actionMenu"}),useInput((y,g)=>{let w=Cp(y,g,We.getState().query),E=w.queryUpdate;if(Ko(w.actions),E==="reset")l(),d("");else if(E!==null){let{query:D,cursorPosition:M,setCursorPosition:C}=We.getState();if("backspace"in E)M>0&&(a(D.slice(0,M-1)+D.slice(M)),C(M-1));else if("append"in E)a(D.slice(0,M)+E.append+D.slice(M)),C(M+E.append.length);else if("cursorMove"in E){let $=M+E.cursorMove;$>=0&&$<=D.length&&C($);}}},{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(E=>E.name.toLowerCase().includes(g)||E.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Rp(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=rt(a=>a.justAuthenticated),o=rt(a=>a.credentials),s=rt(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 Fe(e,t,r=false){return r?true:!Pl.valid(e)||!Pl.valid(t)?false:Pl.gt(t,e)}j();R();var rr=x("updater");async function Px(e,t,r,n,o,s){try{await v(I.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Q().interfaceType});}catch(i){rr.warn(`Failed to send update metrics: ${String(i)}`);}}function Tx(e){let t=Oe(),r=`${e}@${le}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function yi(e,t={}){let r=Date.now(),n=null;try{rr.debug(`[${e}] Acquiring lock...`),n=await Cr();let o=Tx(e);if(!o)throw rr.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;rr.debug(`[${e}] Fetching manifest...`);let u=(await Nn(e,t.source)).version;if(!i||!Fe(i,u,t.force))throw rr.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Pr(e,i??"unknown");rr.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Ue(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await Px(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),rr.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){rr.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Cr();let d=Oe(),m=`${e}@${le}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,it(d),rr.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Tr();R();var wi=x("dispatcher");async function Cx(e,t,r,n,o){let s=_n(e);return wi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await ni(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),wi.debug(`[${e}] Retrying install after marketplace add`),Re(t)}async function $p(e,t,r,n){let o=Dn(e,n),s=_n(e);r?.onStatus?.(`Installing ${s}...`),wi.debug(`[${e}] Attempting install: ${o}`);let i=await Re(o);if(i.exitCode===0)return i;wi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Cx(e,o,a,t,r)}async function Lp(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 Mp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Lp(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 $o(i,u,a),t();},[e,t]),s=useCallback(async i=>{await yi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}F();R();var xi=x("mcp");function Vo(e,t){e.silent?tt({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):P(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Dp(e,t){e.silent?we({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(q(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&b(t.stdout));}function kx(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 Tl(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 Op(e,t,r){if(!await pe())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Vo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}xi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=kx(e,t,r.transport,r.scope);if(!r.force){let s=h(e),i=h(n);if(!await Ie(`Install external MCP "${s}"?
118
118
  This will run: ${i}
119
- [y/N] `))return Si.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:Xl({text:`Adding MCP "${h(e)}"...`}).start();try{let s=await Ae(n);return o?.stop(),s.exitCode!==0?(Ko(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&I(`stdout: ${s.stdout}`),1):(Cp(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Ko(r,{name:e,action:"add",message:q(s)}),1}}async function Ap(e,t){if(!await pe())return 1;Si.debug(`[${e}] Starting MCP remove`);let r=Il(e,t.scope);if(!t.force){let o=h(e),s=h(r);if(!await Ue(`Remove MCP "${o}"?
119
+ [y/N] `))return xi.debug(`[${e}] Installation cancelled by user`),b("Operation cancelled."),0}let o=r.silent?void 0:Ql({text:`Adding MCP "${h(e)}"...`}).start();try{let s=await Re(n);return o?.stop(),s.exitCode!==0?(Vo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&b(`stdout: ${s.stdout}`),1):(Dp(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Vo(r,{name:e,action:"add",message:Y(s)}),1}}async function Up(e,t){if(!await pe())return 1;xi.debug(`[${e}] Starting MCP remove`);let r=Tl(e,t.scope);if(!t.force){let o=h(e),s=h(r);if(!await Ie(`Remove MCP "${o}"?
120
120
  This will run: ${s}
121
- [y/N] `))return Si.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:Xl({text:`Removing MCP "${h(e)}"...`}).start();try{let o=await Ae(r);return n?.stop(),o.exitCode!==0?(Ko(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(Cp(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Ko(t,{name:e,action:"remove",message:q(o)}),1}}$();function $p({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Pp(),f=async(C,R,_)=>{l(true,C),n();try{await R(),o(r.length),s(_,"success");}catch(O){let ee=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${ee}`),s(ee,"error");}finally{l(false);}};return {handleInstall:(C,R)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:C,...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:C=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let R=e.status==="enabled";f(R?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),R?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(_){if(_ instanceof Pr)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:C=>{if(C.length===0)return;let R=C.length;(async()=>{l(true,`Updating ${R} plugin${R>1?"s":""}...`),n();try{let O=[];for(let H of C)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"?C[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:C=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let R=Il(e.name,C),_=await Ae(R);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Eo();$();var Vo=x("api:bundle"),zn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Ho=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},lx=/^[a-zA-Z0-9_-]{1,128}$/;async function Lp(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Vo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new zn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new Ho:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Vo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Mp(e){if(!lx.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Vo.debug(`Fetching bundle by flowId "${e}"`);try{return await Xt().get(`v1/use-cases/${t}`).json()}catch(r){return Lp(r,e)}}async function xi(e){let t=encodeURIComponent(e);Vo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Xt().get(`v1/use-cases/by-name/${t}`).json(),Vo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Lp(n,e)}if(r.length===0)throw new zn(e);return r[0]}$();var cx=x("tui:bundle-flow");function _p({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();cx.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Mp(d):xi(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();j();var Jo=["local","project","user"],ux=new Set(["--transport","--scope","-s"]);function Dp(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(ux.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function sn(e,t){return t?`${e}::${t}`:e}function vl(e){return e===le?no:cn}function Op(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??no,flowId:e.flowId}}function El(e,t){let r=vl(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 Up(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:dr[r].label,pathHint:dr[r].pathHint,items:t.get(r)??[]}))}function Np(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 Bp({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>sn(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=>[sn(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(sn(g.name,g.author?.name))??y.get(g.name),E=w?.version,D=!!E&&!!g.version&&Fe(g.version,E);return {...g,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(sn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let y=f.installCommand?Dp(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||y&&i.has(y))return false}return true}).map(f=>Op(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>El(f,f.catalogItem)):a.map(f=>El(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=>[sn(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(sn(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 Pl(){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 cd();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,v(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 Fp(){return {items:fe(t=>t.installedItems)}}$();var gx=x("catalog");function Kp(){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=We(X=>X.query),{catalog:d,isLoading:m,error:p,refetch:f}=Pl(),{items:y}=Fp(),g=fe(X=>X.loadFromDisk),{items:w,emptyMessage:E,getSelectedCatalogItem:D,outdatedCount:M}=Bp({catalog:d,installedItems:y,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:R,selectedIndex:_,clampIndex:O,filteredItems:ee}=xp({listLength:w.length}),k=ee(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:Np(k),[t,k]),Q=useMemo(()=>t==="installed"||t==="updates"?Up(H):[],[t,H]),K=H[_]??null,V=useMemo(()=>D(K),[D,K]),{notify:z}=Ip(),{handleInstall:A,handleUninstall:N,handleToggleStatus:G,handleUpdate:Re,handleBatchUpdate:Zo,handleMcpConfigUninstall:mg}=$p({selectedItem:K,selectedCatalogItem:V,items:w,closeMenu:R,clampIndex:O,notify:z}),{handleBundleInstallStart:fg,handleBundleDetailConfirm:gg,handleBundleDetailBack:hg,handleBundleInstallComplete:yg}=_p({closeMenu:R,notify:z}),wg=useCallback(()=>Zo(H),[Zo,H]);return useEffect(()=>{g();},[]),useEffect(()=>{O(H.length);},[H.length,O]),useEffect(()=>{p&&(gx.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(Cn,{}),jsx(vu,{outdatedCount:M}),t==="marketplaces"&&xr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(hp,{})}):jsx(Bu,{filteredItems:H,groups:Q,emptyMessage:E,onBatchUpdate:wg}),(n||m)&&jsxs(Fragment,{children:[jsx(Vs,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Js,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Gs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Fu,{message:r.message,type:r.type}),C&&K&&(t==="discover"?V?.type==="bundle"?e?.phase==="installing"?jsx(rp,{bundle:e.bundle,onComplete:yg}):jsx(Hd,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>fg(K.name,K.flowId),onConfirm:gg,onClose:e?.phase==="detail"?hg:R}):jsx(Kd,{itemName:K.name,itemType:V?.type,onInstall:A,onClose:R}):K.type==="mcp"?jsx(qd,{itemName:K.name,itemScope:K.scope??"user",onUninstall:mg,onClose:R}):jsx(Wd,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:V?.version,onUninstall:N,onToggleStatus:X=>G(X),onUpdate:Re,onClose:R})),jsx(Ks,{})]})}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 xx=3;function Hp(){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 y=1;y<=xx;y++)try{await Oe(m.name,{onDownloadProgress:(g,w)=>{let E=Date.now();(E-l.current>100||g>=w)&&(l.current=E,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof ze){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),v(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=Jr();Hr("summary_review"),v(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 Go={cursorDelta:0,confirm:false,back:false};function Jp(e,t){return t.upArrow?{...Go,cursorDelta:-1}:t.downArrow?{...Go,cursorDelta:1}:t.escape?{...Go,back:true}:t.return?{...Go,confirm:true}:Go}var bx={cursorDelta:0,select:false};function Gp(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:bx}B();var Wp=yy.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 Ll=5;function zp({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(Vs,{message:"Loading Starter Kits..."});if(o)return jsx(Gs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(kn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Ll/2)),i=Math.min(t.length,s+Ll);i===t.length&&(s=Math.max(0,i-Ll));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(Wp,{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 qp=yy.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 Dl=8;function Yp(){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,v(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(Dl/2)),i=Math.min(t.length,s+Dl);i===t.length&&(s=Math.max(0,i-Dl));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(qp,{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 $x=["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(tp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Js,{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 Qp({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:$x.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 em(){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=rt(k=>k.setJustAuthenticated),E=rt(k=>k.justAuthenticated),{loadStarterKits:D,installSelected:M}=Hp(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(y("starterKitList"),C.current||(C.current=true,Hr("bundle_selection"))):y(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,y]);let R=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let Q=await Y();Q&&await gr({...Q,starterKit:k.slug});}v(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Jr()}).catch(()=>{});let{successCount:H}=L.getState();v(b.CLI_ONBOARDING_COMPLETED,{duration_ms:yr(),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)Ps("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=Jr();o(t[r]),Hr("kit_display"),v(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 K=i+Q.cursorDelta;K>=0&&K<s.length&&a(K);}if(Q.confirm){let K=L.getState().selectedStarterKit;K&&(async()=>(await Y())?.starterKit!==K.slug&&v(b.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let V=Jr();Hr("kit_confirmation"),v(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:V}).catch(()=>{});let z=Jr();Hr("tool_installation"),v(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:z}).catch(()=>{}),l("installing"),M();}if(Q.back){let K=L.getState().selectedStarterKit;K&&v(b.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let Q=Gp(k,H);if(Q.cursorDelta!==0){let K=u+Q.cursorDelta;K>=0&&K<=1&&c(K);}Q.select&&(u===0?_():R());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Cn,{}),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."}),!E&&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(zp,{onRetry:O}),e==="starterKitDetail"&&jsx(Yp,{}),(e==="installing"||e==="summary")&&jsx(Qp,{onComplete:R,onRetry:_})]}),jsx(Ks,{})]})}j();var nm=null;function om(){return nm}async function ki(){let t=qr().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 sm(n);(o||s)&&await yt({...r,installedVersion:o,installMethod:s});}}async function sm(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 qn(e){let t=await Promise.all(e.map(r=>Mx(r)));return nm=t,t}async function Mx(e){let t=tm(e.versionCommand);t==="permission-denied"&&(_x(e.versionCommand[0]),t=tm(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&&!nt(e.alias)){let{installedVersion:l,installMethod:u}=await sm(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 tm(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 _x(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 Ux(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 um(e,t){let[r,n]=useState(()=>Ux(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 E=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(E+1)%w.availableStrategies.length];n(M=>M.map(C=>C.module.alias===w.module.alias?{...C,selectedStrategy:D}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}B();function pm({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}=um(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(ot,{itemName:m,actions:d,onAction:c,onClose:u})]})}var Kx=/^https?:\/\/.+/;function mm({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 Hx(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 hm(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=Hx(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 vr(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}}j();B();function ym({module:e}){let t=h(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(tp,{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 bm({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}=hm(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(()=>{Yr().catch(()=>{}),n("list");let w=ie().some(E=>E.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,E)=>{E.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(ym,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,E,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(E),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 vm(){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(ou(p)){Yr().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=om();if(p){c(p);return}qn(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(pm,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(mm,{onConfirm:m}),e==="installation"&&jsx(bm,{confirmedItems:o,customUrl:i})]})}j();$();var eb=x("ClaudeMdSuggestion"),tb=[`Install ${ce}`,"Skip for now"],rb=["Retry","Skip for now"];function Tm(){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(()=>{v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Oe(ce),o("installed");}catch(m){if(m instanceof ze){o("installed");return}eb.warn(`Failed to install ${ce}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?rb:tb;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(Cn,{}),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(Pm,{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(tp,{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(Pm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Pm({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 ib=promisify(execFile),Mi="@ciandt-flow/cli";async function Cm(){let e=ue;if(bl.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Mi};try{let t=await fetch(`https://registry.npmjs.org/${Mi}/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:Mi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Mi}}}async function _i(e){try{return await ib(Wt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function ab(e){let t=nt(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 km(e){let t=await ab(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 Am(e,t){let r=nt(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 $m(e){let r=nt(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 Rm(){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([Cm(),qn(se),Promise.all(se.map(l=>km(l)))]);if(ki(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await _i(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 Am(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:$m(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Yr(),t(l=>({...l,outcome:"done"}));}catch{await Yr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}j();function mb({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(tp,{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 fb({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 Lm(){let{outcome:e,items:t}=Rm(),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(mb,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(fb,{outcome:e})})]})}Ie();In();$();ta();var wb={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Mm=10;function _m(){let[e,t]=useState(ea());useEffect(()=>bc(()=>{t([...ea()]);}),[]);let r=e.slice(-Mm);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Mm,") \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:wb[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Ib=x("app"),vb={auth:gu,starterKitSetup:em,moduleSetup:vm,claudeMdSuggestion:Tm,verify:Lm,main:Kp};function Um(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Bs(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Nm(){v(b.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:yr(),interface:"tui"}).catch(()=>{});}async function Fm(){let e=await Y();if(e&&ru()&&await hr()){e.customUrl&&kt(e.customUrl);let{clientSecret:n,...o}=e;rt.getState().setCredentials(o),Nm(),Bs(e);return}if(!e){Um();return}try{e.customUrl&&kt(e.customUrl),await $t();}catch(n){Ib.debug(`Token validation failed: ${String(n)}`),Um();return}Nm();let{clientSecret:t,...r}=e;rt.getState().setCredentials(r),Bs(e);}function jm(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=vb[r],{pendingExit:o}=Wc(),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(_m,{}),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();vs();B();j();$();lo();Ie();async function Wl(e,t={}){let r=ks({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return As(r),await gr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Pt=x("auth");function Vm(){Ge.clearFallbackFile(),Ss();}var Eb=3,Km=3,Hm=` \u2139 The data collected during setup is used solely to improve
121
+ [y/N] `))return xi.debug(`[${e}] Removal cancelled by user`),b("Operation cancelled."),0}let n=t.silent?void 0:Ql({text:`Removing MCP "${h(e)}"...`}).start();try{let o=await Re(r);return n?.stop(),o.exitCode!==0?(Vo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&b(`stdout: ${o.stdout}`),1):(Dp(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Vo(t,{name:e,action:"remove",message:Y(o)}),1}}R();function Np({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Mp(),f=async(C,$,_)=>{l(true,C),n();try{await $(),o(r.length),s(_,"success");}catch(O){let te=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${te}`),s(te,"error");}finally{l(false);}};return {handleInstall:(C,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:C,...$!==void 0?{providerId:$}:{},onDownloadProgress:(_,O)=>{let te=Date.now();(te-a.current>100||_>=O)&&(a.current=te,u(_,O));}}),"\u2713 Installed successfully"));},handleUninstall:C=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(_){if(_ instanceof Pr)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:C=>{if(C.length===0)return;let $=C.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let O=[];for(let H of C)O.push(await p(H.name).then(()=>({status:"fulfilled",value:void 0}),ee=>({status:"rejected",reason:ee})));let te=O.filter(H=>H.status==="fulfilled").length,k=O.map((H,ee)=>H.status==="rejected"?C[ee].name:null).filter(H=>H!==null);o(r.length),k.length===0?s(`\u2713 Updated ${te}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${te}/${$}; failed: ${k.join(", ")}`,te>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:C=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=Tl(e.name,C),_=await Re($);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Po();R();var Ho=x("api:bundle"),Xn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Jo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},$x=/^[a-zA-Z0-9_-]{1,128}$/;async function Fp(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Ho.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new Xn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new Jo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Ho.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function jp(e){if(!$x.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Ho.debug(`Fetching bundle by flowId "${e}"`);try{return await Yt().get(`v1/use-cases/${t}`).json()}catch(r){return Fp(r,e)}}async function bi(e){let t=encodeURIComponent(e);Ho.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Yt().get(`v1/use-cases/by-name/${t}`).json(),Ho.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Fp(n,e)}if(r.length===0)throw new Xn(e);return r[0]}R();var Lx=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();Lx.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?jp(d):bi(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");}}}F();j();var Go=["local","project","user"],Mx=new Set(["--transport","--scope","-s"]);function Vp(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(Mx.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function an(e,t){return t?`${e}::${t}`:e}function Cl(e){return e===le?oo:un}function Hp(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??oo,flowId:e.flowId}}function kl(e,t){let r=Cl(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 Jp(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 Go.filter(r=>t.has(r)).map(r=>({scope:r,label:Gt[r].label,pathHint:Gt[r].pathHint,items:t.get(r)??[]}))}function Gp(e){let t=r=>{if(!r)return 1/0;let n=Go.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Wp({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>an(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=>[an(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(an(g.name,g.author?.name))??y.get(g.name),E=w?.version,D=!!E&&!!g.version&&Fe(g.version,E);return {...g,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(an(f.name,f.author?.name)))return false;if(f.type==="mcp"){let y=f.installCommand?Vp(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||y&&i.has(y))return false}return true}).map(f=>Hp(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>kl(f,f.catalogItem)):a.map(f=>kl(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=>[an(g.name,g.author?.name),g])),y=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(an(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 Al(){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 wd();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,v(I.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 zp(){return {items:fe(t=>t.installedItems)}}R();var Nx=x("catalog");function qp(){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=We(X=>X.query),{catalog:d,isLoading:m,error:p,refetch:f}=Al(),{items:y}=zp(),g=fe(X=>X.loadFromDisk),{items:w,emptyMessage:E,getSelectedCatalogItem:D,outdatedCount:M}=Wp({catalog:d,installedItems:y,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:_,clampIndex:O,filteredItems:te}=kp({listLength:w.length}),k=te(w),H=useMemo(()=>t!=="installed"&&t!=="updates"?k:Gp(k),[t,k]),ee=useMemo(()=>t==="installed"||t==="updates"?Jp(H):[],[t,H]),K=H[_]??null,V=useMemo(()=>D(K),[D,K]),{notify:z}=Rp(),{handleInstall:A,handleUninstall:B,handleToggleStatus:G,handleUpdate:Le,handleBatchUpdate:Qo,handleMcpConfigUninstall:Og}=Np({selectedItem:K,selectedCatalogItem:V,items:w,closeMenu:$,clampIndex:O,notify:z}),{handleBundleInstallStart:Ug,handleBundleDetailConfirm:Ng,handleBundleDetailBack:Bg,handleBundleInstallComplete:Fg}=Kp({closeMenu:$,notify:z}),jg=useCallback(()=>Qo(H),[Qo,H]);return useEffect(()=>{g();},[]),useEffect(()=>{O(H.length);},[H.length,O]),useEffect(()=>{p&&(Nx.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(kn,{}),jsx(Lu,{outdatedCount:M}),t==="marketplaces"&&xr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Ep,{})}):jsx(zu,{filteredItems:H,groups:ee,emptyMessage:E,onBatchUpdate:jg}),(n||m)&&jsxs(Fragment,{children:[jsx(Hs,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Gs,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Ws,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Xu,{message:r.message,type:r.type}),C&&K&&(t==="discover"?V?.type==="bundle"?e?.phase==="installing"?jsx(up,{bundle:e.bundle,onComplete:Fg}):jsx(Zd,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Ug(K.name,K.flowId),onConfirm:Ng,onClose:e?.phase==="detail"?Bg:$}):jsx(qd,{itemName:K.name,itemType:V?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(op,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Og,onClose:$}):jsx(tp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:V?.version,onUninstall:B,onToggleStatus:X=>G(X),onUpdate:Le,onClose:$})),jsx(Vs,{})]})}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"})}));Ee();var Vx=3;function Zp(){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 ei();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<=Vx;y++)try{await Ue(m.name,{onDownloadProgress:(g,w)=>{let E=Date.now();(E-l.current>100||g>=w)&&(l.current=E,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof ze){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),v(I.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Q().interfaceType}).catch(()=>{}));}let d=Gr();Jr("summary_review"),v(I.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 Wo={cursorDelta:0,confirm:false,back:false};function Qp(e,t){return t.upArrow?{...Wo,cursorDelta:-1}:t.downArrow?{...Wo,cursorDelta:1}:t.escape?{...Wo,back:true}:t.return?{...Wo,confirm:true}:Wo}var Hx={cursorDelta:0,select:false};function em(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Hx}F();var tm=Fy.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 Ol=5;function rm({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(Hs,{message:"Loading Starter Kits..."});if(o)return jsx(Ws,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(An,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Ol/2)),i=Math.min(t.length,s+Ol);i===t.length&&(s=Math.max(0,i-Ol));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(tm,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}F();var om=Fy.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)"})]})});F();var Bl=8;function sm(){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,v(I.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(Bl/2)),i=Math.min(t.length,s+Bl);i===t.length&&(s=Math.max(0,i-Bl));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(om,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}F();var Qx=["Retry failed","Continue anyway"];function im({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(cp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Gs,{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 am({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(im,{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(im,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Qx.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 lm(){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=rt(k=>k.setJustAuthenticated),E=rt(k=>k.justAuthenticated),{loadStarterKits:D,installSelected:M}=Zp(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(y("starterKitList"),C.current||(C.current=true,Jr("bundle_selection"))):y(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,y]);let $=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let ee=await Z();ee&&await gr({...ee,starterKit:k.slug});}v(I.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Gr()}).catch(()=>{});let{successCount:H}=L.getState();v(I.CLI_ONBOARDING_COMPLETED,{duration_ms:yr(),tools_installed_count:H}).catch(()=>{}),w(false),y("verify"),f("verify");},[w,y,f]),_=useCallback(()=>{m(),M();},[m,M]),O=useCallback(()=>{D();},[D]),te=useCallback(()=>{y("verify"),f("verify");},[y,f]);return useInput((k,H)=>{if(H.escape)Ts("esc"),te();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 ee=Gr();o(t[r]),Jr("kit_display"),v(I.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ee}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,H)=>{let ee=Qp(k,H);if(ee.cursorDelta!==0){let K=i+ee.cursorDelta;K>=0&&K<s.length&&a(K);}if(ee.confirm){let K=L.getState().selectedStarterKit;K&&(async()=>(await Z())?.starterKit!==K.slug&&v(I.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let V=Gr();Jr("kit_confirmation"),v(I.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:V}).catch(()=>{});let z=Gr();Jr("tool_installation"),v(I.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:z}).catch(()=>{}),l("installing"),M();}if(ee.back){let K=L.getState().selectedStarterKit;K&&v(I.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,H)=>{if(d===0)return;let ee=em(k,H);if(ee.cursorDelta!==0){let K=u+ee.cursorDelta;K>=0&&K<=1&&c(K);}ee.select&&(u===0?_():$());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(kn,{}),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."}),!E&&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(rm,{onRetry:O}),e==="starterKitDetail"&&jsx(sm,{}),(e==="installing"||e==="summary")&&jsx(am,{onComplete:$,onRetry:_})]}),jsx(Vs,{})]})}j();var dm=null;function pm(){return dm}async function Ai(){let t=Yr().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 mm(n);(o||s)&&await yt({...r,installedVersion:o,installMethod:s});}}async function mm(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 Yn(e){let t=await Promise.all(e.map(r=>rb(r)));return dm=t,t}async function rb(e){let t=cm(e.versionCommand);t==="permission-denied"&&(nb(e.versionCommand[0]),t=cm(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&&!nt(e.alias)){let{installedVersion:l,installMethod:u}=await mm(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 cm(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 nb(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=ve__default.realpathSync(r),{mode:o}=ve__default.statSync(n);ve__default.chmodSync(n,o|73);}catch{}}function ib(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 wm(e,t){let[r,n]=useState(()=>ib(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 E=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(E+1)%w.availableStrategies.length];n(M=>M.map(C=>C.module.alias===w.module.alias?{...C,selectedStrategy:D}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}F();function xm({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}=wm(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(ot,{itemName:m,actions:d,onAction:c,onClose:u})]})}var db=/^https?:\/\/.+/;function bm({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&&db.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 mb(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 Em(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=mb(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 vr(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}}j();F();function Pm({module:e}){let t=h(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(cp,{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 Am({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}=Em(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(E=>E.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,E)=>{E.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(Pm,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,E,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(E),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 $m(){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(mu(p)){Zr().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=pm();if(p){c(p);return}Yn(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(xm,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(bm,{onConfirm:m}),e==="installation"&&jsx(Am,{confirmedItems:o,customUrl:i})]})}j();R();var vb=x("ClaudeMdSuggestion"),Eb=[`Install ${ce}`,"Skip for now"],Pb=["Retry","Skip for now"];function _m(){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(()=>{v(I.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Ue(ce),o("installed");}catch(m){if(m instanceof ze){o("installed");return}vb.warn(`Failed to install ${ce}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Pb:Eb;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(kn,{}),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(Mm,{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(cp,{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(Mm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Mm({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 Ab=promisify(execFile),_i="@ciandt-flow/cli";async function Dm(){let e=ue;if(Pl.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 Di(e){try{return await Ab(Xt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Rb(e){let t=nt(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 Om(e){let t=await Rb(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 Um(e,t){let r=nt(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 Nm(e){let r=nt(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 Bm(){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([Dm(),Yn(se),Promise.all(se.map(l=>Om(l)))]);if(Ai(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Di(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 Um(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:Nm(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}j();function Ob({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(cp,{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 Ub({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 Fm(){let{outcome:e,items:t}=Bm(),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(Ub,{outcome:e})})]})}Ee();vn();R();sa();var jb={debug:"gray",info:"cyan",warn:"yellow",error:"red"},jm=10;function Km(){let[e,t]=useState(oa());useEffect(()=>Rc(()=>{t([...oa()]);}),[]);let r=e.slice(-jm);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",jm,") \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:jb[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Jb=x("app"),Gb={auth:Eu,starterKitSetup:lm,moduleSetup:$m,claudeMdSuggestion:_m,verify:Fm,main:qp};function Jm(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Fs(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Gm(){v(I.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:yr(),interface:"tui"}).catch(()=>{});}async function zm(){let e=await Z();if(e&&du()&&await hr()){e.customUrl&&kt(e.customUrl);let{clientSecret:n,...o}=e;rt.getState().setCredentials(o),Gm(),Fs(e);return}if(!e){Jm();return}try{e.customUrl&&kt(e.customUrl),await Rt();}catch(n){Jb.debug(`Token validation failed: ${String(n)}`),Jm();return}Gm();let{clientSecret:t,...r}=e;rt.getState().setCredentials(r),Fs(e);}function Xm(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=Gb[r],{pendingExit:o}=ru(),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]})}Ee();Es();F();j();R();co();Ee();async function Yl(e,t={}){let r=As({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Rs(r),await gr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Pt=x("auth");function Ym(){Ge.clearFallbackFile(),xs();}var Wb=3,qm=3,Zm=` \u2139 The data collected during setup is used solely to improve
122
122
  Flow's internal tools and will not be shared externally.
123
- `;function lr(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===`
123
+ `;function Ht(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===`
124
124
  `){l(),process.stdout.write(`
125
- `),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 Pb(){let e=zr();return process.stdout.write(`
125
+ `),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 zb(){let e=Xr();return process.stdout.write(`
126
126
  `+T.yellow(" \u26A0 ")+`${h(e)} contains invalid JSON.
127
- `),(await lr(T.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 Wl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof Xr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${zr()} and retry.`);if(!await Pb())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Wl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function Tb(){if((await lr(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await lr(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(dn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${pn}. Try again.
128
- `));}}async function Cb(){let e=(await lr(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await lr(T.cyan(" ? ")+"Enter your email address: ")).trim();if(mn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${fn}. Try again.
129
- `));}}async function Gm(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Ns(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
127
+ `),(await Ht(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Qm(e,t,r){try{await Yl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof qr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${Xr()} and retry.`);if(!await zb())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Yl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function Xb(){if((await Ht(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Ht(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(pn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${mn}. Try again.
128
+ `));}}async function qb(){let e=(await Ht(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await Ht(T.cyan(" ? ")+"Enter your email address: ")).trim();if(fn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${gn}. Try again.
129
+ `));}}async function ef(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Bs(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
130
130
  `)):o?process.stdout.write(T.yellow(` \u26A0 Unexpected error. Please contact Flow support.
131
131
  `)):n?process.stdout.write(T.yellow(`
132
132
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
133
133
  `)):process.stdout.write(T.green(` done
134
- `)),{initFailed:n}}async function Wm(){for(let e=1;e<=Km;e++)try{return await Qs()}catch{if(e===Km)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function zm(){let e=await Wm();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
134
+ `)),{initFailed:n}}async function tf(){for(let e=1;e<=qm;e++)try{return await ei()}catch{if(e===qm)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function rf(){let e=await tf();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await Ht(T.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
135
135
  `+T.cyan(" ? ")+`Starter Kit:
136
- `),e.forEach((t,r)=>{process.stdout.write(` ${T.cyan(`${r+1})`)} ${h(t.name)}
137
- `);}),process.stdout.write(` ${T.cyan("0)")} Skip \u2014 don't install any starter kit now
138
- `),process.stdout.write(`
139
- `);;){let t=(await lr(T.cyan(" ? ")+`Select starter kit (0-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(t==="0")return null;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(T.yellow(` \u26A0 Invalid selection. Please try again.
140
- `));}}async function Xm(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
136
+ `),e.forEach((r,n)=>{process.stdout.write(` ${T.cyan(`${n+1})`)} ${h(r.name)}
137
+ `);}),process.stdout.write(`
138
+ `);;){let r=(await Ht(T.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),n=parseInt(r,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(T.yellow(` \u26A0 Invalid selection. Please try again.
139
+ `));}}async function nf(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
141
140
  Starter kit '${h(e.name)}' has no plugins to install.
142
141
  `)),true;process.stdout.write(`
143
142
  Installing ${e.plugins.length} plugins from '${h(e.name)}'...
144
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${h(o)}...`));let i=false;for(let a=1;a<=Eb;a++)try{await Oe(o),t++,i=!0;break}catch(l){if(l instanceof ze){t++,i=true;break}}i?process.stdout.write(T.green(` done
143
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${h(o)}...`));let i=false;for(let a=1;a<=Wb;a++)try{await Ue(o),t++,i=!0;break}catch(l){if(l instanceof ze){t++,i=true;break}}i?process.stdout.write(T.green(` done
145
144
  `)):(r++,process.stdout.write(T.red(` failed
146
145
  `)));}return r===0?process.stdout.write(T.green(` \u2713 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed successfully.
147
146
  `)):process.stdout.write(T.yellow(` \u26A0 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
148
- `)),r===0}async function qm(){process.stdout.write(`
147
+ `)),r===0}async function of(){process.stdout.write(`
149
148
  `),process.stdout.write(T.bold(` Personalize your Claude Code
150
149
  `)),process.stdout.write(T.dim(` This plugin helps Claude understand your preferences and work style.
151
150
 
152
- `));let e=(await lr(T.cyan(" ? ")+`Install ${ce}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(`
151
+ `));let e=(await Ht(T.cyan(" ? ")+`Install ${ce}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){v(I.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(`
153
152
  You can always install it later from the catalog.
154
- `));return}v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${ce}...`));try{await Oe(ce),process.stdout.write(T.green(` done
153
+ `));return}v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${ce}...`));try{await Ue(ce),process.stdout.write(T.green(` done
155
154
  `));}catch(t){if(t instanceof ze)process.stdout.write(T.green(` already installed
156
155
  `));else {Pt.warn(`Failed to install ${ce}: ${t instanceof Error?t.message:t}`),process.stdout.write(T.red(` failed
157
156
  `)),process.stdout.write(T.dim(` You can install it later from the catalog.
@@ -159,112 +158,112 @@ This will run: ${s}
159
158
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
160
159
  `),process.stdout.write(T.cyan.bold(` /${ce}
161
160
  `)),process.stdout.write(` Claude will guide you through the rest.
162
- `);}async function kb(e){if(Vm(),process.stdout.write(`
163
- `+Hm+`
164
- `),e.customUrl!==void 0&&!dn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${pn}.
165
- `)),1;if(e.customEmail!==void 0&&!mn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${fn}.
166
- `)),1;let t=e.jwt.trim(),r;try{r=So(t);}catch(o){let s=h(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
167
- `)),1}e.customUrl&&kt(e.customUrl),Pt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Vr(r);}catch(o){let s=h(o instanceof Error?o.message:"unknown error");return Pt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
168
- `)),1}let{initFailed:n}=await Gm(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Wm(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${h(e.starterKit)}' not found.
161
+ `);}async function Yb(e){if(Ym(),process.stdout.write(`
162
+ `+Zm+`
163
+ `),e.customUrl!==void 0&&!pn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${mn}.
164
+ `)),1;if(e.customEmail!==void 0&&!fn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${gn}.
165
+ `)),1;let t=e.jwt.trim(),r;try{r=xo(t);}catch(o){let s=h(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
166
+ `)),1}e.customUrl&&kt(e.customUrl),Pt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Hr(r);}catch(o){let s=h(o instanceof Error?o.message:"unknown error");return Pt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
167
+ `)),1}let{initFailed:n}=await ef(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await tf(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${h(e.starterKit)}' not found.
169
168
  `)),process.stderr.write(` Available starter kits:
170
169
  `);for(let a of s)process.stderr.write(` - ${h(a.slug)} (${h(a.name)})
171
- `);return 1}o=i;}else o=await zm();return await Jm({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await Xm(o):process.stdout.write(T.dim(`
170
+ `);return 1}o=i;}else o=await rf();return await Qm({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await nf(o):process.stdout.write(T.dim(`
172
171
  Skipped starter kit installation.
173
- `)),await qm(),Pt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
174
- \u2713 Setup complete. Tenant: ${h(r.tenant)}. JWT written to ${zr()}.
172
+ `)),await of(),Pt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
173
+ \u2713 Setup complete. Tenant: ${h(r.tenant)}. JWT written to ${Xr()}.
175
174
 
176
175
  `)),n&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
177
176
  `)),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(T.red(` \u2717 Starter kit setup failed: ${s}
178
- `)),1}}async function Ab(e,t){Vm(),Pt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
179
- `),process.stdout.write(Hm+`
180
- `);let r=(await lr(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Pt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
181
- `)),1;let n;try{n=So(r);}catch(l){let u=h(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
182
- `)),1}let o=e??await Tb(),s=t??await Cb();o&&kt(o),Pt.debug(`[${n.tenant}] Authenticating tenant`);try{await Vr(n);}catch(l){let u=h(l instanceof Error?l.message:"unknown error");return Pt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
183
- `)),1}let{initFailed:i}=await Gm(o,s),a=await zm();return await Jm({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await Xm(a):process.stdout.write(T.dim(`
177
+ `)),1}}async function Zb(e,t){Ym(),Pt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
178
+ `),process.stdout.write(Zm+`
179
+ `);let r=(await Ht(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Pt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
180
+ `)),1;let n;try{n=xo(r);}catch(l){let u=h(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
181
+ `)),1}let o=e??await Xb(),s=t??await qb();o&&kt(o),Pt.debug(`[${n.tenant}] Authenticating tenant`);try{await Hr(n);}catch(l){let u=h(l instanceof Error?l.message:"unknown error");return Pt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
182
+ `)),1}let{initFailed:i}=await ef(o,s),a=await rf();return await Qm({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await nf(a):process.stdout.write(T.dim(`
184
183
  Skipped starter kit installation.
185
- `)),await qm(),Pt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
186
- \u2713 Setup complete. Tenant: ${h(n.tenant)}. JWT written to ${zr()}.
184
+ `)),await of(),Pt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
185
+ \u2713 Setup complete. Tenant: ${h(n.tenant)}. JWT written to ${Xr()}.
187
186
 
188
187
  `)),i&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
189
188
  `)),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(T.red(` \u2717 Unexpected error: ${n}
190
- `)),1}}async function zl(e={}){if(e.jwt)return kb({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!dn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${pn}.
191
- `)),1;if(e.customEmail!==void 0&&!mn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${fn}.
192
- `)),1;try{return await Ab(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
193
- `),130;throw t}}async function $b(){try{return process.stdout.write(`
194
- `),(await lr(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
189
+ `)),1}}async function Zl(e={}){if(e.jwt)return Yb({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!pn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${mn}.
190
+ `)),1;if(e.customEmail!==void 0&&!fn.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${gn}.
191
+ `)),1;try{return await Zb(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
192
+ `),130;throw t}}async function Qb(){try{return process.stdout.write(`
193
+ `),(await Ht(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
195
194
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
196
- `),130;throw e}}async function Ym(e){if(!await Y())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
197
- `)),0;if(!e){let t=await $b();if(t!==null)return t}try{return await Mc(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
195
+ `),130;throw e}}async function sf(e){if(!await Z())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
196
+ `)),0;if(!e){let t=await Qb();if(t!==null)return t}try{return await Kc(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
198
197
  `)),0}catch{return process.stderr.write(T.red(` \u2717 Error removing credentials
199
- `)),1}}async function Zm(){let e=await Y();return e?await hr()?(process.stdout.write(`
198
+ `)),1}}async function af(){let e=await Z();return e?await hr()?(process.stdout.write(`
200
199
  `+T.bold(` Authenticated
201
200
  `)),process.stdout.write(T.dim(" Tenant: ")+h(e.tenant)+`
202
201
  `),process.stdout.write(T.dim(" Client ID: ")+h(e.clientId)+`
203
202
  `),process.stdout.write(T.dim(" Starter Kit: ")+h(e.starterKit??"not set")+`
204
- `),process.stdout.write(T.dim(" Config: ")+h(await _c())+`
203
+ `),process.stdout.write(T.dim(" Config: ")+h(await Vc())+`
205
204
  `),process.stdout.write(`
206
- `),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}B();j();He();j();var Lb=[le,"flow-harness"];function Qm(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Mb(e,t,r=process.env){return Qm(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Qm(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 ef(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 Oi(e=process.env){let t=Nr();if(!be__default.existsSync(t))return [];try{let r=JSON.parse(be__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>Mb(n,o,e))}catch{return []}}function tf(){let e=Nr(),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 Lb){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 _b(e){let t=ie(),r;try{r=await Yt(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return v(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(pr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(wn(["","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 Db(e){let t=ie(),r=await Yt(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&&Fe(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return v(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(I("All plugins are up to date."),0):e.json?(pr(o),0):(wn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
205
+ `),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}F();j();He();j();var tI=[le,"flow-harness"];function lf(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function rI(e,t,r=process.env){return lf(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:lf(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 cf(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 Ui(e=process.env){let t=Br();if(!ve__default.existsSync(t))return [];try{let r=JSON.parse(ve__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>rI(n,o,e))}catch{return []}}function uf(){let e=Br(),t={fixed:[],skipped:[]};if(!ve__default.existsSync(e))return t;let r;try{r=JSON.parse(ve__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 tI){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`;ve__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(o,e);}return t}async function nI(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 v(I.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(pr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Sn(["","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 oI(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&&Fe(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return v(I.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(b("All plugins are up to date."),0):e.json?(pr(o),0):(Sn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
207
206
  ${o.length} plugin(s) outdated.
208
- `),0)}async function Ob(e){let t=ie();if(v(b.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return pr(t),0;let r=[];try{r=await Yt(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(Oi().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=Jo.indexOf(i.scope??"user"),u=Jo.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return wn(["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??vl(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",un[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,Ct(i.installedAt??"")]})),process.stdout.write(`
207
+ `),0)}async function sI(e){let t=ie();if(v(I.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return b("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return pr(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(Ui().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=Go.indexOf(i.scope??"user"),u=Go.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return Sn(["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??Cl(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",dn[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,Ct(i.installedAt??"")]})),process.stdout.write(`
209
208
  ${t.length} plugin(s) installed.
210
- `),0}async function rf(e){if(!await pe())return 1;try{return e.available?await _b(e):e.outdated?await Db(e):await Ob(e)}catch(t){return P(t instanceof Error?t.message:"Failed to list plugins."),1}}Tr();B();j();$();var me=x("manage");function Ui(e,t){return t?ie().find(r=>r.name===e&&r.scope===t):ie().find(r=>r.name===e)}function Ub(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Xl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Nb(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=h(e),a=h(_n(e,r.scope));if(!await Ue(`${t}Install external plugin "${i}"?
209
+ `),0}async function df(e){if(!await pe())return 1;try{return e.available?await nI(e):e.outdated?await oI(e):await sI(e)}catch(t){return P(t instanceof Error?t.message:"Failed to list plugins."),1}}Tr();F();j();R();var me=x("manage");function Ni(e,t){return t?ie().find(r=>r.name===e&&r.scope===t):ie().find(r=>r.name===e)}function iI(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,b(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Ql({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function aI(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=h(e),a=h(Dn(e,r.scope));if(!await Ie(`${t}Install external plugin "${i}"?
211
210
  This will run: ${a}
212
- [y/N] `))return me.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Xl({text:`${t}Installing ${e}...`}).start());}let s=o?Ub(t,o):void 0;try{let i=await vp(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?tt({status:"error",plugin:e,message:a}):P(`${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?tt({status:"error",plugin:e,message:a}):P(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Bb(e,t,r){let n=r.silent?void 0:Xl({text:`${t}Installing ${e}...`}).start();if(Ln(e))return Nb(e,t,r,n);try{let o=await Oe(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=Hs(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 ze)return r.silent?Te({status:"already_installed",plugin:e,message:o.message}):I(`${t}${o.message}`),{name:e,success:true};let s=q(o);return r.silent?tt({status:"error",plugin:e,message:s}):P(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function Fb(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
213
- Installation summary: ${t} succeeded, ${r} failed`);}async function jb(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 Yt();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 eo(e,t={}){if(!await pe())return 1;let r=[],n=await jb(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 Bb(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}:{}}))}):Fb(r)),r.some(o=>!o.success)?1:0}async function nf(e,t){if(!await pe())return 1;if(me.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Ui(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`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 Ue(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return me.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return me.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Ao(e,t.scope),me.info(`[${e}] Uninstalled successfully`),te("Plugin removed successfully"),0}catch(r){return me.error(`[${e}] Failed to uninstall: ${q(r)}`),P(q(r)),1}}async function of(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Ui(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return me.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return me.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await $o(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)}`),P(q(n)),1}}async function sf(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Ui(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return me.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return me.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await $o(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)}`),P(q(n)),1}}async function af(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await hi(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 Pr)return r.silent?Te({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=q(n);return r.silent?tt({status:"error",plugin:e,message:o}):P(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Kb(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
214
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Vb(e,t,r){try{let n=await Un(e,r.source);Fe(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return P(q(n)),1}return 0}function Hb(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Jb(e,t,r){let n=t.get(e.name);return n?e.version&&Fe(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function Gb(e,t){try{let r=await Yt(t.source),n=Hb(r),o=0;for(let s of e)Jb(s,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return P(q(r)),1}return 0}async function Wb(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await af(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}:{}}))}):Kb(r),r.some(n=>!n.success)?1:0}async function lf(e,t={}){if(!await pe())return 1;if(e){let o=Ui(e,t.scope);return o?t.dryRun?Vb(e,o.version??"",t):(await af(e,"",t)).success?0:1:(t.silent?tt({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):P(`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"}):I("No plugins installed"),0):t.dryRun?Gb(n,t):Wb(n,t)}B();$();var qo=x("cli:bundle");function zb(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 Xb(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
211
+ [y/N] `))return me.debug(`[${e}] Installation cancelled by user`),r.silent||b(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Ql({text:`${t}Installing ${e}...`}).start());}let s=o?iI(t,o):void 0;try{let i=await $p(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?tt({status:"error",plugin:e,message:a}):P(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?we({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):q(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=Y(i);return r.silent?tt({status:"error",plugin:e,message:a}):P(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function lI(e,t,r){let n=r.silent?void 0:Ql({text:`${t}Installing ${e}...`}).start();if(Mn(e))return aI(e,t,r,n);try{let o=await Ue(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?we({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):q(`${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 ze)return r.silent?we({status:"already_installed",plugin:e,message:o.message}):b(`${t}${o.message}`),{name:e,success:true};let s=Y(o);return r.silent?tt({status:"error",plugin:e,message:s}):P(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function cI(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;b(`
212
+ Installation summary: ${t} succeeded, ${r} failed`);}async function uI(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 to(e,t={}){if(!await pe())return 1;let r=[],n=await uI(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 lI(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?we({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}:{}}))}):cI(r)),r.some(o=>!o.success)?1:0}async function Bi(e,t){if(!await pe())return 1;if(me.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Ni(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`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 Ie(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return me.debug(`[${e}] Uninstall cancelled by user`),b("Operation cancelled."),0}try{return me.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Ro(e,t.scope),me.info(`[${e}] Uninstalled successfully`),q("Plugin removed successfully"),0}catch(r){return me.error(`[${e}] Failed to uninstall: ${Y(r)}`),P(Y(r)),1}}async function pf(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Ni(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return me.debug(`[${e}] Already enabled, skipping`),b(`${r.name} is already enabled`),0;try{return me.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await $o(e,"enabled",t.scope),me.info(`[${e}] Enabled successfully`),q(`${r.name} enabled successfully`),0}catch(n){return me.error(`[${e}] Failed to enable: ${Y(n)}`),P(Y(n)),1}}async function mf(e,t={}){if(!await pe())return 1;me.debug(`[${e}] Looking up installed plugin`);let r=Ni(e,t.scope);if(!r)return me.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return me.debug(`[${e}] Already disabled, skipping`),b(`${r.name} is already disabled`),0;try{return me.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await $o(e,"disabled",t.scope),me.info(`[${e}] Disabled successfully`),q(`${r.name} disabled successfully`),0}catch(n){return me.error(`[${e}] Failed to disable: ${Y(n)}`),P(Y(n)),1}}async function ff(e,t,r){r.silent||b(`${t}Updating ${e}...`);try{let n=await yi(e,r);return r.silent?we({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):q(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Pr)return r.silent?we({status:"up_to_date",plugin:e,message:n.message}):b(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=Y(n);return r.silent?tt({status:"error",plugin:e,message:o}):P(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function dI(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;b(`
213
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function pI(e,t,r){try{let n=await Nn(e,r.source);Fe(t,n.version,r.force)?b(`Would update ${e}: v${t} \u2192 v${n.version}`):b(`${e} is already up to date (v${t})`);}catch(n){return P(Y(n)),1}return 0}function mI(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function fI(e,t,r){let n=t.get(e.name);return n?e.version&&Fe(e.version,n,r)?(b(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(b(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(b(`Skipping ${e.name}: not found in catalog`),false)}async function gI(e,t){try{let r=await Qt(t.source),n=mI(r),o=0;for(let s of e)fI(s,n,t.force)&&o++;o===0&&b("All plugins are up to date");}catch(r){return P(Y(r)),1}return 0}async function hI(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await ff(e[n].name,o,t);r.push(s);}return t.silent?we({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}:{}}))}):dI(r),r.some(n=>!n.success)?1:0}async function gf(e,t={}){if(!await pe())return 1;if(e){let o=Ni(e,t.scope);return o?t.dryRun?pI(e,o.version??"",t):(await ff(e,"",t)).success?0:1:(t.silent?tt({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):P(`Plugin "${e}" is not installed`),1)}let n=ie().filter(o=>o.marketplace===le);return n.length===0?(t.silent?we({status:"empty",message:"No plugins installed"}):b("No plugins installed"),0):t.dryRun?gI(n,t):hI(n,t)}F();R();var Yo=x("cli:bundle");function yI(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 wI(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
215
214
  Bundle: ${h(e)} (${t.length} artifacts)
216
- `);for(let o of t)process.stdout.write(`${zb(o)}
215
+ `);for(let o of t)process.stdout.write(`${yI(o)}
217
216
  `);process.stdout.write(`
218
217
  ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
219
218
 
220
- `);}async function cf(e){if(!e.trim())return P("Bundle name cannot be empty."),1;if(!await pe())return 1;qo.debug(`Fetching bundle "${e}"`);let r;try{r=await xi(e);}catch(a){return a instanceof zn||a instanceof Ho?(P(a.message),1):(P(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(qo.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Xb(r.title,n),o.length===0)return P("No artifacts available for installation in this bundle."),1;if(!await Ue(`Install ${o.length} artifact(s)? [Y/n] `))return qo.debug("Installation cancelled by user"),0;qo.debug(`Starting installation of ${o.length} artifact(s)`);let i=await pi(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(`
219
+ `);}async function hf(e){if(!e.trim())return P("Bundle name cannot be empty."),1;if(!await pe())return 1;Yo.debug(`Fetching bundle "${e}"`);let r;try{r=await bi(e);}catch(a){return a instanceof Xn||a instanceof Jo?(P(a.message),1):(P(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(Yo.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),wI(r.title,n),o.length===0)return P("No artifacts available for installation in this bundle."),1;if(!await Ie(`Install ${o.length} artifact(s)? [Y/n] `))return Yo.debug("Installation cancelled by user"),0;Yo.debug(`Starting installation of ${o.length} artifact(s)`);let i=await mi(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(`
221
220
  `),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
222
221
  `),a===l&&process.stdout.write(`
223
- `);}});if(qo.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(", ");P(`${i.failed} failed: ${h(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>h(l.name??l.flowId)).join(", ");I(`${i.skipped} unavailable: ${a}`);}return 0}Tr();B();$();var uf=x("marketplace");function Yb(e){return `claude plugin marketplace add ${e}`}async function df(e,t){if(!await pe())return 1;let r;try{r=Zs(e);}catch(s){let i=q(s);return t.silent?tt({status:"error",source:e,message:i}):P(i),1}uf.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Yb(r);if(!t.force){let s=h(r),i=h(n);if(!await Ue(`Add marketplace "${s}"?
222
+ `);}});if(Yo.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&q(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");P(`${i.failed} failed: ${h(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>h(l.name??l.flowId)).join(", ");b(`${i.skipped} unavailable: ${a}`);}return 0}Tr();F();R();var yf=x("marketplace");function xI(e){return `claude plugin marketplace add ${e}`}async function wf(e,t){if(!await pe())return 1;let r;try{r=Qs(e);}catch(s){let i=Y(s);return t.silent?tt({status:"error",source:e,message:i}):P(i),1}yf.debug(`[marketplace] Adding marketplace source: ${r}`);let n=xI(r);if(!t.force){let s=h(r),i=h(n);if(!await Ie(`Add marketplace "${s}"?
224
223
  This will run: ${i}
225
- [y/N] `))return uf.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:Xl({text:`Adding marketplace "${h(r)}"...`}).start();try{let s=await Ae(n);return o?.stop(),s.exitCode!==0?(t.silent?tt({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(P(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&I(`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&&I(s.stdout)),0)}catch(s){o?.stop();let i=q(s);return t.silent?tt({status:"error",source:r,message:i}):P(`Failed to add marketplace "${r}": ${i}`),1}}Ie();B();async function tI(){return await Y()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function rI(){let e=Date.now();try{await Yt();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 nI(){return await hr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function oI(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function sI(){let e=Oi();if(e.length!==0){process.stdout.write(`
224
+ [y/N] `))return yf.debug("[marketplace] Operation cancelled by user"),b("Operation cancelled."),0}let o=t.silent?void 0:Ql({text:`Adding marketplace "${h(r)}"...`}).start();try{let s=await Re(n);return o?.stop(),s.exitCode!==0?(t.silent?tt({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(P(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&b(`stdout: ${s.stdout}`)),1):(t.silent?we({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(q(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&b(s.stdout)),0)}catch(s){o?.stop();let i=Y(s);return t.silent?tt({status:"error",source:r,message:i}):P(`Failed to add marketplace "${r}": ${i}`),1}}Ee();F();async function EI(){return await Z()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function PI(){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 TI(){return await hr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function CI(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function kI(){let e=Ui();if(e.length!==0){process.stdout.write(`
226
225
  `+T.bold(` Marketplace Auto-Update
227
226
 
228
- `));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=h(t.name).padEnd(20),o=h(ef(t));process.stdout.write(` ${r} ${n} ${T.dim(o)}
229
- `);}}}function iI(){process.stdout.write(`
227
+ `));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=h(t.name).padEnd(20),o=h(cf(t));process.stdout.write(` ${r} ${n} ${T.dim(o)}
228
+ `);}}}function AI(){process.stdout.write(`
230
229
  `+T.bold(` FlowSetup CLI \u2014 Auto-Update Fix
231
230
 
232
- `));let e=tf();for(let t of e.fixed)process.stdout.write(` ${T.green("[FIXED]")} ${h(t)} \u2014 autoUpdate: true set
231
+ `));let e=uf();for(let t of e.fixed)process.stdout.write(` ${T.green("[FIXED]")} ${h(t)} \u2014 autoUpdate: true set
233
232
  `);for(let{name:t,reason:r}of e.skipped)process.stdout.write(` ${T.dim("[SKIP] ")} ${h(t)} \u2014 ${h(r)}
234
233
  `);return process.stdout.write(`
235
234
  `),e.fixed.length===0?process.stdout.write(T.dim(` Nothing to fix \u2014 all set.
236
235
 
237
236
  `)):process.stdout.write(T.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
238
237
 
239
- `)),0}async function pf(e={}){if(e.fix)return iI();process.stdout.write(`
238
+ `)),0}async function Sf(e={}){if(e.fix)return AI();process.stdout.write(`
240
239
  `+T.bold(` FlowSetup CLI Diagnostics
241
240
 
242
- `));let t=[{name:"Credentials",fn:tI},{name:"Prompt Manager",fn:rI},{name:"Valid Token",fn:nI},{name:"Claude Code",fn:oI}],r=true;for(let n of t){let o=await n.fn(),s="",i=T.green;o.passed?s=T.green("[OK] "):(s=T.red("[FAIL]"),i=T.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${h(o.message)}`;process.stdout.write(a+`
243
- `);}return sI(),process.stdout.write(`
241
+ `));let t=[{name:"Credentials",fn:EI},{name:"Prompt Manager",fn:PI},{name:"Valid Token",fn:TI},{name:"Claude Code",fn:CI}],r=true;for(let n of t){let o=await n.fn(),s="",i=T.green;o.passed?s=T.green("[OK] "):(s=T.red("[FAIL]"),i=T.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${h(o.message)}`;process.stdout.write(a+`
242
+ `);}return kI(),process.stdout.write(`
244
243
  `),r?(process.stdout.write(T.green(` \u2713 All checks passed!
245
244
 
246
245
  `)),0):(process.stdout.write(T.red(` \u2717 Some checks failed \u2014 verify your configuration
247
246
 
248
- `)),1)}Ie();Kr();j();async function mf(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(!Jt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await nd.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}In();Is();Ie();B();$();var lI=x("commands:usage"),Ni=20,ff="EMAIL",gf="MONTHLY CONSUMPTION (USD)",hf="STATUS";function cI(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Ni),n=Ni-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function yf(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function uI(e){let t=e.toLowerCase(),r=h(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function dI(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 pI(e){try{let t=await xn();if(t?.email)return h(t.email);let r=bn(e);return h(r.email??"")}catch(t){return lI.debug(`JWT email decode failed: ${String(t)}`),""}}async function wf(e){if(!await pe())return 1;let r;try{r=await $t();}catch(g){return P(`Authentication error: ${q(g)}`),1}let n;try{n=await mf(r);}catch(g){return P(`Failed to fetch usage data: ${q(g)}`),1}if(e.json)return pr(n),0;let o=await pI(r)||h(n.user_id),s=yf(n.consumed_usd),i=yf(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(ff.length,o.length+2),c=Math.max(gf.length,Ni+2+l.length),d=` ${ff.padEnd(u)} ${gf.padEnd(c)} ${hf}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(hf.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${cI(n.percentage)} ${l.padEnd(c-Ni-2)}`,y=` ${T.dim("Resets")} ${dI(n.renewal_date)}`;return process.stdout.write(`
247
+ `)),1)}Ee();Vr();j();async function xf(e){let t=await Z(),r=At("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Wt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await pd.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}vn();vs();Ee();F();R();var $I=x("commands:usage"),Fi=20,bf="EMAIL",If="MONTHLY CONSUMPTION (USD)",vf="STATUS";function LI(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Fi),n=Fi-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function Ef(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function MI(e){let t=e.toLowerCase(),r=h(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function _I(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 DI(e){try{let t=await bn();if(t?.email)return h(t.email);let r=In(e);return h(r.email??"")}catch(t){return $I.debug(`JWT email decode failed: ${String(t)}`),""}}async function Pf(e){if(!await pe())return 1;let r;try{r=await Rt();}catch(g){return P(`Authentication error: ${Y(g)}`),1}let n;try{n=await xf(r);}catch(g){return P(`Failed to fetch usage data: ${Y(g)}`),1}if(e.json)return pr(n),0;let o=await DI(r)||h(n.user_id),s=Ef(n.consumed_usd),i=Ef(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(bf.length,o.length+2),c=Math.max(If.length,Fi+2+l.length),d=` ${bf.padEnd(u)} ${If.padEnd(c)} ${vf}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(vf.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${LI(n.percentage)} ${l.padEnd(c-Fi-2)}`,y=` ${T.dim("Resets")} ${_I(n.renewal_date)}`;return process.stdout.write(`
249
248
  `),process.stdout.write(T.dim(d)+`
250
249
  `),process.stdout.write(T.dim(m)+`
251
- `),process.stdout.write(` ${p} ${f} ${uI(n.status)}
250
+ `),process.stdout.write(` ${p} ${f} ${MI(n.status)}
252
251
  `),process.stdout.write(y+`
253
252
  `),process.stdout.write(`
254
- `),0}var gI=["github.com","www.github.com"],hI=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,yI=/^([^@]+)@(.+)$/;function wI(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function ql(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 SI(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=ql(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=ql(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Bi(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(wI(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:")&&gI.includes(r.hostname))return SI(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(hI);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(yI);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=ql(m));}return d}}return {type:"git",url:t}}function Fi(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 Sf(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 If(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function EI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Yl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Yo(e){try{let t=await readFile(e,"utf-8"),{data:r}=Sf(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 vf(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Yl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Zl.has(a.name)).map(a=>vf(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Vi(e,t){let r=[],n=new Set;if(t&&!EI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Yl(o)){let i=await Yo(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 Yl(u)){let c=await Yo(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await vf(o);for(let a of i){let l=await Yo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Ef(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}He();var kf=1,$I={retries:5,minTimeout:50};async function Af(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bh.lock(e+".lock",{realpath:false,retries:$I});try{return await t()}finally{await r();}}function Pf(){return {version:kf,skills:{}}}async function Hi(e){let t=so(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<kf?Pf():n}catch{return Pf()}}function RI(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function $f(e,t){let r=so(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:RI(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
255
- `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Rf(e,t,r){let n=so(r);await Af(n,async()=>{let o=await Hi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await $f(o,r);});}async function Lf(e,t){let r=so(t);await Af(r,async()=>{let n=await Hi(t);e in n.skills&&(delete n.skills[e],await $f(n,t));});}He();$();var Mf=x("skillInstaller");async function BI(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Z().interfaceType});}catch(o){Mf.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function FI(e,t){try{await v(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){Mf.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function jI(e,t){await cp$1(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 KI(e,t,r){let n=at(e.name),o=Br(t),s=join(o,n);if(!If(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 jI(e.path,s);let a=Fi(r)??r.url;return await Rf(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 _f(e,t){let r=Bi(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 Vi(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Ef(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await KI(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await BI(c.name,t.scope,u,p):await FI(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(()=>{});}}He();B();$();var WI=x("skills");async function zI(e){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Z().interfaceType});}catch(t){WI.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function XI(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 qI(e){let t=Bi(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return P("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${h(e)}...`),r=await Ot(t.url,t.ref),n=r;let o=await Vi(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let i=Fi(t)??h(e);I(`Found ${o.length} skill(s) in ${i}:
253
+ `),0}var NI=["github.com","www.github.com"],BI=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,FI=/^([^@]+)@(.+)$/;function jI(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function ec(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 KI(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=ec(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=ec(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ji(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(jI(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:")&&NI.includes(r.hostname))return KI(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(BI);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(FI);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=ec(m));}return d}}return {type:"git",url:t}}function Ki(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 Tf(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 rc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Af(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function WI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function tc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Zo(e){try{let t=await readFile(e,"utf-8"),{data:r}=Tf(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 Rf(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([tc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!rc.has(a.name)).map(a=>Rf(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ji(e,t){let r=[],n=new Set;if(t&&!WI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await tc(o)){let i=await Zo(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 tc(u)){let c=await Zo(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Rf(o);for(let a of i){let l=await Zo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function $f(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}He();var Df=1,QI={retries:5,minTimeout:50};async function Of(e,t){mkdirSync(dirname(e),{recursive:true});let r=await ly.lock(e+".lock",{realpath:false,retries:QI});try{return await t()}finally{await r();}}function Lf(){return {version:Df,skills:{}}}async function Gi(e){let t=io(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Df?Lf():n}catch{return Lf()}}function ev(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Uf(e,t){let r=io(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:ev(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
254
+ `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Nf(e,t,r){let n=io(r);await Of(n,async()=>{let o=await Gi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Uf(o,r);});}async function Bf(e,t){let r=io(t);await Of(r,async()=>{let n=await Gi(t);e in n.skills&&(delete n.skills[e],await Uf(n,t));});}He();R();var Ff=x("skillInstaller");async function lv(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Q().interfaceType});}catch(o){Ff.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function cv(e,t){try{await v(I.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:Q().interfaceType});}catch(r){Ff.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function uv(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(rc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function dv(e,t,r){let n=at(e.name),o=Fr(t),s=join(o,n);if(!Af(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm$1(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await uv(e.path,s);let a=Ki(r)??r.url;return await Nf(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 jf(e,t){let r=ji(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 Ji(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?$f(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await dv(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await lv(c.name,t.scope,u,p):await cv(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(()=>{});}}He();F();R();var hv=x("skills");async function yv(e){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Q().interfaceType});}catch(t){hv.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function wv(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 Sv(e){let t=ji(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return P("Invalid local path."),1;n=t.localPath;}else b(`Fetching skills from ${h(e)}...`),r=await Ot(t.url,t.ref),n=r;let o=await Ji(n,t.subpath);if(o.length===0)return b("No skills found in this source."),0;let i=Ki(t)??h(e);b(`Found ${o.length} skill(s) in ${i}:
256
255
  `);for(let a of o){let l=h(a.name),u=h(a.description);process.stdout.write(` ${T.bold(l)} ${T.dim(u)}
257
256
  `);}return process.stdout.write(`
258
- `),0}catch(n){return n instanceof Ar?P(n.message):P(n instanceof Error?n.message:String(n)),1}finally{r&&await Ut(r).catch(()=>{});}}function YI(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 ${T.dim(`\u2192 ${o}/`)}`);}else P(`${n}: ${h(r.error??"unknown error")}`);}process.stdout.write(`
259
- `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${h(t)}`),e.failed>0&&P(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Of(e,t){if(t.list)return qI(e);let r=t.global?"global":"project";try{let n=await _f(e,{scope:r,skillFilter:t.skill,yes:t.yes});return YI(n),n.failed>0?1:0}catch(n){return n instanceof Ar?P(n.message):P(n instanceof Error?n.message:String(n)),1}}async function Uf(e){let t=Br(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 Yo(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 Nf(e){let t=e.global?"global":"project",r=await Uf(t),n=await Hi(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 pr(s),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
257
+ `),0}catch(n){return n instanceof Rr?P(n.message):P(n instanceof Error?n.message:String(n)),1}finally{r&&await Ut(r).catch(()=>{});}}function xv(e){for(let r of e.results){let n=h(r.skill);if(r.success){let o=relative(process.cwd(),r.path);q(`${n} installed ${T.dim(`\u2192 ${o}/`)}`);}else P(`${n}: ${h(r.error??"unknown error")}`);}process.stdout.write(`
258
+ `);let t=e.source;e.installed>0&&b(`Installed ${e.installed} of ${e.discovered} skill(s) from ${h(t)}`),e.failed>0&&P(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?b("No skills found in this source."):e.results.length===0&&e.discovered>0&&b(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Vf(e,t){if(t.list)return Sv(e);let r=t.global?"global":"project";try{let n=await jf(e,{scope:r,skillFilter:t.skill,yes:t.yes});return xv(n),n.failed>0?1:0}catch(n){return n instanceof Rr?P(n.message):P(n instanceof Error?n.message:String(n)),1}}async function Hf(e){let t=Fr(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 Zo(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 Jf(e){let t=e.global?"global":"project",r=await Hf(t),n=await Gi(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 pr(s),0}if(r.length===0)return b(`No skills installed (${t==="global"?"global":"project"} scope).`),0;b(`${t==="global"?"Global":"Project"} skills (${r.length}):
260
259
  `);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?T.dim(` (${i})`):"";process.stdout.write(` ${T.bold(a)}${c}
261
260
  `),process.stdout.write(` ${T.dim(u)}
262
261
 
263
- `);}return 0}async function Bf(e,t){let r=t.global?"global":"project";if(!e){let i=await Uf(r);if(i.length===0)return I("No skills installed."),0;I("Installed skills:");for(let a of i)process.stdout.write(` - ${h(a.name)}
262
+ `);}return 0}async function Gf(e,t){let r=t.global?"global":"project";if(!e){let i=await Hf(r);if(i.length===0)return b("No skills installed."),0;b("Installed skills:");for(let a of i)process.stdout.write(` - ${h(a.name)}
264
263
  `);return process.stdout.write(`
265
- `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=at(e),o=Br(r),s=join(o,n);try{await stat(s);}catch{return P(`Skill "${h(e)}" is not installed.`),1}if(!t.force&&!await XI(`Remove skill "${h(n)}"?`))return I("Cancelled."),0;try{return await rm(s,{recursive:!0,force:!0}),await Lf(n,r),await zI(n),te(`Skill "${h(n)}" removed.`),0}catch(i){return P(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}B();$();j();var Ji=x("transfer"),ec=1;function ZI(e){return e.marketplace&&e.marketplace!==le?`${e.name}@${e.marketplace}`:e.name}function QI(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&I(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),I(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Kf(e){let t=xe__default.resolve(e.output);try{let r=ie(),n={version:ec,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 Ji.error(`Export failed: ${n}`),P(`Failed to export plugins: ${n}`),1}}async function Vf(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 P(`Failed to read import file "${e}": ${q(a)}`),1}if(r.version!==ec)return P(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${ec}`),1;if(!Array.isArray(r.plugins))return P('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return I("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}]`;Ji.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Ji.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&I(`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));QI(n,a);}if(t.dryRun)return I("Dry-run mode: no plugins were installed"),0;if(n.length===0){I(`
266
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)P(` ${a.name}: ${a.error}`);return o.length>0?1:0}I(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=ZI(a);Ji.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await eo([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}I(`
267
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)P(` ${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 tv=x("moduleProxy");function rv(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=cl.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 Hf(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{tv.warn(`Failed to emit proxy executed event: ${String(s)}`);}),F(o);}async function Gf(e,t){let r=se.find(o=>o.alias===e);if(!r){P(`Unknown module alias: '${e}'`),F(1);return}if(!await Lt(r.binaryName)){P(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(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){P(`No supported installation method available for '${e}' on this platform.`),F(1);return}if(await rv("Would you like to install it now? [Y/n] ")){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await vr(r,"inline",s);if(!a.success){P(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),F(1);return}await Hf(r,t);}else I(`To install manually, run: flow modules install ${e}`),await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),F(1);return}await Hf(r,t);}B();var iv=promisify(execFile);async function av(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await iv(Wt(),["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 lv(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Fe(t,r)?"outdated":"installed"}async function tc(){let e=await Promise.all(se.map(async t=>{let[r,n]=await Promise.all([Lt(t.binaryName),av(t)]),s=nt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=lv(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return wn(["Name","Alias","Version","Status","Platform"],e),0}async function Xf(e){let t=se.find(i=>i.alias===e);if(!t)return P(`Unknown module alias: '${e}'`),1;let[r]=await qn([t]);if(r.alreadyInstalled){let i=nt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return I(`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"?P(`Module ${t.name} is not supported on ${process.platform}.${a}`):P(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Xl({text:`Installing ${t.name}...`}).start(),s;try{s=await vr(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):(P(s.error?.message??"Installation failed"),1)}async function Wf(e,t){let r=Xl({text:`Updating ${e.name}...`}).start(),n;try{n=await Os(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 qf(e){if(e!==null){let n=se.find(i=>i.alias===e);if(!n)return P(`Unknown module alias: '${e}'`),1;let o=nt(n.alias);return o?.installMethod?await Wf(n,o.installedVersion??"unknown")==="error"?1:0:(P(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=qr().filter(n=>n.installMethod!==null);if(t.length===0)return I("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 Wf(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var Yf="b10864926258503a01a6afc980d3f4216004ee41",Zf=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
264
+ `),b("Specify a skill name to remove: flow skills remove <name>"),1}let n=at(e),o=Fr(r),s=join(o,n);try{await stat(s);}catch{return P(`Skill "${h(e)}" is not installed.`),1}if(!t.force&&!await wv(`Remove skill "${h(n)}"?`))return b("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Bf(n,r),await yv(n),q(`Skill "${h(n)}" removed.`),0}catch(i){return P(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}F();R();j();var Wi=x("transfer"),oc=1;function bv(e){return e.marketplace&&e.marketplace!==le?`${e.name}@${e.marketplace}`:e.name}function Iv(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&b(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),b(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Xf(e){let t=be__default.resolve(e.output);try{let r=ie(),n={version:oc,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 ve__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),q(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=Y(r);return Wi.error(`Export failed: ${n}`),P(`Failed to export plugins: ${n}`),1}}async function qf(e,t={}){if(!await pe())return 1;let r;try{let a=ve__default.readFileSync(be__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return P(`Failed to read import file "${e}": ${Y(a)}`),1}if(r.version!==oc)return P(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${oc}`),1;if(!Array.isArray(r.plugins))return P('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return b("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}]`;Wi.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Wi.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&b(`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));Iv(n,a);}if(t.dryRun)return b("Dry-run mode: no plugins were installed"),0;if(n.length===0){b(`
265
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)P(` ${a.name}: ${a.error}`);return o.length>0?1:0}b(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=bv(a);Wi.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await to([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}b(`
266
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)P(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();F();function N(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}F();R();var Ev=x("moduleProxy");function Pv(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=ml.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 Yf(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(I.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{Ev.warn(`Failed to emit proxy executed event: ${String(s)}`);}),N(o);}async function Qf(e,t){let r=se.find(o=>o.alias===e);if(!r){P(`Unknown module alias: '${e}'`),N(1);return}if(!await Lt(r.binaryName)){P(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),N(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){P(`No supported installation method available for '${e}' on this platform.`),N(1);return}if(await Pv("Would you like to install it now? [Y/n] ")){await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await vr(r,"inline",s);if(!a.success){P(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),N(1);return}await Yf(r,t);}else b(`To install manually, run: flow modules install ${e}`),await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),N(1);return}await Yf(r,t);}F();var Av=promisify(execFile);async function Rv(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await Av(Xt(),["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 $v(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Fe(t,r)?"outdated":"installed"}async function sc(){let e=await Promise.all(se.map(async t=>{let[r,n]=await Promise.all([Lt(t.binaryName),Rv(t)]),s=nt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=$v(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Sn(["Name","Alias","Version","Status","Platform"],e),0}async function rg(e){let t=se.find(i=>i.alias===e);if(!t)return P(`Unknown module alias: '${e}'`),1;let[r]=await Yn([t]);if(r.alreadyInstalled){let i=nt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return b(`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"?P(`Module ${t.name} is not supported on ${process.platform}.${a}`):P(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Ql({text:`Installing ${t.name}...`}).start(),s;try{s=await vr(t,"on_demand",n);}finally{o.stop();}return s.success?(q(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(P(s.error?.message??"Installation failed"),1)}async function eg(e,t){let r=Ql({text:`Updating ${e.name}...`}).start(),n;try{n=await Us(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 ng(e){if(e!==null){let n=se.find(i=>i.alias===e);if(!n)return P(`Unknown module alias: '${e}'`),1;let o=nt(n.alias);return o?.installMethod?await eg(n,o.installedVersion??"unknown")==="error"?1:0:(P(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Yr().filter(n=>n.installMethod!==null);if(t.length===0)return b("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 eg(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var og="b10864926258503a01a6afc980d3f4216004ee41",sg=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
268
267
  title: "0-current-state \u2014 Index"
269
268
  type: index
270
269
  domain: platform
@@ -526,23 +525,27 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
526
525
  **6. Source code never in monitored folders.**
527
526
  If you create a folder with app or script source code, keep it out of the 5 numbered folders
528
527
  entirely (e.g. \`prototypes/\`).
529
- `},{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 Qf=".flow-harness-lock";function eg(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 tg(e,t){return e.files?.[t]?.sha256}function rg(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)+`
530
- `,"utf8");}B();function wv(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Sv(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function og(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??bv,i=join(t,Qf),a=eg(i),l=[],u=Sv(),c={};for(let m of Zf){let p=join(t,m.path),f=await xv({dstPath:p,template:m,existingLockHash:tg(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&&rg(i,a,c,Yf);let d=u.divergent>0||u.declined>0;return {files:l,counts:u,hasUnresolved:d}}async function xv(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=wv(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}:(I(`divergent, kept local (customized): ${r.path}`),{status:"divergent",write:false,recordHash:a})}async function bv(e){return Ue(` Overwrite ${e} with the updated template? [y/N] `)}B();$();Ie();Kr();$();var rc=x("lib:otelMetrics"),vv="flow-plugins-cli",Ev="1.0.0",Pv=5e3;function Tv(){return At("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function Cv(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 kv(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:vv,version:Ev},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>Cv(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function nc(e,t={}){try{let[r,n]=await Promise.all([xn(),Y()]),o=r?.email,s=n?.tenant;if(!o||!s){rc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=kv(e,t);await nd.post(Tv(),{json:i,timeout:Pv,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),rc.debug(`OTel metric sent: ${e}`);}catch(r){rc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var oc=x("cli:init");function Av(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 $v(e,t,r,n){v(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=>{oc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),nc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,files_updated:e.clean,exit_code:r}).catch(()=>{});}function Rv(e,t){v(b.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{oc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),nc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function sg(e){oc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let t=Date.now(),r;try{r=await og({targetDir:e.path,dryRun:e.dryRun,force:e.force});}catch(c){throw Rv(c instanceof Error?c.message:String(c),Date.now()-t),c}let n=r.hasUnresolved?2:0;if($v(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(`
531
- `);for(let c of r.files)process.stdout.write(` ${o}${Av(c.status)}: ${c.path}
528
+ `},{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 ig=".flow-harness-lock";function ag(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 lg(e,t){return e.files?.[t]?.sha256}function cg(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)+`
529
+ `,"utf8");}F();function jv(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Kv(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function dg(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??Hv,i=join(t,ig),a=ag(i),l=[],u=Kv(),c={};for(let m of sg){let p=join(t,m.path),f=await Vv({dstPath:p,template:m,existingLockHash:lg(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&&cg(i,a,c,og);let d=u.divergent>0||u.declined>0;return {files:l,counts:u,hasUnresolved:d}}async function Vv(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=jv(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}:(b(`divergent, kept local (customized): ${r.path}`),{status:"divergent",write:false,recordHash:a})}async function Hv(e){return Ie(` Overwrite ${e} with the updated template? [y/N] `)}F();R();Ee();Vr();R();var ic=x("lib:otelMetrics"),Gv="flow-plugins-cli",Wv="1.0.0",zv=5e3;function Xv(){return At("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function qv(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 Yv(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:Gv,version:Wv},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>qv(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function ac(e,t={}){try{let[r,n]=await Promise.all([bn(),Z()]),o=r?.email,s=n?.tenant;if(!o||!s){ic.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=Yv(e,t);await pd.post(Xv(),{json:i,timeout:zv,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),ic.debug(`OTel metric sent: ${e}`);}catch(r){ic.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var lc=x("cli:init");function Zv(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 Qv(e,t,r,n){v(I.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=>{lc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),ac("flow_cli.strategy_init",{dry_run:t,files_new:e.new,files_updated:e.clean,exit_code:r}).catch(()=>{});}function eE(e,t){v(I.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{lc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),ac("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function pg(e){lc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let t=Date.now(),r;try{r=await dg({targetDir:e.path,dryRun:e.dryRun,force:e.force});}catch(c){throw eE(c instanceof Error?c.message:String(c),Date.now()-t),c}let n=r.hasUnresolved?2:0;if(Qv(r.counts,!!e.dryRun,n,Date.now()-t),e.json)return we({dryRun:!!e.dryRun,counts:r.counts,files:r.files,exitCode:n}),n;let o=e.dryRun?"[dry-run] ":"";process.stdout.write(`
530
+ `);for(let c of r.files)process.stdout.write(` ${o}${Zv(c.status)}: ${c.path}
532
531
  `);process.stdout.write(`
533
- `);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&&I("Some files were kept as-is because they differ from what this command last wrote. Re-run with --force to overwrite them."),u>0&&I("Some updates were declined or skipped (no TTY). Re-run with --force to apply them."),n!==0&&P("flow setup strategy finished with unresolved files \u2014 see above."),n}B();j();var ro=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Lv=["local","project","user"];function Mv(){I(`The following ${ro.length} runbook bundles will be installed:`);for(let e of ro)process.stdout.write(` - ${e}
534
- `);}function _v(e){let t=De().plugins;for(let[r,n]of Object.entries(t))if((r===e||r.startsWith(`${e}@`))&&n[0])return n[0]}function ig(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function Dv(e,t){return I(`${e} is already installed ${ig(t)}.`),Ue(" Install here too? This won't duplicate any files, but the plugin will end up enabled in both places, and the central install record will only remember this newest one. [y/N] ")}async function Ov(){return Td(" Install scope:",Lv.map(e=>({value:e,label:dr[e].actionLabel,description:dr[e].description})))}async function ag(e={}){let t=e.isInteractive??!!process.stdin.isTTY;e.silent||Mv();let r=e.scope;if(!r&&!e.silent&&t)try{r=await Ov();}catch(o){if(o instanceof Error&&o.message==="SIGINT")return process.stdout.write(`
535
- `),130;throw o}let n=[];for(let o=0;o<ro.length;o++){let s=ro[o],i=`[${o+1}/${ro.length}] `,a=e.force??false;if(!a){let l=_v(s);if(l){if(e.silent||!t){e.silent||I(`${i}Skipping ${s} \u2014 already installed ${ig(l)}. Re-run with --force to install here too.`);continue}try{if(!await Dv(s,l)){I(`${i}Skipped ${s}.`);continue}a=!0;}catch(u){if(u instanceof Error&&u.message==="SIGINT")return process.stdout.write(`
536
- `),130;throw u}}}e.silent||I(`${i}Installing ${s}...`),n.push(await eo([s],{scope:r,silent:e.silent,force:a}));}return n.some(o=>o!==0)?1:0}function lg(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",`
532
+ `);let{new:s,unchanged:i,clean:a,divergent:l,declined:u}=r.counts;return q(`${s} new, ${i} unchanged, ${a} updated, ${l} kept (customized)`+(u>0?`, ${u} pending confirmation`:"")),l>0&&b("Some files were kept as-is because they differ from what this command last wrote. Re-run with --force to overwrite them."),u>0&&b("Some updates were declined or skipped (no TTY). Re-run with --force to apply them."),n!==0&&P("flow setup strategy finished with unresolved files \u2014 see above."),n}F();j();var no=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var uc="repos.yaml",oE="projects",sE="projects-ref";function mg(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).map(t=>({name:String(t.name??""),remote:String(t.remote??""),group:t.group!==void 0?String(t.group):void 0})).filter(t=>t.name&&t.remote):[]}function yg(e){let t=join(e,uc);if(!existsSync(t))return null;let r=parse(readFileSync(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return null;let n=r.workspace??{};return {workspace:{repos_dir:String(n.repos_dir??oE),refs_dir:String(n.refs_dir??sE)},repos:mg(r.repos),references:mg(r.references)}}function wg(e,t){let r=join(e,uc);writeFileSync(r,stringify(t),"utf8");}function Sg(e){let t=join(e,".gitignore"),r=uc;if(!existsSync(t)){writeFileSync(t,`${r}
533
+ `,"utf8");return}readFileSync(t,"utf8").split(`
534
+ `).some(s=>s.trim()===r)||appendFileSync(t,`${r}
535
+ `,"utf8");}var xg="projects",bg="projects-ref";function iE(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}async function aE(){let e=await Ar(" Repo name (ENTER to finish): ");if(!e)return null;let t=await Ar(` Group/category for '${e}' (optional, default: general): `),r=await Ar(` Remote (URL) for '${e}' \u2014 SSH or HTTPS: `);if(!r)return null;let n=iE(r),o=await Ie(` Is '${e}' a reference/read-only repo? [y/N] `);return {entry:{name:e,remote:n,group:t||"general"},isReference:o}}async function Ig(){if(!await Ie("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Ar(` Folder for work repos (default: ${xg}): `),r=await Ar(` Folder for reference repos (default: ${bg}): `),n=[],o=[];for(;;){let s=await aE();if(!s)break;s.isReference?o.push(s.entry):n.push(s.entry);}return n.length===0&&o.length===0?null:{workspace:{repos_dir:t||xg,refs_dir:r||bg},repos:n,references:o}}R();var Eg=x("workspace:repos"),Tg=6e4;async function uE(e){try{return (await simpleGit(e).status()).current}catch{return null}}function Cg(){let{HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n}=process.env;return {HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n,GIT_TERMINAL_PROMPT:"0"}}async function dE(e){await simpleGit(e,{timeout:{block:Tg}}).env(Cg()).pull(["--ff-only"]);}async function pE(e,t){await simpleGit({timeout:{block:Tg}}).env(Cg()).clone(e,t);}async function pc(e,t,r){let n=join(t,e.name),o=join(n,".git");if(existsSync(o)){let s=await uE(n);if(s==="main"||s==="master")try{return await dE(n),{name:e.name,kind:r,outcome:"updated"}}catch(i){return Eg.warn(`[${e.name}] pull failed (branch diverged?): ${String(i)}`),{name:e.name,kind:r,outcome:"skipped"}}return {name:e.name,kind:r,outcome:"skipped"}}try{return mkdirSync(t,{recursive:!0}),await pE(e.remote,n),{name:e.name,kind:r,outcome:"cloned"}}catch(s){let i=s instanceof Error?s.message:String(s);return Eg.error(`[${e.name}] clone failed: ${i}`),{name:e.name,kind:r,outcome:"failed",error:i}}}function zi(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}async function kg(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=yg(t);if(!n){if(!r)return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true};let d=await Ig();if(!d)return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true};wg(t,d),Sg(t),n=d;}let o=join(t,n.workspace.repos_dir),s=join(t,n.workspace.refs_dir),i=[];for(let d of n.repos)i.push(await pc(d,o,"repo"));for(let d of n.references)i.push(await pc(d,s,"reference"));let a=new Set(n.repos.map(d=>d.name)),l=new Set(n.references.map(d=>d.name)),u=[...zi(o,a),...zi(s,l)],c=0;if(e.prune&&u.length>0)for(let d of [o,s]){let m=zi(d,d===o?a:l);for(let p of m)rmSync(join(d,p),{recursive:true,force:true}),c++;}return {repos:i,orphans:e.prune?[]:u,prunedCount:c,skippedNoManifest:false}}R();var fE=["local","project","user"];function gE(){b(`The following ${no.length} runbook bundles will be installed:`);for(let e of no)process.stdout.write(` - ${e}
536
+ `);}function hE(e){let t=Oe().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function Xi(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function yE(e,t,r){return b(`${e} is already installed ${Xi(r)}.`),Ie(` Move it to ${Gt[t].actionLabel} instead? This uninstalls it from ${Xi(r)} first. [y/N] `)}async function wE(){return _d(" Install scope:",fE.map(e=>({value:e,label:Gt[e].actionLabel,description:Gt[e].description})))}async function Ag(e={}){let t=e.isInteractive??!!process.stdin.isTTY;e.silent||gE();let r=e.scope;if(!r&&!e.silent&&t)try{r=await wE();}catch(o){if(o instanceof Error&&o.message==="SIGINT")return process.stdout.write(`
537
+ `),130;throw o}let n=[];for(let o=0;o<no.length;o++){let s=no[o],i=`[${o+1}/${no.length}] `,a=e.force??false;if(!a){let l=hE(s);if(l){if(e.silent||!t){e.silent||b(`${i}Skipping ${s} \u2014 already installed ${Xi(l)}. Re-run with --force to install here too.`);continue}try{if(!await yE(s,r,l)){b(`${i}Skipped ${s}.`);continue}let c=await Bi(s,{force:!0,scope:l.scope});if(c!==0){b(`${i}Could not remove ${s} from ${Xi(l)} \u2014 skipping rather than leaving it in an inconsistent state.`),n.push(c);continue}}catch(u){if(u instanceof Error&&u.message==="SIGINT")return process.stdout.write(`
538
+ `),130;throw u}}}e.silent||b(`${i}Installing ${s}...`),n.push(await to([s],{scope:r,silent:e.silent,force:a}));}return n.some(o=>o!==0)?1:0}var SE=x("cli:setup-workspace");function xE(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}async function Rg(e={}){SE.debug(`Running flow setup workspace: ${JSON.stringify(e)}`);let t=await kg({targetDir:e.path,prune:e.prune});if(e.json)return we({repos:t.repos,orphans:t.orphans,prunedCount:t.prunedCount,skippedNoManifest:t.skippedNoManifest}),t.repos.some(i=>i.outcome==="failed")?1:0;if(t.skippedNoManifest)return b("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;for(let i of t.repos)process.stdout.write(` ${i.name}: ${xE(i.outcome)}
539
+ `);let r=t.repos.filter(i=>i.outcome==="cloned").length,n=t.repos.filter(i=>i.outcome==="updated").length,o=t.repos.filter(i=>i.outcome==="skipped").length,s=t.repos.filter(i=>i.outcome==="failed").length;return q(`${r} cloned, ${n} updated, ${o} skipped`+(s>0?`, ${s} failed`:"")+(t.prunedCount>0?`, ${t.prunedCount} pruned`:"")),t.orphans.length>0&&b(`Orphan director${t.orphans.length===1?"y":"ies"} not in repos.yaml: ${t.orphans.join(", ")}. Re-run with --prune to remove.`),s>0?1:0}function $g(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",`
537
540
  Without arguments, opens the interactive interface (TUI).
538
541
  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",`
539
542
  Examples:
540
- $ flow setup init`).action(async()=>{let c=await zl();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",`
543
+ $ flow setup init`).action(async()=>{let c=await Zl();N(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",`
541
544
  Examples:
542
545
  $ flow setup strategy
543
546
  $ flow setup strategy --dry-run
544
547
  $ flow setup strategy --force
545
- $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await sg({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path});F(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).addHelpText("after",`
548
+ $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await pg({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path});N(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).addHelpText("after",`
546
549
  Examples:
547
550
  $ flow setup harness
548
551
  $ flow setup harness --scope project
@@ -550,14 +553,19 @@ Examples:
550
553
 
551
554
  Without --scope and with an interactive terminal, prompts once for the scope
552
555
  (local/project/user) before installing all 7 bundles. A bundle already
553
- installed elsewhere (any scope, any project) is skipped with a confirmation
554
- prompt unless --force is passed.`).action(async c=>{let d=await ag({scope:c.scope,silent:c.silent,force:c.force});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",`
556
+ installed elsewhere (any scope, any project) prompts to move it here instead
557
+ (uninstall there, install here) unless --force is passed, which installs
558
+ here too without asking, leaving the bundle enabled in both places.`).action(async c=>{let d=await Ag({scope:c.scope,silent:c.silent,force:c.force});N(d);}),r.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
559
+ Examples:
560
+ $ flow setup workspace
561
+ $ flow setup workspace --prune
562
+ $ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await Rg({path:c.path,prune:c.prune,json:c.json});N(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",`
555
563
  Examples:
556
564
  $ flow plugin list
557
565
  $ flow plugin list --available
558
566
  $ flow plugin list --outdated
559
567
  $ flow plugin list --json
560
- $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await rf(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",`
568
+ $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await df(c);N(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",`
561
569
  Examples:
562
570
  $ flow plugin install flow-adr-writer
563
571
  $ flow plugin install flow-adr-writer --scope project
@@ -566,11 +574,11 @@ Examples:
566
574
  $ flow plugin install flow-adr-writer --silent
567
575
  $ flow plugin install superpowers@claude-plugins-official
568
576
  $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
569
- $ flow plugin install runbook-design --source flow-harness`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){P("No valid plugin names provided"),F(1);return}Je("cli",{verbose:d.verbose,silent:d.silent});let p=await eo(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",`
577
+ $ flow plugin install runbook-design --source flow-harness`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){P("No valid plugin names provided"),N(1);return}Je("cli",{verbose:d.verbose,silent:d.silent});let p=await to(m,d);N(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",`
570
578
  Examples:
571
579
  $ flow plugin uninstall flow-adr-writer
572
580
  $ flow plugin uninstall flow-adr-writer --scope project
573
- $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await nf(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",`
581
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await Bi(c,d);N(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",`
574
582
  Examples:
575
583
  $ flow plugin update flow-adr-writer
576
584
  $ flow plugin update flow-adr-writer --scope project
@@ -579,79 +587,79 @@ Examples:
579
587
  $ flow plugin update flow-adr-writer --verbose
580
588
  $ flow plugin update flow-adr-writer --silent
581
589
  $ flow plugin update
582
- $ flow plugin update --dry-run`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await lf(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",`
590
+ $ flow plugin update --dry-run`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await gf(c??null,d);N(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",`
583
591
  Examples:
584
592
  $ flow plugin enable flow-adr-writer
585
- $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await of(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",`
593
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await pf(c,d);N(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",`
586
594
  Examples:
587
595
  $ flow plugin disable flow-adr-writer
588
- $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await sf(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",`
596
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await mf(c,d);N(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
589
597
  Examples:
590
598
  $ flow plugin export
591
- $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Kf(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",`
599
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Xf(c);N(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",`
592
600
  Examples:
593
601
  $ flow plugin import flow-plugins.json
594
602
  $ flow plugin import flow-plugins.json --scope user
595
603
  $ flow plugin import flow-plugins.json --force
596
604
  $ flow plugin import flow-plugins.json --dry-run
597
- $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Vf(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",`
605
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await qf(c,d);N(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",`
598
606
  Examples:
599
607
  $ flow plugin marketplace add anthropics/claude-code
600
608
  $ flow plugin marketplace add https://github.com/owner/repo
601
609
  $ flow plugin marketplace add anthropics/claude-code --force
602
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await df(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",`
610
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await wf(c,d);N(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",`
603
611
  Examples:
604
612
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
605
613
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
606
614
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
607
- $ 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 kp(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",`
615
+ $ 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 Op(c,d,m);N(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",`
608
616
  Examples:
609
617
  $ flow mcp remove notion
610
618
  $ flow mcp remove notion --scope project
611
- $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await Ap(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",`
619
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await Up(c,d);N(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",`
612
620
  Examples:
613
621
  $ flow auth login
614
622
  $ flow auth login --jwt <token>
615
623
  $ flow auth login --jwt <token> --starter-kit dev
616
624
  $ flow auth login --jwt <token> --custom-email name@example.com
617
- $ flow auth login --verbose`).action(async c=>{Je("cli",{verbose:c.verbose});let d=await zl(c);F(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
625
+ $ flow auth login --verbose`).action(async c=>{Je("cli",{verbose:c.verbose});let d=await Zl(c);N(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
618
626
  Examples:
619
627
  $ flow auth logout
620
- $ flow auth logout --force`).action(async c=>{let d=await Ym(c.force);F(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
628
+ $ flow auth logout --force`).action(async c=>{let d=await sf(c.force);N(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
621
629
  Examples:
622
- $ 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",`
630
+ $ flow auth status`).action(async()=>{let c=await af();N(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",`
623
631
  Examples:
624
632
  $ flow skills add vercel-labs/agent-skills
625
633
  $ flow skills add owner/repo -g
626
634
  $ flow skills add owner/repo --skill pr-review commit
627
635
  $ flow skills add ./local/skills -y
628
- $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Of(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",`
636
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Vf(c,d);N(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
629
637
  Examples:
630
638
  $ flow skills list
631
639
  $ flow skills list -g
632
- $ flow skills list --json`).action(async c=>{let d=await Nf(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",`
640
+ $ flow skills list --json`).action(async c=>{let d=await Jf(c);N(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",`
633
641
  Examples:
634
642
  $ flow skills remove pr-review
635
- $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Bf(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",`
643
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Gf(c,d);N(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",`
636
644
  Examples:
637
645
  $ flow bundle install "My React Kit"
638
646
  $ flow bundle install "Squad Setup Bundle"
639
- $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Je("cli",{verbose:d.verbose});let m=await cf(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",`
647
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Je("cli",{verbose:d.verbose});let m=await hf(c);N(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",`
640
648
  Examples:
641
649
  $ flow health
642
- $ flow health --fix`).action(async c=>{let d=await pf(c);F(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
650
+ $ flow health --fix`).action(async c=>{let d=await Sf(c);N(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
643
651
  Examples:
644
652
  $ flow usage
645
- $ flow usage --json`).action(async c=>{let d=await wf(c);F(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await tc();F(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
653
+ $ flow usage --json`).action(async c=>{let d=await Pf(c);N(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await sc();N(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
646
654
  Examples:
647
- $ flow modules list`).action(async()=>{let c=await tc();F(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
655
+ $ flow modules list`).action(async()=>{let c=await sc();N(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
648
656
  Examples:
649
657
  $ flow modules install metrics
650
- $ flow modules install dashboard`).action(async c=>{let d=await Xf(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",`
658
+ $ flow modules install dashboard`).action(async c=>{let d=await rg(c);N(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",`
651
659
  Examples:
652
660
  $ flow modules update
653
- $ flow modules update metrics`).action(async c=>{let d=await qf(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 Gf(c.alias,d);});return t.hook("preAction",()=>{ki();}),t}$();function Bv(){return xe__default.join(Le__default.homedir(),".claude","settings.json")}function ug(){let e=Bv();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 Jv=x("updateChecker"),Gv=promisify(execFile),Wv=1440*60*1e3,dg=3e4;function zv(){let e=process.env.FLOW_HOME??xe__default.join(Le__default.homedir(),".flow");return xe__default.join(e,"update.lock")}async function pg(e){try{let{stdout:t}=await Gv(Wt(),["view",e,"version"],{timeout:dg,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Xv(e){let t=new AbortController,r=setTimeout(()=>t.abort(),dg);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 qv(e){return e.versionCheck.type==="npm-registry"?pg(e.versionCheck.package):Xv(e.versionCheck.repo)}async function Yv(){let e=await pg("@ciandt-flow/cli");return e&&Fe(ue,e)?(_i({currentVersion:ue,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function Zv(){let e=qr().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<Wv)return;let s=await qv(r);try{await yt({...t,lastChecked:new Date().toISOString()});}catch(i){Jv.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Fe(t.installedVersion,s)&&Os(r,"background").catch(()=>{});}));}async function ic(){let e=ug();if(e===false)return;let t=zv();be__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=null;try{r=await Bh.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await Yv().catch(()=>null);n&&process.stdout.write(`
661
+ $ flow modules update metrics`).action(async c=>{let d=await ng(c??null);N(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 Qf(c.alias,d);});return t.hook("preAction",()=>{Ai();}),t}R();function vE(){return be__default.join(Me__default.homedir(),".claude","settings.json")}function Mg(){let e=vE();try{if(!ve__default.existsSync(e))return !0;let r=JSON.parse(ve__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var AE=x("updateChecker"),RE=promisify(execFile),$E=1440*60*1e3,_g=3e4;function LE(){let e=process.env.FLOW_HOME??be__default.join(Me__default.homedir(),".flow");return be__default.join(e,"update.lock")}async function Dg(e){try{let{stdout:t}=await RE(Xt(),["view",e,"version"],{timeout:_g,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function ME(e){let t=new AbortController,r=setTimeout(()=>t.abort(),_g);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 _E(e){return e.versionCheck.type==="npm-registry"?Dg(e.versionCheck.package):ME(e.versionCheck.repo)}async function DE(){let e=await Dg("@ciandt-flow/cli");return e&&Fe(ue,e)?(Di({currentVersion:ue,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function OE(){let e=Yr().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<$E)return;let s=await _E(r);try{await yt({...t,lastChecked:new Date().toISOString()});}catch(i){AE.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Fe(t.installedVersion,s)&&Us(r,"background").catch(()=>{});}));}async function gc(){let e=Mg();if(e===false)return;let t=LE();ve__default.mkdirSync(be__default.dirname(t),{recursive:true});let r=null;try{r=await ly.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await DE().catch(()=>null);n&&process.stdout.write(`
654
662
  \u26A0 @ciandt-flow/cli v${n} installing in background.
655
663
  Restart flow to apply the update.
656
664
 
657
- `);}await Zv().catch(()=>{});}finally{await r().catch(()=>{});}}var eE=x("cli"),ac=lg(async()=>{Je("tui"),Kc("tui"),Vc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();uo("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();uo("sigterm",t,r).finally(()=>process.exit(143));}),await ic().catch(()=>{}),await ad().catch(t=>{eE.error(`Failed to init catalog registry: ${String(t)}`);}),await Fm();let{waitUntilExit:e}=render(jsx(jm,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});ac.hook("preAction",async(e,t)=>{t!==ac&&await ic().catch(()=>{});});ac.parse();
665
+ `);}await OE().catch(()=>{});}finally{await r().catch(()=>{});}}var NE=x("cli"),hc=$g(async()=>{Je("tui"),Yc("tui"),Zc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();po("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();po("sigterm",t,r).finally(()=>process.exit(143));}),await gc().catch(()=>{}),await hd().catch(t=>{NE.error(`Failed to init catalog registry: ${String(t)}`);}),await zm();let{waitUntilExit:e}=render(jsx(Xm,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});hc.hook("preAction",async(e,t)=>{t!==hc&&await gc().catch(()=>{});});hc.parse();