@ciandt-flow/cli 2.7.0 → 2.7.1-beta.14
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.
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as pn from'crypto';import {randomUUID,createHash}from'crypto';import*as $e from'os';import $e__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 Ie from'fs';import Ie__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as sl from'readline';import {createInterface}from'readline';import ma from'conf';import qu,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import zh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import oh from'jsonwebtoken';import hh from'proper-lockfile';import Nh from'ink-big-text';import Gd from'ink-spinner';import*as Mt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Wy from'unzipper';import {simpleGit}from'simple-git';import yl from'semver';import Hl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var qf=Object.defineProperty;var H=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var tc=(e,t)=>{for(var r in t)qf(e,r,{get:t[r],enumerable:true});};var lr,pe,Vi,Yn,sn,an,rc,Ji,Zn,ae,Xe,Kt,zo,ln,cn,un,dn,K=H(()=>{"use strict";lr="FLOW",pe="flow-skills",Vi="flow-cli",Yn="internal",sn="external",an={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"}},rc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ji=new Set(["internal","external"]),Zn={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"}},ae="flow-claude-md-setup",Xe=5,Kt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zo="https://flow.ciandt.com",ln=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,cn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",un=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,dn="Must be a valid email address (e.g. name@example.com)";});var Xo,Zf,oc,Qn,Hi=H(()=>{"use strict";Xo="aes-256-gcm",Zf=16,oc=16,Qn=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=pn.randomBytes(Zf),n=pn.createCipheriv(Xo,this.key,r,{authTagLength:oc}),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:Xo}}decrypt(t){if(t.algorithm!==Xo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=pn.createDecipheriv(Xo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:oc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Gi(e){return e.replace(rg,"").replace(ng,"").replace(og,"").replace(Qf,"Bearer ***").replace(eg,"***").replace(tg,"***").replace(/\r\n|\r|\n/g,"\\n")}var Qf,eg,tg,rg,ng,og,Wi=H(()=>{"use strict";Qf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,eg=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,tg=/[A-Za-z0-9+/]{40,}={0,2}/g,rg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,ng=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,og=/\x1b/g;});function Yo(e){return e||pe}function sc(e,t,r){return Xi(Yo(r),e,t)}function zi(e,t){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(t),"plugins","native",e)}function Zo(e){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(e),".claude-plugin","marketplace.json")}function Qo(){return xe.join($e.homedir(),Dr,"plugins","known_marketplaces.json")}function ic(e){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(e))}function ac(){return xe.join($e.homedir(),qo,"cache","install.lock")}function lc(){return xe.join($e.homedir(),qo,"logs","flowsetup.log")}function Xi(e,t,r){return xe.join($e.homedir(),Dr,"plugins","cache",e,t,r)}function Or(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills")}function eo(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function es(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join($e.homedir(),".config","opencode","plugins")}function cc(){return xe.join($e.homedir(),qo,"flow-catalogs.json")}function uc(){let e=process.env.FLOW_HOME??xe.join($e.homedir(),qo);return xe.join(e,"config.json")}function ts(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Dr,"agents"):xe.join($e.homedir(),Dr,"agents")}var Dr,qo,qe=H(()=>{"use strict";K();Dr=".claude",qo=".flow";});var sg,ig,rs,dc=H(()=>{"use strict";qe();sg=5*1024*1024,ig=3,rs=class{filePath;constructor(){this.filePath=lc(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
2
|
+
import*as pn from'crypto';import {randomUUID,createHash}from'crypto';import*as $e from'os';import $e__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 Ie from'fs';import Ie__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as sl from'readline';import {createInterface}from'readline';import ma from'conf';import qu,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import zh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import oh from'jsonwebtoken';import hh from'proper-lockfile';import Nh from'ink-big-text';import Gd from'ink-spinner';import*as Mt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Wy from'unzipper';import {simpleGit}from'simple-git';import yl from'semver';import Hl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var qf=Object.defineProperty;var H=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var tc=(e,t)=>{for(var r in t)qf(e,r,{get:t[r],enumerable:true});};var lr,pe,Vi,Yn,sn,an,rc,Ji,Zn,ae,Xe,Kt,zo,ln,cn,un,dn,K=H(()=>{"use strict";lr="FLOW",pe="flow-skills",Vi="flow-cli",Yn="internal",sn="external",an={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"}},rc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ji=new Set(["internal","external"]),Zn={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"}},ae="flow-claude-md-setup",Xe=5,Kt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zo="https://flow.ciandt.com",ln=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,cn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",un=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,dn="Must be a valid email address (e.g. name@example.com)";});var Xo,Zf,oc,Qn,Hi=H(()=>{"use strict";Xo="aes-256-gcm",Zf=16,oc=16,Qn=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=pn.randomBytes(Zf),n=pn.createCipheriv(Xo,this.key,r,{authTagLength:oc}),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:Xo}}decrypt(t){if(t.algorithm!==Xo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=pn.createDecipheriv(Xo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:oc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Gi(e){return e.replace(rg,"").replace(ng,"").replace(og,"").replace(Qf,"Bearer ***").replace(eg,"***").replace(tg,"***").replace(/\r\n|\r|\n/g,"\\n")}var Qf,eg,tg,rg,ng,og,Wi=H(()=>{"use strict";Qf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,eg=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,tg=/[A-Za-z0-9+/]{40,}={0,2}/g,rg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,ng=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,og=/\x1b/g;});function Yo(e){return e||pe}function sc(e,t,r){return Xi(Yo(r),e,t)}function zi(e,t){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(t),"plugins","native",e)}function Zo(e){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(e),".claude-plugin","marketplace.json")}function Qo(){return xe.join($e.homedir(),Dr,"plugins","known_marketplaces.json")}function ic(e){return xe.join($e.homedir(),Dr,"plugins","marketplaces",Yo(e))}function ac(){return xe.join($e.homedir(),qo,"cache","install.lock")}function lc(){return xe.join($e.homedir(),qo,"logs","flowsetup.log")}function Xi(e,t,r){return xe.join($e.homedir(),Dr,"plugins","cache",e,t,r)}function Or(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills")}function eo(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function es(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join($e.homedir(),".config","opencode","plugins")}function cc(){return xe.join($e.homedir(),qo,"flow-catalogs.json")}function uc(){let e=process.env.FLOW_HOME??xe.join($e.homedir(),qo);return xe.join(e,"config.json")}function ts(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Dr,"agents"):xe.join($e.homedir(),Dr,"agents")}var Dr,qo,qe=H(()=>{"use strict";K();Dr=".claude",qo=".flow";});var sg,ig,rs,dc=H(()=>{"use strict";qe();sg=5*1024*1024,ig=3,rs=class{filePath;constructor(){this.filePath=lc(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
3
|
`;try{Ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=xe.dirname(this.filePath);Ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(Ie.statSync(this.filePath).size>sg){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);Ie.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=xe.dirname(this.filePath),r=xe.basename(this.filePath,".log"),n=Ie.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(ig))Ie.unlinkSync(xe.join(t,o));}catch{}}};});var ns,pc=H(()=>{"use strict";ns=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
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 os,mc=H(()=>{"use strict";os=class{write(t){process.stdout.write(t.message+`
|
|
5
5
|
`);}};});function Yi(){return ss}function fc(e){return qi.add(e),()=>{qi.delete(e);}}var ss,qi,is,Zi=H(()=>{"use strict";ss=[],qi=new Set;is=class{write(t){ss.push(t),ss.length>100&&ss.shift();for(let r of qi)r();}};});function ag(){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 Fe(e,t){if(e==="tui"){let r=ag();Br={context:e,transports:[new is,new rs],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Br={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Br={context:e,transports:[new ns("cli")],minLevel:"debug",debugModules:null}:Br={context:e,transports:[new os],minLevel:"info",debugModules:null};}function gc(){return Br.transports}function hc(e,t){let{debugModules:r,minLevel:n}=Br;return Br.context==="tui"&&r&&r!=="all"?r.has(t)?mn[e]>=mn.debug:mn[e]>=mn.warn:mn[e]>=mn[n]}var mn,Br,Qi=H(()=>{"use strict";dc();pc();mc();Zi();mn={debug:0,info:1,warn:2,error:3},Br={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function as(e,t,r){if(!hc(e,t))return;let n={level:e,module:t,message:Gi(r),timestamp:new Date};for(let o of gc())o.write(n);}function x(e){let t=yc.get(e);if(t)return t;let r={debug:n=>as("debug",e,n),info:n=>as("info",e,n),warn:n=>as("warn",e,n),error:n=>as("error",e,n)};return yc.set(e,r),r}var yc,wc=H(()=>{"use strict";Wi();Qi();yc=new Map;});var L=H(()=>{"use strict";wc();Qi();Wi();});function lg(e){return typeof e=="object"&&e!==null&&ta in e&&e[ta]===true}function ra(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ta]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return ea.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(lg(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return ea.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return ea.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var ea,ta,na=H(()=>{"use strict";L();ea=x("encryption"),ta="__encrypted__";});var oa,dg,pt,fn,sa=H(()=>{"use strict";L();oa=promisify(execFile),dg=promisify(exec),pt=x("encryption:macos-keyvault"),fn=class{static async isAvailable(){try{let{stdout:t}=await dg("command -v security");return pt.debug(`security binary found at: ${t.trim()}`),!0}catch{return pt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{pt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await oa("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return pt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return pt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{pt.debug(`Storing secret: service=${t}, account=${r}`),await oa("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),pt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw pt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return pt.debug(`Deleting secret: service=${t}, account=${r}`),await oa("security",["delete-generic-password","-a",r,"-s",t]),pt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return pt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g,"")}function le(e){process.stdout.write(T.green(` \u2713 ${y(e)}
|
|
@@ -107,7 +107,7 @@ public class FlowCredManager {
|
|
|
107
107
|
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw mt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=ua(t,r);mt.debug(`Deleting secret: target=${n}`);let o=Tg(n),{stdout:s}=await cs(ls(o)),i=s.trim()==="True";return mt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
108
|
`)[0]:"unknown error";return mt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function $g(){let e=`${$e.hostname()}${$e.userInfo().username}`;return pn.scryptSync(e,kg,Cg)}function Lg(){let e=$g(),t=new Qn(e),r=ra(t);return new ma({projectName:fa,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function us(){return ds||(ds=Lg()),ds}var Cg,kg,fa,Ag,ds,Ke,no=H(()=>{"use strict";Hi();na();Cg=32,kg="flow-plugins-cli-fallback",fa="flow-plugins-cli-fallback",Ag={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)"};ds=null;Ke=class{warned=!1;async getSecret(t,r){return us().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Ag[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;}us().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=us(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return us().path}static hasExistingData(){try{let t=new ma({projectName:fa});return Ie.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ma({projectName:fa});Ie.rmSync(t.path,{force:!0});}catch{}ds=null;}};});async function ga(){if(Ke.hasExistingData())return new Ke;switch(process.platform){case "darwin":return await fn.isAvailable()?new fn:new Ke;case "linux":return await ur.isAvailable()?new ur:await ur.ensureInstalled()?new ur:new Ke;case "win32":return await hn.isAvailable()?new hn:new Ke;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var vc=H(()=>{"use strict";sa();la();pa();no();});var Ec=H(()=>{"use strict";Hi();na();vc();sa();la();pa();no();});async function dr(){return fs||(fs=ga()),fs}function gs(){fs=null;}async function te(){let t=await(await dr()).getSecret(Vt,ha);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function pr(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 Pc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await dr()).setSecret(Vt,ha,JSON.stringify(e));}async function Tc(){let e=await dr();await e.deleteSecret(Vt,ha),await e.deleteSecret(Vt,ya),await e.deleteSecret(Vt,wa);}async function Cc(){return (await dr()).getStoragePath()}async function kc(e){await(await dr()).setSecret(Vt,ya,JSON.stringify(e));}async function hs(){let t=await(await dr()).getSecret(Vt,ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ys(e){await(await dr()).setSecret(Vt,wa,JSON.stringify(e));}async function ws(){let t=await(await dr()).getSecret(Vt,wa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function mr(){let e=await hs();return e?new Date(e.expiresAt)>new Date:false}function Tt(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/`,Pc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Pc,Vt,ha,ya,wa,fs,Ee=H(()=>{"use strict";Ec();L();Pc=x("config:credentials"),Vt="flow-plugins-cli",ha="credentials",ya="token-cache",wa="user-info",fs=null;});function yn(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ss=H(()=>{"use strict";});function Mg(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Sa(e){if(Ac.some(r=>r.test(e)))return true;let t=Mg(e);return !!(t&&Ac.some(r=>r.test(t)))}function Rg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function fr(e,t){let r=Rg(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Sa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Ac,wn=H(()=>{"use strict";Ac=[/^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 Og(e){if(!Kt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Ug(e){if(e instanceof HTTPError){let t=e.response.status;xa.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&$c[r]?new Error($c[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(xa.debug(`Non-HTTP error during authentication: ${e.message}`),e):(xa.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Nr(e){let t=fr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Og(e.tenant);let r;try{r=await qu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Ug(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await pr(e),await kc({accessToken:r.access_token,expiresAt:n});let o=yn(r.access_token);await ys({sub:o.sub,name:o.name,email:o.email});}var xa,$c,xs=H(()=>{"use strict";Ee();Ss();wn();L();K();xa=x("api:auth");$c={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 Ct(){if(await mr()){let n=await hs();if(n)return n.accessToken}Lc.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ke.clearFallbackFile(),gs(),await Nr(t);let r=await hs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Lc.debug("Token refreshed successfully"),r.accessToken}var Lc,Sn=H(()=>{"use strict";Ee();xs();no();L();Lc=x("lib:tokenProvider");});function Gt(){return qu.create({prefix:fr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ct();e.headers.set("Authorization",`Bearer ${t}`);let r=await te();r?.tenant&&Kt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var So=H(()=>{"use strict";wn();Ee();Sn();K();});function Cn(e,t){let r=Gt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function kn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Va=H(()=>{"use strict";So();});function xo(e){if(!e||!Dy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function An(e){return Oy.test(e)}function $n(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Ha(e){if(!Uy.test(e))throw new Error(`Invalid plugin name: "${e}". Plugin names must start with an alphanumeric character and contain only letters, digits, dots, hyphens, underscores, and slashes.`)}function Ln(e,t){let r=$n(e);Ha(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function Xs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!By.test(t)&&!Ny.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Dy,Oy,Uy,By,Ny,Er=H(()=>{"use strict";Dy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;Oy=/^[^@]+@[^@]+$/;Uy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;By=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,Ny=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Gu={};tc(Gu,{FlowApiAdapter:()=>Mn});var Fy,Mn,Ga=H(()=>{"use strict";So();Va();L();Er();Fy=x("catalog.flow-api"),Mn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Cn("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 kn(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){xo(t);try{return await Cn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await kn(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 Gt().head("v1/plugins/catalog"),Fy.debug("ping ok"),!0}catch{return !1}}};});function Ky(){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 zu(){return Wu??=Ky(),Wu}var Wu,Xu=H(()=>{"use strict";});var Zu={};tc(Zu,{GitRepoAdapter:()=>Rn});function Yu(e,t){if(!Vy.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Vy,Rn,Wa=H(()=>{"use strict";Xu();wn();Vy=/^[a-zA-Z0-9_.-]+$/;Rn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Sa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Yu(a,"owner"),Yu(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await qu.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await qu.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await zu();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});K();var nc=new Set(["skill","mcp","bundle"]),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(nc),origins:new Set(Ji)},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(nc)},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(Ji)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ee();Sn();Ss();K();wn();L();var Is=x("api:metrics");function Mc(){return fr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Rc(e,t,r){return qu.post(e,{json:t,headers:r})}async function Ng(e){let t=await ws();if(t)return t;let r=yn(e),n={sub:r.sub,name:r.name,email:r.email};return await ys(n),n}async function v(e,t){let r=await Ct(),n=await Ng(r),o=await te();if(!Kt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Vi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Rc(Mc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Is.debug(`Metrics event sent: ${e}`);}catch(i){throw Is.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function _c(e,t,r){try{let n=r&&Kt.test(r)?r:"unknown",o={action:e,booster:Vi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Rc(Mc(),o,{FlowTenant:n}),Is.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Is.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"};var Fg={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ft={...Fg};function Dc(e){let t=Date.now();ft={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Fr(e){ft.currentStep=e,ft.stepStart=Date.now();}function Y(){return {...ft}}function gr(){return ft.sessionStart===0?0:Date.now()-ft.sessionStart}function jr(){return ft.stepStart===0?0:Date.now()-ft.stepStart}function Oc(){ft.tuiSessionStart=Date.now();}function Uc(){return ft.tuiSessionStart===0?0:Date.now()-ft.tuiSessionStart}L();var jg=3e3,Kg=x("abandonment");async function bs(e){let{currentStep:t,sessionStart:r}=Y();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:gr()};try{await Promise.race([v(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),jg))]);}catch(o){Kg.warn(`Abandonment event failed: ${String(o)}`);}}function Bc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}L();var Vg=3e3,Jg=x("session-end");async function so(e,t,r){let n=Uc(),s=[v(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(bs(e));try{await Bc(Promise.all(s).then(()=>{}),Vg);}catch(i){Jg.warn(`Session end event failed: ${String(i)}`);}}var zg=2e3;function Fc(){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),so("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},zg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Zg=16;function jc({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(Zg)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}K();function Kc({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();un.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:dn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}K();function Vc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}K();function Jc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[lr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var Qe=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));xs();K();function Jr(){return xe__default.join($e__default.homedir(),".claude","settings.json")}function Gc(e){return `${(e&&e.trim().length>0?e.trim():zo).replace(/\/+$/,"")}/flow-litellm/`}function mo(){let e=Jr();if(!Ie__default.existsSync(e))return {status:"missing"};let t=Ie__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Es(e){let t=Jr();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function Wc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function Ca(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function zc(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 sh=3600,Hr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function fo(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 ih(e){return oh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:sh})}function Ps(e,t={}){let r=mo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Hr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Ca(r.settings):null,s=r.status==="ok"?zc(r.settings):null,i=t.jwtOverride??ih(e),a=Gc(e.customUrl),l=Wc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Ts(e){Es(e.merged);}function Xc(){let e=mo();return e.status!=="ok"?false:Ca(e.settings)!==null}Ee();qe();function ah(){let e=uc();if(!Ie__default.existsSync(e))return {};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var ka=null;function lh(){return ka===null&&(ka=ah()),ka}function wr(){return !!lh().ENABLE_EXPERIMENTAL_BETAS}K();function ph(){return oe.filter(e=>e.platforms[process.platform]?.status==="supported")}function Yc(e){let t=ph();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Cs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=xe__default.join($e__default.homedir(),".claude","settings.json"),r=Ie__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??zo),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"}},mh={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},oe=wr()?[Cs,mh]:[Cs];Ee();L();var yh=x("moduleState");function As(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var wh={retries:5,minTimeout:50};async function Zc(e,t){Ie__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await hh.lock(e+".lock",{realpath:false,retries:wh});try{return await t()}finally{await r();}}function Qc(){let e=As();if(!Ie__default.existsSync(e))return [];try{let t=JSON.parse(Ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(yh.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),Ie__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return Ie__default.rmSync(e,{force:true}),[]}}function Gr(){return Qc()}function eu(e){let t=As();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Ie__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function et(e){return Gr().find(t=>t.alias===e)??null}async function gt(e){let t=As();await Zc(t,async()=>{let r=Qc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,eu(r);});}async function Wr(){let e=As();Ie__default.existsSync(e)||await Zc(e,async()=>{Ie__default.existsSync(e)||eu([]);});}var Ih=promisify(execFile);function Sr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function At(e){let t=process.platform==="win32"?"where":"which";try{return await Ih(t,[e]),!0}catch{return false}}function Jt(){return process.platform==="win32"?"npm.cmd":"npm"}var tu=promisify(execFile),In=class{type="npm";async isAvailable(){return At("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Sr(t,"npm");if(!r)return null;try{let{stdout:n}=await tu(Jt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=Sr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await tu(Jt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var $s=promisify(execFile),Th=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Ls=class{type="homebrew";async isAvailable(){return At("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Sr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Sr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await $s("brew",["tap",o.tap]),await $s("brew",["trust",o.tap])),await $s("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await $s("brew",["list","--versions",t]),n=r.trim().match(Th);return n?n[2]:null}catch{return null}}};var bn=promisify(execFile),nu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ou(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ms=class{type="curl";async isAvailable(){return At("curl")}async install(t){let r=Date.now(),n=Sr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=xe__default.join(ou(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await bn(n,["--version"]),s=o.match(nu);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($e__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await bn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{Ie__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return Ie__default.chmodSync(s,448),await bn("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{Ie__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ou(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(Ie__default.mkdirSync(s,{recursive:!0}),a=!0,await bn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return Ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}Ie__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await bn(i,["--version"]),c=u.match(nu);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{Ie__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($e__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await bn("curl",["-L","--fail","-o",n,r]);let o=Ie__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=Ie__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{Ie__default.unlinkSync(n);}catch{}}}};L();var su="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(su=e.version);}catch{}var me=su;var Pe=x("moduleInstaller");function Lt(e){switch(e){case "npm":return new In;case "homebrew":return new Ls;case "curl":return new Ms}}async function go(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){Pe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ir(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Pe.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 go(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 go(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 go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Lt(r),u=false;try{u=await l.isAvailable();}catch(d){Pe.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 go(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:me,trigger:t});}catch(d){Pe.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);Pe.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await gt({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){Pe.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Rh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await go(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Rh(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 te(),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 Pe.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,Pe.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Pe.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Pe.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Rs(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Lt(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:me,trigger:"command"});}catch(a){Pe.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);Pe.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await gt({...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){Pe.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){Pe.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){Pe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}L();var _s=x("flowAiObsSetup");async function Ds(e,t){try{if(!await new In().isAvailable().catch(()=>!1))return _s.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ir(Cs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(_s.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(_s.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return _s.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}L();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 _h=x("useAuthSetup");function au(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:b}=Qe(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},R=()=>{v(I.CLI_SESSION_STARTED,{cli_version:me,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});},P=async j=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{j&&Ts(j),await pr(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),b(true),R(),await Ds(n.current,o.current).catch(G=>_h.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Os({starterKit:B.starterKit});},$=async()=>P(),_=async j=>P(j),O=j=>{try{let z={...r.current,customUrl:n.current??void 0};return Ps(z,{allowOverwriteMalformed:j,jwtOverride:e.trim()})}catch(z){return z instanceof Hr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},Q=()=>{let j=O(true);j&&(f(j),_(j));},k=async()=>{let j=e.trim();if(!j){i("This field is required");return}let z;try{z=fo(j);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=z,m("customUrl");},J=j=>{n.current=j,m("email");},Z=j=>{o.current=j,N();},N=async()=>{let j=n.current;j&&Tt(j),c(true),l(null),h.current+=1;try{await Nr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),_c(I.CLI_AUTH_FAILED,{error_code:iu(z),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:D,handleSubmit:k,goToEmailStep:J,handleEmailConfirm:Z,commitAndProceed:_,skipJwtAndProceed:$,planPersistOverwrite:Q}}K();V();function lu(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=au(),[g,w]=useState("confirm"),[b,D]=useState(""),R=useRef(""),[P,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),R.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?h():O.escape&&u();return}if(o==="customUrl"){if(g==="confirm")_==="y"||_==="Y"?w("input"):(_==="n"||_==="N"||O.return)&&d(null);else if(O.escape)R.current="",D(""),w("confirm");else if(O.return){let Q=R.current.trim();Q.length>0&&ln.test(Q)?($(false),d(Q)):Q.length>0&&$(true);}else O.backspace||O.delete?(R.current=R.current.slice(0,-1),D(R.current)):_&&!O.ctrl&&!O.meta&&(R.current=R.current+_,D(R.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:[lr," \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:b}),jsx(Text,{color:"cyan",children:"\u2588"})]}),P&&jsx(Text,{color:"red",children:cn}),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:[lr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Kc,{onConfirm:m})]}):o==="preview"&&s?jsx(Vc,{plan:s}):o==="malformedConfirm"?jsx(Jc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \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(jc,{label:"JWT",value:e,onChange:_=>{a(_),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function En(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Nh,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",me]})})]})}var pu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=wr()?pu:pu.slice(0,3);function Fh(e){return re.findIndex(t=>t.id===e)}function La(e,t,r){let n=Fh(r.activeTab);if(t.rightArrow||t.tab){let o=re[(n+1)%re.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=re[(n-1+re.length)%re.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:re[n]?.focus??"list"}]:[]}var gu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function hu({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${gu[r]} (${e})`:gu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ve=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function wu(){let e=S(i=>i.focus),t=Ve(i=>i.query),r=Ve(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}K();var Jh=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...an[e]})),Hh=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...rc[e]}));function Su(){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"]})]}),Jh.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"]})]}),Hh.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}K();function xu({type:e}){let{label:t,color:r}=an[e];return jsx(Text,{color:r,children:t})}K();function vu({origin:e}){return e===Yn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}V();var Bs=zh.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(xu,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(vu,{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 ",Pt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Pn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}K();function Tu({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Pn,{message:t});let n=Math.max(0,r-Math.floor(Xe/2)),o=Math.min(e.length,n+Xe);o===e.length&&(n=Math.max(0,o-Xe));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Bs,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Au({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}K();function Lu({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(Pn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Xe/2)),u=Math.min(n.length,l+Xe);u===n.length&&(l=Math.max(0,u-Xe));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Au,{label:p.label,pathHint:p.pathHint},p.key):jsx(Bs,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var ry={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ny({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(wu,{}),jsx(Su,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:ry[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Lu,{groups:n,emptyMessage:r}):jsx(Tu,{items:e,emptyMessage:r})]})}function Mu({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(ny,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var iy={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 Ns(){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:[iy[e],t?" | Ctrl+D: debug log":""]})})}V();function Ru({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function Fs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Ba(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Uu=20;function js(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Uu),s="\u2588".repeat(o)+"\u2591".repeat(Uu-o),i=`${Ba(e)} / ${Ba(t)}`;return {bar:s,percent:n,label:i}}function Ks({received:e,total:t}){let{bar:r,percent:n,label:o}=js(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Vs({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function tt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}K();var Ka=Object.entries(Zn),ju=[...Ka.map(([,e])=>e.actionLabel),"Cancel"],Ku=Object.fromEntries(Ka.map(([,e])=>[e.actionLabel,e.description]));function Vu(e){let t=Ka.find(([,r])=>r.actionLabel===e);return t?t[0]:null}L();var Iy=x("provider.registry"),by=3e4,Hs=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+by}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&Iy.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 vy={user:"global",project:"project",local:"local"};function Gs(e){return e?vy[e]:"global"}var Je=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},vr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};So();Va();L();var Ty=x("catalog.registry"),Ws=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);Ty.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};qe();var _y={retries:5,minTimeout:50};async function Ja(e,t){mkdirSync(dirname(e),{recursive:true});let r=await hh.lock(e+".lock",{realpath:false,retries:_y});try{return await t()}finally{await r();}}var zs=class{filePath;constructor(t){this.filePath=t??cc();}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 Ja(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 Ja(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ja(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};Ga();var ce=new Ws,Wt=new zs,Jy=["flow-harness"];function Hy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?Jy:e.split(",").map(t=>t.trim()).filter(Boolean)}ce.register(new Mn);for(let e of Hy())ce.register(new Mn(e));var Qu=false;async function ed(){if(Qu)return;Qu=true;let e=await Wt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Wa(),Zu));for(let r of e)ce.register(new t(r.id,r.name,r.source));}Er();var td=2;async function zt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Ga(),Gu));return new t(e).fetchItems()}return ce.fetchAll()}async function rd(){return ce.fetchAllWithErrors()}async function _n(e,t){xo(e);try{return await Cn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await kn(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 nd(e,t,r){xo(e);try{let n=await Cn(`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*td)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*td}`);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 kn(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 Gt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}qe();qe();async function od(e,t){let r=xe.resolve(t);await Mt.mkdir(r,{recursive:true});let n=xe.join(xe.dirname(r),`${randomUUID()}.zip`);try{await Mt.writeFile(n,e);let o=await Wy.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 Mt.unlink(n);}catch{}}}async function za(e){await Mt.rm(e,{recursive:true,force:true});}async function Pr(){let e=ac();await Mt.mkdir(xe.dirname(e),{recursive:true});try{await Mt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await hh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}qe();K();function qy(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||pe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ad(e){let t=Zo(e);if(!Ie__default.existsSync(t))return null;try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return null}}function Yy(e){let t=ad(e);if(t)return t;let r=qy(e),n=Zo(e);return Ie__default.mkdirSync(xe__default.dirname(n),{recursive:true}),Xa(r,e),r}function Xa(e,t){let r=Zo(t),n=`${r}.${randomUUID()}.tmp`;Ie__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(n,r);}function Zy(e){let t=e||pe,r=Qo(),n={};try{Ie__default.existsSync(r)&&(n=JSON.parse(Ie__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()};let o=`${r}.${randomUUID()}.tmp`;Ie__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(o,r);}function ld(e,t,r){St(e.name),Zy(r);let n=zi(e.name,r);Ie__default.mkdirSync(xe__default.dirname(n),{recursive:true});try{Ie__default.lstatSync(n),Ie__default.rmSync(n,{recursive:!0,force:!0});}catch{}Ie__default.cpSync(t,n,{recursive:true,dereference:true});let o=Yy(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Xa(o,r));}function qa(e,t){St(e);let r=zi(e,t);try{Ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=ad(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Xa(n,t);}V();L();var ew=x("mcpConfigReader"),tw=500,rw=512;function nw(){return xe__default.join($e__default.homedir(),".claude.json")}function ow(){return xe__default.join(process.cwd(),".mcp.json")}function ud(e){if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return ew.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ya(e){if(!Io(e))return {};let t=e.mcpServers;return Io(t)?t:{}}function Za(e,t){return Object.keys(e).slice(0,tw).map(n=>({name:y(n.slice(0,rw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function pd(){let e=[],t=nw(),r=ud(t);if(Io(r)){let a=r,l=Ya(a);e.push(...Za(l,"user"));let u=process.cwd();if(Io(a.projects)){let c=a.projects[u];if(Io(c)){let d=Ya(c);e.push(...Za(d,"local"));}}}let n=ow(),o=ud(n),s=Ya(o);e.push(...Za(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}L();var rt=x("storage");async function iw(e,t,r){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Y().interfaceType});}catch(n){rt.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function aw(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:Y().interfaceType}).catch(o=>rt.warn(`Failed to send ${t} metrics: ${String(o)}`));}function rl(){return xe__default.join($e__default.homedir(),".claude","plugins","installed_plugins.json")}function lw(){return xe__default.join($e__default.homedir(),".claude","plugins")}function Ys(e){let t;try{t=Ie__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(lw()),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 fd(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($e__default.homedir(),".claude","settings.json")}function ot(){let e=rl();if(!Ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function nl(){let e=rl();try{let t=await Ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function cw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function gd(e,t){try{Ie__default.mkdirSync(xe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}catch(r){throw cw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function nt(e){gd(rl(),e);}function bo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function uw(e,t){let r=xe__default.join(e,".claude-plugin"),n=xe__default.join(r,"plugin.json");if(Ie__default.existsSync(n))try{return JSON.parse(Ie__default.readFileSync(n,"utf-8"))}catch{return null}let o=xe__default.join(r,"marketplace.json");if(Ie__default.existsSync(o))try{let s=JSON.parse(Ie__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ol(e="user"){let t=fd(e);if(!Ie__default.existsSync(t))return {};try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function hd(e,t="user"){gd(fd(t),e);}function dw(e,t){let{name:r,marketplace:n}=bo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],!o)throw rt.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function pw(e,t){let{name:r,marketplace:n}=bo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],o?{key:o,name:r}:null}function Qa(e="user"){return ol(e).enabledPlugins??{}}function el(e,t="user"){let r=ol(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,hd(r,t);}function vo(e,t,r="user"){let n=ol(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},hd(n,r);}function mw(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 se(){let e=ot(),t=Qa(),r=Qa("project"),n=Qa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=bo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return mw(p).map(h=>{let g=uw(h.installPath,d),b=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:b===false?"disabled":"enabled"}})}),i=pd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function md(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Eo(e,t){rt.debug(`[${e}] Acquiring lock to uninstall`);let r=await Pr();try{let n=ot(),o=pw(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);rt.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Ys(l.installPath);let u=xe__default.dirname(l.installPath);Ys(u),rt.debug(`[${i}] Removing directory: ${u}`),Ie__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;nt({...n,plugins:m}),el(s,t),qa(i,md(s));}else n.plugins[s]=c,nt(n),el(s,t);}else {rt.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Ys(c.installPath);let d=xe__default.dirname(c.installPath);Ys(d),rt.debug(`[${i}] Removing directory: ${d}`),Ie__default.rmSync(d,{recursive:!0,force:!0}),el(s,c.scope);}qa(i,md(s));let{[s]:l,...u}=n.plugins;nt({...n,plugins:u});}await iw(i,a[0].origin??"internal",a[0].type??"skill"),rt.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Po(e,t,r){rt.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Pr();try{let o=ot(),{key:s,name:i}=dw(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";rt.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),vo(s,t==="enabled",l),aw(i,t,u),rt.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}K();L();var fw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,gw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function St(e){if(!fw.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function hw(e){if(!gw.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var Tr=x("installer");function yw(e,t,r){let n=`${e}@${r||pe}`,s=ot().plugins[n];if(s&&!t)throw new Je(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function ww(e,t,r){r&&await za(t);try{Tr.debug(`[${t}] Extracting archive...`),await od(e,t);}catch(n){throw await za(t),n}}function Sw(e,t,r,n,o,s="claude-code",i){let a=ot(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],nt(a),vo(e,true,n);}async function xw(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:Y().interfaceType});}catch(i){Tr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Iw(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:Y().interfaceType});}catch(o){Tr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Re(e,t={}){let r=Date.now(),n=null;try{Tr.debug(`[${e}] Acquiring lock...`),n=await Pr();let{pluginKey:o,alreadyInstalled:s}=yw(e,t.force,t.source),{source:i}=t;Tr.debug(`[${e}] Fetching manifest...`);let a=await _n(e,i);St(a.name),hw(a.version),Tr.debug(`[${e}] Downloading archive...`);let l=await nd(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=sc(a.name,a.version,t.source);await ww(l,d,!!s&&!!t.force),Sw(o,d,a.version,u,"internal",t.providerId,c),ld(a,d,t.source);let m=Date.now()-r;Tr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await xw(a.name,a.version,m,Gs(u),"internal",c),p}catch(o){throw await Iw(e,o,"internal",t.type??"skill"),Tr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}L();V();Ee();Sn();L();var bw=x("commands:helpers");async function ue(){let e=await te();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&Tt(e.customUrl);try{await Ct();}catch(t){return bw.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function Rt(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function yd(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}Er();var On=x("claudeProxy"),cl="claude ",wd="flow ",il=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Dn=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";}},vw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ew=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Pw={"--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}$/},Tw=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Cw=/^(flow|claude)\s+auth\s+login(\s|$)/,Sd=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function xd(e){return Sd.test(e.trim())}function kw(e){return Sd.exec(e.trim())?.[2]??""}async function Id(e){let t=kw(e);Ha(t);let r=Date.now();On.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw ul(n)?new al:n}}function Aw(e){bd(e);let t=e.slice(cl.length);if(!vw.test(t))throw new Dn(e)}var Zs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},al=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function bd(e){if(!e||!/^claude /.test(e))throw new il(e)}function $w(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Ew.test(r))throw new Dn(`Unexpected flag: ${r}`);let n=Pw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Dn(`Flag ${r} requires a value`);if(!n.test(o))throw new Dn(`Unsafe value for flag ${r}`);t++;}}}async function Ce(e){bd(e);let t=e.slice(cl.length).split(/\s+/).filter(Boolean);$w(t);let r=Lw(t);On.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 On.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw ul(o)?new Zs:o}}function Lw(e){return e.length>=3?e[2]:e.join(" ")}function ul(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Mw(e){return e.startsWith(wd)?cl+e.slice(wd.length):e}function Rw(e){return Tw.test(e)||Cw.test(e)}function _w(e){let t=0;for(;t<e.length&&Rw(e[t]);)t++;return e.slice(t)}var Dw=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Ow(e,t){return !t||e.includes("--scope")||!Dw.test(e)?e:`${e} --scope ${t}`}async function To(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=_w(r).map(i=>Mw(i)).map(i=>Ow(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Aw(i);On.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Ce(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Ce(o[i]),s.exitCode!==0)return s;return s}async function Qs(e,t,r){let n=$n(e),o=t?.trim();if(!o&&(o=(await yd(`Plugin "${n}" could not be installed.
|
|
110
|
+
`),this.warned=!0;}us().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=us(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return us().path}static hasExistingData(){try{let t=new ma({projectName:fa});return Ie.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new ma({projectName:fa});Ie.rmSync(t.path,{force:!0});}catch{}ds=null;}};});async function ga(){if(Ke.hasExistingData())return new Ke;switch(process.platform){case "darwin":return await fn.isAvailable()?new fn:new Ke;case "linux":return await ur.isAvailable()?new ur:await ur.ensureInstalled()?new ur:new Ke;case "win32":return await hn.isAvailable()?new hn:new Ke;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var vc=H(()=>{"use strict";sa();la();pa();no();});var Ec=H(()=>{"use strict";Hi();na();vc();sa();la();pa();no();});async function dr(){return fs||(fs=ga()),fs}function gs(){fs=null;}async function te(){let t=await(await dr()).getSecret(Vt,ha);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function pr(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 Pc.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await dr()).setSecret(Vt,ha,JSON.stringify(e));}async function Tc(){let e=await dr();await e.deleteSecret(Vt,ha),await e.deleteSecret(Vt,ya),await e.deleteSecret(Vt,wa);}async function Cc(){return (await dr()).getStoragePath()}async function kc(e){await(await dr()).setSecret(Vt,ya,JSON.stringify(e));}async function hs(){let t=await(await dr()).getSecret(Vt,ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ys(e){await(await dr()).setSecret(Vt,wa,JSON.stringify(e));}async function ws(){let t=await(await dr()).getSecret(Vt,wa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function mr(){let e=await hs();return e?new Date(e.expiresAt)>new Date:false}function Tt(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/`,Pc.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Pc,Vt,ha,ya,wa,fs,Ee=H(()=>{"use strict";Ec();L();Pc=x("config:credentials"),Vt="flow-plugins-cli",ha="credentials",ya="token-cache",wa="user-info",fs=null;});function yn(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ss=H(()=>{"use strict";});function Mg(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Sa(e){if(Ac.some(r=>r.test(e)))return true;let t=Mg(e);return !!(t&&Ac.some(r=>r.test(t)))}function Rg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function fr(e,t){let r=Rg(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Sa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Ac,wn=H(()=>{"use strict";Ac=[/^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 Og(e){if(!Kt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Ug(e){if(e instanceof HTTPError){let t=e.response.status;xa.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&$c[r]?new Error($c[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(xa.debug(`Non-HTTP error during authentication: ${e.message}`),e):(xa.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Nr(e){let t=fr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Og(e.tenant);let r;try{r=await qu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Ug(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await pr(e),await kc({accessToken:r.access_token,expiresAt:n});let o=yn(r.access_token);await ys({sub:o.sub,name:o.name,email:o.email});}var xa,$c,xs=H(()=>{"use strict";Ee();Ss();wn();L();K();xa=x("api:auth");$c={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 Ct(){if(await mr()){let n=await hs();if(n)return n.accessToken}Lc.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ke.clearFallbackFile(),gs(),await Nr(t);let r=await hs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Lc.debug("Token refreshed successfully"),r.accessToken}var Lc,Sn=H(()=>{"use strict";Ee();xs();no();L();Lc=x("lib:tokenProvider");});function Gt(){return qu.create({prefix:fr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ct();e.headers.set("Authorization",`Bearer ${t}`);let r=await te();r?.tenant&&Kt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var So=H(()=>{"use strict";wn();Ee();Sn();K();});function Cn(e,t){let r=Gt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function kn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Va=H(()=>{"use strict";So();});function xo(e){if(!e||!Dy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function An(e){return Oy.test(e)}function $n(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Ha(e){if(!Uy.test(e))throw new Error(`Invalid plugin name: "${e}". Plugin names must start with an alphanumeric character and contain only letters, digits, dots, hyphens, underscores, and slashes.`)}function Ln(e,t){let r=$n(e);Ha(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function Xs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!By.test(t)&&!Ny.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Dy,Oy,Uy,By,Ny,Er=H(()=>{"use strict";Dy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;Oy=/^[^@]+@[^@]+$/;Uy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;By=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,Ny=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Gu={};tc(Gu,{FlowApiAdapter:()=>Mn});var Fy,Mn,Ga=H(()=>{"use strict";So();Va();L();Er();Fy=x("catalog.flow-api"),Mn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Cn("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 kn(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){xo(t);try{return await Cn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await kn(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 Gt().head("v1/plugins/catalog"),Fy.debug("ping ok"),!0}catch{return !1}}};});function Ky(){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 zu(){return Wu??=Ky(),Wu}var Wu,Xu=H(()=>{"use strict";});var Zu={};tc(Zu,{GitRepoAdapter:()=>Rn});function Yu(e,t){if(!Vy.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Vy,Rn,Wa=H(()=>{"use strict";Xu();wn();Vy=/^[a-zA-Z0-9_.-]+$/;Rn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Sa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Yu(a,"owner"),Yu(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await qu.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await qu.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await zu();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});K();var nc=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(nc),origins:new Set(Ji)},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(nc)},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(Ji)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ee();Sn();Ss();K();wn();L();var Is=x("api:metrics");function Mc(){return fr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Rc(e,t,r){return qu.post(e,{json:t,headers:r})}async function Ng(e){let t=await ws();if(t)return t;let r=yn(e),n={sub:r.sub,name:r.name,email:r.email};return await ys(n),n}async function v(e,t){let r=await Ct(),n=await Ng(r),o=await te();if(!Kt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Vi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Rc(Mc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Is.debug(`Metrics event sent: ${e}`);}catch(i){throw Is.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function _c(e,t,r){try{let n=r&&Kt.test(r)?r:"unknown",o={action:e,booster:Vi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Rc(Mc(),o,{FlowTenant:n}),Is.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Is.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"};var Fg={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ft={...Fg};function Dc(e){let t=Date.now();ft={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Fr(e){ft.currentStep=e,ft.stepStart=Date.now();}function Y(){return {...ft}}function gr(){return ft.sessionStart===0?0:Date.now()-ft.sessionStart}function jr(){return ft.stepStart===0?0:Date.now()-ft.stepStart}function Oc(){ft.tuiSessionStart=Date.now();}function Uc(){return ft.tuiSessionStart===0?0:Date.now()-ft.tuiSessionStart}L();var jg=3e3,Kg=x("abandonment");async function bs(e){let{currentStep:t,sessionStart:r}=Y();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:gr()};try{await Promise.race([v(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),jg))]);}catch(o){Kg.warn(`Abandonment event failed: ${String(o)}`);}}function Bc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}L();var Vg=3e3,Jg=x("session-end");async function so(e,t,r){let n=Uc(),s=[v(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(bs(e));try{await Bc(Promise.all(s).then(()=>{}),Vg);}catch(i){Jg.warn(`Session end event failed: ${String(i)}`);}}var zg=2e3;function Fc(){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),so("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},zg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Zg=16;function jc({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(Zg)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}K();function Kc({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();un.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:dn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}K();function Vc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}K();function Jc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[lr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var Qe=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));xs();K();function Jr(){return xe__default.join($e__default.homedir(),".claude","settings.json")}function Gc(e){return `${(e&&e.trim().length>0?e.trim():zo).replace(/\/+$/,"")}/flow-litellm/`}function mo(){let e=Jr();if(!Ie__default.existsSync(e))return {status:"missing"};let t=Ie__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Es(e){let t=Jr();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function Wc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function Ca(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function zc(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 sh=3600,Hr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function fo(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 ih(e){return oh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:sh})}function Ps(e,t={}){let r=mo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Hr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Ca(r.settings):null,s=r.status==="ok"?zc(r.settings):null,i=t.jwtOverride??ih(e),a=Gc(e.customUrl),l=Wc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Ts(e){Es(e.merged);}function Xc(){let e=mo();return e.status!=="ok"?false:Ca(e.settings)!==null}Ee();qe();function ah(){let e=uc();if(!Ie__default.existsSync(e))return {};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var ka=null;function lh(){return ka===null&&(ka=ah()),ka}function wr(){return !!lh().ENABLE_EXPERIMENTAL_BETAS}K();function ph(){return oe.filter(e=>e.platforms[process.platform]?.status==="supported")}function Yc(e){let t=ph();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Cs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=xe__default.join($e__default.homedir(),".claude","settings.json"),r=Ie__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??zo),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"}},mh={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},oe=wr()?[Cs,mh]:[Cs];Ee();L();var yh=x("moduleState");function As(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var wh={retries:5,minTimeout:50};async function Zc(e,t){Ie__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await hh.lock(e+".lock",{realpath:false,retries:wh});try{return await t()}finally{await r();}}function Qc(){let e=As();if(!Ie__default.existsSync(e))return [];try{let t=JSON.parse(Ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(yh.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),Ie__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return Ie__default.rmSync(e,{force:true}),[]}}function Gr(){return Qc()}function eu(e){let t=As();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Ie__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function et(e){return Gr().find(t=>t.alias===e)??null}async function gt(e){let t=As();await Zc(t,async()=>{let r=Qc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,eu(r);});}async function Wr(){let e=As();Ie__default.existsSync(e)||await Zc(e,async()=>{Ie__default.existsSync(e)||eu([]);});}var Ih=promisify(execFile);function Sr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function At(e){let t=process.platform==="win32"?"where":"which";try{return await Ih(t,[e]),!0}catch{return false}}function Jt(){return process.platform==="win32"?"npm.cmd":"npm"}var tu=promisify(execFile),In=class{type="npm";async isAvailable(){return At("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Sr(t,"npm");if(!r)return null;try{let{stdout:n}=await tu(Jt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=Sr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await tu(Jt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var $s=promisify(execFile),Th=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Ls=class{type="homebrew";async isAvailable(){return At("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Sr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Sr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await $s("brew",["tap",o.tap]),await $s("brew",["trust",o.tap])),await $s("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await $s("brew",["list","--versions",t]),n=r.trim().match(Th);return n?n[2]:null}catch{return null}}};var bn=promisify(execFile),nu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ou(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ms=class{type="curl";async isAvailable(){return At("curl")}async install(t){let r=Date.now(),n=Sr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=xe__default.join(ou(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await bn(n,["--version"]),s=o.match(nu);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($e__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await bn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{Ie__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return Ie__default.chmodSync(s,448),await bn("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{Ie__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ou(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(Ie__default.mkdirSync(s,{recursive:!0}),a=!0,await bn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return Ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}Ie__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await bn(i,["--version"]),c=u.match(nu);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{Ie__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($e__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await bn("curl",["-L","--fail","-o",n,r]);let o=Ie__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=Ie__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{Ie__default.unlinkSync(n);}catch{}}}};L();var su="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(su=e.version);}catch{}var me=su;var Pe=x("moduleInstaller");function Lt(e){switch(e){case "npm":return new In;case "homebrew":return new Ls;case "curl":return new Ms}}async function go(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){Pe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ir(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Pe.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 go(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 go(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 go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Lt(r),u=false;try{u=await l.isAvailable();}catch(d){Pe.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 go(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:me,trigger:t});}catch(d){Pe.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);Pe.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await gt({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){Pe.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Rh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await go(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Rh(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 te(),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 Pe.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,Pe.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Pe.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Pe.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Rs(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Lt(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:me,trigger:"command"});}catch(a){Pe.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);Pe.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await gt({...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){Pe.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){Pe.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){Pe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}L();var _s=x("flowAiObsSetup");async function Ds(e,t){try{if(!await new In().isAvailable().catch(()=>!1))return _s.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ir(Cs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(_s.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(_s.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return _s.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}L();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 _h=x("useAuthSetup");function au(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:b}=Qe(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},R=()=>{v(I.CLI_SESSION_STARTED,{cli_version:me,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});},P=async j=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{j&&Ts(j),await pr(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),b(true),R(),await Ds(n.current,o.current).catch(G=>_h.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Os({starterKit:B.starterKit});},$=async()=>P(),_=async j=>P(j),O=j=>{try{let z={...r.current,customUrl:n.current??void 0};return Ps(z,{allowOverwriteMalformed:j,jwtOverride:e.trim()})}catch(z){return z instanceof Hr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},Q=()=>{let j=O(true);j&&(f(j),_(j));},k=async()=>{let j=e.trim();if(!j){i("This field is required");return}let z;try{z=fo(j);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=z,m("customUrl");},J=j=>{n.current=j,m("email");},Z=j=>{o.current=j,N();},N=async()=>{let j=n.current;j&&Tt(j),c(true),l(null),h.current+=1;try{await Nr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),_c(I.CLI_AUTH_FAILED,{error_code:iu(z),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:D,handleSubmit:k,goToEmailStep:J,handleEmailConfirm:Z,commitAndProceed:_,skipJwtAndProceed:$,planPersistOverwrite:Q}}K();V();function lu(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=au(),[g,w]=useState("confirm"),[b,D]=useState(""),R=useRef(""),[P,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),R.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?h():O.escape&&u();return}if(o==="customUrl"){if(g==="confirm")_==="y"||_==="Y"?w("input"):(_==="n"||_==="N"||O.return)&&d(null);else if(O.escape)R.current="",D(""),w("confirm");else if(O.return){let Q=R.current.trim();Q.length>0&&ln.test(Q)?($(false),d(Q)):Q.length>0&&$(true);}else O.backspace||O.delete?(R.current=R.current.slice(0,-1),D(R.current)):_&&!O.ctrl&&!O.meta&&(R.current=R.current+_,D(R.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:[lr," \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:b}),jsx(Text,{color:"cyan",children:"\u2588"})]}),P&&jsx(Text,{color:"red",children:cn}),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:[lr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Kc,{onConfirm:m})]}):o==="preview"&&s?jsx(Vc,{plan:s}):o==="malformedConfirm"?jsx(Jc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \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(jc,{label:"JWT",value:e,onChange:_=>{a(_),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function En(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Nh,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",me]})})]})}var pu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=wr()?pu:pu.slice(0,3);function Fh(e){return re.findIndex(t=>t.id===e)}function La(e,t,r){let n=Fh(r.activeTab);if(t.rightArrow||t.tab){let o=re[(n+1)%re.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=re[(n-1+re.length)%re.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:re[n]?.focus??"list"}]:[]}var gu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function hu({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${gu[r]} (${e})`:gu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ve=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function wu(){let e=S(i=>i.focus),t=Ve(i=>i.query),r=Ve(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}K();var Jh=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...an[e]})),Hh=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...rc[e]}));function Su(){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"]})]}),Jh.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"]})]}),Hh.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}K();function xu({type:e}){let{label:t,color:r}=an[e];return jsx(Text,{color:r,children:t})}K();function vu({origin:e}){return e===Yn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}V();var Bs=zh.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(xu,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(vu,{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 ",Pt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Pn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}K();function Tu({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Pn,{message:t});let n=Math.max(0,r-Math.floor(Xe/2)),o=Math.min(e.length,n+Xe);o===e.length&&(n=Math.max(0,o-Xe));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Bs,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Au({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}K();function Lu({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(Pn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Xe/2)),u=Math.min(n.length,l+Xe);u===n.length&&(l=Math.max(0,u-Xe));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Au,{label:p.label,pathHint:p.pathHint},p.key):jsx(Bs,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var ry={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ny({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(wu,{}),jsx(Su,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:ry[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Lu,{groups:n,emptyMessage:r}):jsx(Tu,{items:e,emptyMessage:r})]})}function Mu({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(ny,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var iy={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 Ns(){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:[iy[e],t?" | Ctrl+D: debug log":""]})})}V();function Ru({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function Fs({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Ba(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Uu=20;function js(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Uu),s="\u2588".repeat(o)+"\u2591".repeat(Uu-o),i=`${Ba(e)} / ${Ba(t)}`;return {bar:s,percent:n,label:i}}function Ks({received:e,total:t}){let{bar:r,percent:n,label:o}=js(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Vs({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function tt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}K();var Ka=Object.entries(Zn),ju=[...Ka.map(([,e])=>e.actionLabel),"Cancel"],Ku=Object.fromEntries(Ka.map(([,e])=>[e.actionLabel,e.description]));function Vu(e){let t=Ka.find(([,r])=>r.actionLabel===e);return t?t[0]:null}L();var Iy=x("provider.registry"),by=3e4,Hs=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+by}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&Iy.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 vy={user:"global",project:"project",local:"local"};function Gs(e){return e?vy[e]:"global"}var Je=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},vr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};So();Va();L();var Ty=x("catalog.registry"),Ws=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);Ty.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};qe();var _y={retries:5,minTimeout:50};async function Ja(e,t){mkdirSync(dirname(e),{recursive:true});let r=await hh.lock(e+".lock",{realpath:false,retries:_y});try{return await t()}finally{await r();}}var zs=class{filePath;constructor(t){this.filePath=t??cc();}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 Ja(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 Ja(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ja(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};Ga();var ce=new Ws,Wt=new zs,Jy=["flow-harness"];function Hy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?Jy:e.split(",").map(t=>t.trim()).filter(Boolean)}ce.register(new Mn);for(let e of Hy())ce.register(new Mn(e));var Qu=false;async function ed(){if(Qu)return;Qu=true;let e=await Wt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Wa(),Zu));for(let r of e)ce.register(new t(r.id,r.name,r.source));}Er();var td=2;async function zt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Ga(),Gu));return new t(e).fetchItems()}return ce.fetchAll()}async function rd(){return ce.fetchAllWithErrors()}async function _n(e,t){xo(e);try{return await Cn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await kn(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 nd(e,t,r){xo(e);try{let n=await Cn(`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*td)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*td}`);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 kn(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 Gt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}qe();qe();async function od(e,t){let r=xe.resolve(t);await Mt.mkdir(r,{recursive:true});let n=xe.join(xe.dirname(r),`${randomUUID()}.zip`);try{await Mt.writeFile(n,e);let o=await Wy.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 Mt.unlink(n);}catch{}}}async function za(e){await Mt.rm(e,{recursive:true,force:true});}async function Pr(){let e=ac();await Mt.mkdir(xe.dirname(e),{recursive:true});try{await Mt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await hh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}qe();K();function qy(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||pe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function ad(e){let t=Zo(e);if(!Ie__default.existsSync(t))return null;try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return null}}function Yy(e){let t=ad(e);if(t)return t;let r=qy(e),n=Zo(e);return Ie__default.mkdirSync(xe__default.dirname(n),{recursive:true}),Xa(r,e),r}function Xa(e,t){let r=Zo(t),n=`${r}.${randomUUID()}.tmp`;Ie__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(n,r);}function Zy(e){let t=e||pe,r=Qo(),n={};try{Ie__default.existsSync(r)&&(n=JSON.parse(Ie__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()};let o=`${r}.${randomUUID()}.tmp`;Ie__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(o,r);}function ld(e,t,r){St(e.name),Zy(r);let n=zi(e.name,r);Ie__default.mkdirSync(xe__default.dirname(n),{recursive:true});try{Ie__default.lstatSync(n),Ie__default.rmSync(n,{recursive:!0,force:!0});}catch{}Ie__default.cpSync(t,n,{recursive:true,dereference:true});let o=Yy(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Xa(o,r));}function qa(e,t){St(e);let r=zi(e,t);try{Ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=ad(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Xa(n,t);}V();L();var ew=x("mcpConfigReader"),tw=500,rw=512;function nw(){return xe__default.join($e__default.homedir(),".claude.json")}function ow(){return xe__default.join(process.cwd(),".mcp.json")}function ud(e){if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return ew.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ya(e){if(!Io(e))return {};let t=e.mcpServers;return Io(t)?t:{}}function Za(e,t){return Object.keys(e).slice(0,tw).map(n=>({name:y(n.slice(0,rw)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function pd(){let e=[],t=nw(),r=ud(t);if(Io(r)){let a=r,l=Ya(a);e.push(...Za(l,"user"));let u=process.cwd();if(Io(a.projects)){let c=a.projects[u];if(Io(c)){let d=Ya(c);e.push(...Za(d,"local"));}}}let n=ow(),o=ud(n),s=Ya(o);e.push(...Za(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}L();var rt=x("storage");async function iw(e,t,r){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Y().interfaceType});}catch(n){rt.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function aw(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:Y().interfaceType}).catch(o=>rt.warn(`Failed to send ${t} metrics: ${String(o)}`));}function rl(){return xe__default.join($e__default.homedir(),".claude","plugins","installed_plugins.json")}function lw(){return xe__default.join($e__default.homedir(),".claude","plugins")}function Ys(e){let t;try{t=Ie__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(lw()),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 fd(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($e__default.homedir(),".claude","settings.json")}function ot(){let e=rl();if(!Ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function nl(){let e=rl();try{let t=await Ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function cw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function gd(e,t){try{Ie__default.mkdirSync(xe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}catch(r){throw cw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function nt(e){gd(rl(),e);}function bo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function uw(e,t){let r=xe__default.join(e,".claude-plugin"),n=xe__default.join(r,"plugin.json");if(Ie__default.existsSync(n))try{return JSON.parse(Ie__default.readFileSync(n,"utf-8"))}catch{return null}let o=xe__default.join(r,"marketplace.json");if(Ie__default.existsSync(o))try{let s=JSON.parse(Ie__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ol(e="user"){let t=fd(e);if(!Ie__default.existsSync(t))return {};try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function hd(e,t="user"){gd(fd(t),e);}function dw(e,t){let{name:r,marketplace:n}=bo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],!o)throw rt.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function pw(e,t){let{name:r,marketplace:n}=bo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],o?{key:o,name:r}:null}function Qa(e="user"){return ol(e).enabledPlugins??{}}function el(e,t="user"){let r=ol(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,hd(r,t);}function vo(e,t,r="user"){let n=ol(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},hd(n,r);}function mw(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 se(){let e=ot(),t=Qa(),r=Qa("project"),n=Qa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=bo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return mw(p).map(h=>{let g=uw(h.installPath,d),b=(o[h.scope]??t)[u];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:b===false?"disabled":"enabled"}})}),i=pd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function md(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Eo(e,t){rt.debug(`[${e}] Acquiring lock to uninstall`);let r=await Pr();try{let n=ot(),o=pw(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);rt.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Ys(l.installPath);let u=xe__default.dirname(l.installPath);Ys(u),rt.debug(`[${i}] Removing directory: ${u}`),Ie__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;nt({...n,plugins:m}),el(s,t),qa(i,md(s));}else n.plugins[s]=c,nt(n),el(s,t);}else {rt.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Ys(c.installPath);let d=xe__default.dirname(c.installPath);Ys(d),rt.debug(`[${i}] Removing directory: ${d}`),Ie__default.rmSync(d,{recursive:!0,force:!0}),el(s,c.scope);}qa(i,md(s));let{[s]:l,...u}=n.plugins;nt({...n,plugins:u});}await iw(i,a[0].origin??"internal",a[0].type??"skill"),rt.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Po(e,t,r){rt.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Pr();try{let o=ot(),{key:s,name:i}=dw(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";rt.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),vo(s,t==="enabled",l),aw(i,t,u),rt.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}K();L();var fw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,gw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function St(e){if(!fw.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function hw(e){if(!gw.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var Tr=x("installer");function yw(e,t,r){let n=`${e}@${r||pe}`,s=ot().plugins[n];if(s&&!t)throw new Je(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function ww(e,t,r){r&&await za(t);try{Tr.debug(`[${t}] Extracting archive...`),await od(e,t);}catch(n){throw await za(t),n}}function Sw(e,t,r,n,o,s="claude-code",i){let a=ot(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],nt(a),vo(e,true,n);}async function xw(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:Y().interfaceType});}catch(i){Tr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Iw(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:Y().interfaceType});}catch(o){Tr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Re(e,t={}){let r=Date.now(),n=null;try{Tr.debug(`[${e}] Acquiring lock...`),n=await Pr();let{pluginKey:o,alreadyInstalled:s}=yw(e,t.force,t.source),{source:i}=t;Tr.debug(`[${e}] Fetching manifest...`);let a=await _n(e,i);St(a.name),hw(a.version),Tr.debug(`[${e}] Downloading archive...`);let l=await nd(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=sc(a.name,a.version,t.source);await ww(l,d,!!s&&!!t.force),Sw(o,d,a.version,u,"internal",t.providerId,c),ld(a,d,t.source);let m=Date.now()-r;Tr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await xw(a.name,a.version,m,Gs(u),"internal",c),p}catch(o){throw await Iw(e,o,"internal",t.type??"skill"),Tr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}L();V();Ee();Sn();L();var bw=x("commands:helpers");async function ue(){let e=await te();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&Tt(e.customUrl);try{await Ct();}catch(t){return bw.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function Rt(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function yd(e){let t=sl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}Er();var On=x("claudeProxy"),cl="claude ",wd="flow ",il=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Dn=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";}},vw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ew=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Pw={"--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}$/},Tw=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Cw=/^(flow|claude)\s+auth\s+login(\s|$)/,Sd=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function xd(e){return Sd.test(e.trim())}function kw(e){return Sd.exec(e.trim())?.[2]??""}async function Id(e){let t=kw(e);Ha(t);let r=Date.now();On.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw ul(n)?new al:n}}function Aw(e){bd(e);let t=e.slice(cl.length);if(!vw.test(t))throw new Dn(e)}var Zs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},al=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function bd(e){if(!e||!/^claude /.test(e))throw new il(e)}function $w(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Ew.test(r))throw new Dn(`Unexpected flag: ${r}`);let n=Pw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Dn(`Flag ${r} requires a value`);if(!n.test(o))throw new Dn(`Unsafe value for flag ${r}`);t++;}}}async function Ce(e){bd(e);let t=e.slice(cl.length).split(/\s+/).filter(Boolean);$w(t);let r=Lw(t);On.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 On.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw ul(o)?new Zs:o}}function Lw(e){return e.length>=3?e[2]:e.join(" ")}function ul(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Mw(e){return e.startsWith(wd)?cl+e.slice(wd.length):e}function Rw(e){return Tw.test(e)||Cw.test(e)}function _w(e){let t=0;for(;t<e.length&&Rw(e[t]);)t++;return e.slice(t)}var Dw=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Ow(e,t){return !t||e.includes("--scope")||!Dw.test(e)?e:`${e} --scope ${t}`}async function To(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=_w(r).map(i=>Mw(i)).map(i=>Ow(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Aw(i);On.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Ce(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Ce(o[i]),s.exitCode!==0)return s;return s}async function Qs(e,t,r){let n=$n(e),o=t?.trim();if(!o&&(o=(await yd(`Plugin "${n}" could not be installed.
|
|
111
111
|
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Xs(o),r?.(),On.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"}`);On.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ul(s)?new Zs:s}}Er();K();qe();L();var jw=6e4,Cr=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function _t(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:jw}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new Cr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Cr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Cr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Dt(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 Qr(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 Vw(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Jw(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Hw(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Un(e,t){let r=e.source;if(Vw(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(Jw(r))return {cloneUrl:r.url,subPath:"."};if(Hw(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 st(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Ot=x("claude-code.adapter");function zw(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=Qo();if(!Ie__default.existsSync(s))return r;try{let i=JSON.parse(Ie__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 Ad(e,t){let r=e.catalogId?ce.getAdapter(e.catalogId):void 0,n=Un(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=zw(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Xi(s,e.name,"external"):a=join(Or(i==="user"?"global":"project"),e.name);let l=null;try{St(e.name),l=await _t(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(Ie__default.existsSync(a)&&Ie__default.rmSync(a,{recursive:!0,force:!0}),Ie__default.mkdirSync(dirname(a),{recursive:!0}),Ie__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await nl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],nt(d),vo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Ot.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Dt(l).catch(()=>{});}}async function dl(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Gs(n),version:"unknown",duration_ms:t,interface:Y().interfaceType});}catch(o){Ot.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Cd(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:Y().interfaceType});}catch(n){Ot.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Xw={async install(e,t){if(e.origin===sn&&!e.installCommand&&!An(e.name))return Ad(e,t);if(e.origin===sn&&e.installCommand){let r=e.type??"skill",n=await To(e.installCommand,t.scope);return n.exitCode===0?(await dl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Cd(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(An(e.name)){let r=e.type??"skill",n=Ln(e.name,t.scope);Ot.debug(`[${e.name}] Attempting install: ${n}`);let o=await Ce(n);if(o.exitCode===0)return await dl(e.name,o.duration_ms,r,t.scope),{success:true};Ot.debug(`[${e.name}] First attempt failed, adding marketplace`),await Qs(e.name,t.marketplaceSource,()=>{});let s=await Ce(n);return s.exitCode===0?(await dl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Cd(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 Re(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Ot.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Eo(e,t);},getInstallPath(e,t){return ""}};function kd(e){return {async install(t,r){if(t.origin===sn&&!t.installCommand&&!An(t.name))return Ad(t,r);if(!t.installCommand)try{let o=await Re(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Ot.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Ot.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await To(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=ot(),o=`${t}@${pe}`;if(n.plugins[o]){await Eo(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 qw(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!Ie__default.existsSync(t))continue;let r=Ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&Ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function pl(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,pl(r)]))}function $d(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(pl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(pl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=$d(s,o):r[n]=o;}return r}async function Ld(e,t,r,n){let o=await nl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],nt(o);}var Yw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ce.getAdapter(e.catalogId):void 0,o=Un(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{St(e.name),s=await _t(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=qw(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=ts(r);Ie__default.mkdirSync(l,{recursive:!0});let u=st(e.name);if(a.length===1)Ie__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=st(basename(d,".md"));Ie__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Ld(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Ot.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Dt(s).catch(()=>{});}},async uninstall(e,t){let r=ts(t),n=st(e);if(Ie__default.existsSync(r))for(let a of Ie__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))Ie__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=ot(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;nt({...s,plugins:l});}else nt({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(ts(t),`${st(e)}.md`)}},Zw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ce.getAdapter(e.catalogId):void 0,o=Un(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{St(e.name),s=await _t(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!Ie__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(Ie__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=mo();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=$d(m,u);return Es({...d,hooks:p}),await Ld(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Ot.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Dt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ei=class{id="claude-code";name="Claude Code";async isAvailable(){return Qr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Xw,skill:kd("skill"),mcp:kd("mcp"),agent:Yw,hook:Zw}};function ti(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var eS=new Set(["gh"]),tS=ti(eS,"use: gh copilot mcp remove <name>"),ri=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Qr("gh",["--version"])?Qr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:tS}};qe();var rS=new Set(["opencode"]),nS=ti(rS,"use: opencode config remove mcp <name>");function oS(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
112
|
`)}function Md(){return {async install(e,t){try{St(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ce.getAdapter(e.catalogId):void 0,n=Un(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await _t(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=es(t.scope??"user"),a=join(s,".opencode","plugins");if(Ie__default.existsSync(a)){let l=Ie__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/"};Ie__default.mkdirSync(i,{recursive:!0}),Ie__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);Ie__default.existsSync(l)&&Ie__default.rmSync(l,{recursive:!0,force:!0}),Ie__default.mkdirSync(l,{recursive:!0}),Ie__default.cpSync(s,l,{recursive:!0}),Ie__default.mkdirSync(i,{recursive:!0}),Ie__default.writeFileSync(join(i,`${e.name}.js`),oS(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 Dt(o).catch(()=>{});}},async uninstall(e,t){St(e);let r=es(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);Ie__default.existsSync(n)&&Ie__default.rmSync(n,{force:true}),Ie__default.existsSync(o)&&Ie__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(es(t),`${e}.js`)}}}var ni=class{id="opencode";name="OpenCode";async isAvailable(){return Qr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:nS,skill:Md(),bundle:Md()}};var Ut=new Hs;Ut.register(new ei);wr()&&(Ut.register(new ri),Ut.register(new ni));function Rd({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(()=>{Ut.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(b=>b.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Vu(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(tt,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(tt,{itemName:`${e} \u2014 Choose scope`,actions:ju,descriptions:Ku,onAction:f,onClose:h},"scope"):jsx(tt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}V();function Dd({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(tt,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ii({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}V();function Bd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=ii({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(tt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function jd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ii({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(tt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}L();var Fn=x("bundle:installer"),Kd=/already exists/i;async function pS(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(xd(t)){let r=await Id(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Kd.test(n))return;throw new Error(n)}}else {let r=await To(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Kd.test(n))return;throw new Error(n)}}}async function mS(e,t){try{await v(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Fn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function fS(e,t,r){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Fn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Vd(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){Fn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function gS(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){Fn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function ci(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await mS(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){Fn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await Vd(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await pS(f),u++,await fS(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let b=w instanceof Error?w.message:String(w);Fn.error(`Failed to install artifact "${h}": ${b}`),l.push({name:h,type:g,reason:b}),await Vd(i,h,g,b),r?.({index:p+1,total:c,artifact:f,success:false,error:b});}}let d=Date.now()-a,m=l.length;return await gS(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}V();function Wd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,ci(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Gd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Gd,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:se()})}));V();function zd({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 ",Pt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}V();function Xd({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 ${Pt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function qd(e){return e.adapter.removable!==false?4:2}K();V();function Yd({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Qd({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 ep({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,$)=>{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(Yd,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Xe/2)),p=Math.min(a.length,m+Xe);p===a.length&&(m=Math.max(0,p-Xe));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,b=p>s.length,D=f.filter(P=>r.has(`${P.name}@${o}`)),R=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(P=>jsx(Qd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),b&&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"]}),R.map(P=>jsx(Qd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Wa();var bS=/^https?:\/\/.+/;function vS(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function ES(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function op(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!bS.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let b=randomUUID(),D=new Rn(b,w,g);try{await D.fetchItems(),await Wt.add({id:b,name:w,source:g}),ce.register(new Rn(b,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(R){let P=vS(R)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":ES(R)?R.message:R instanceof Error?`Could not reach catalog URL: ${R.message}`:"Failed to validate catalog URL";t(P,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function sp(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Wt.remove(o),ce.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 ap(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=fe(A=>A.installedItems),[o,s]=useState(()=>ce.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,h]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&h("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=ce.listAdapters(),B=await Wt.read(),G=new Map(B.map(Ae=>[Ae.id,Ae]));s(A.map(Ae=>({adapter:Ae,stored:G.get(Ae.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 b=op(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:R}=sp(D),P=useCallback(async A=>{h("removing"),await R(A);},[R]),$=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 Wt.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 Wt.updateField(A.stored.id,{autoUpdate:!B}),w();},[w]),O=useCallback(()=>h("browse"),[]),Q=useCallback(A=>{let B=o[i-1];if(!B)return;let G=B.adapter.removable!==false;[O,()=>{$(B);},...G?[()=>{_(B);},()=>{P(B.adapter.id);}]:[]][A]?.();},[o,i,O,$,_,P]),k=useCallback(()=>h("main"),[]),J=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),Z=useCallback(()=>{let A=o[i-1];A&&_(A);},[o,i,_]),N=useCallback(()=>{let A=o[i-1];A&&P(A.adapter.id);},[o,i,P]);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?b.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&b.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],Ae=G?qd(G)-1:0;d(Wo=>Math.min(Wo+1,Ae));return}B.return&&Q(c);},{isActive:f==="main"&&b.phase==="idle"&&l==="detail"&&e==="marketplaces"}),b.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:b.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.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(b.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:b.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:b.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:b.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(b.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(Ae=>Ae.marketplace===A.adapter.name).map(Ae=>`${Ae.name}@${B}`));return jsx(ep,{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 j=o[i-1]??null,z=j?n.filter(A=>A.marketplace===j.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(zd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&j?jsx(Xd,{entry:j,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:Z,onRemove:N}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:j?"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 lp(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=re.findIndex(i=>i.id===r.activeTab),s=re[(o-1+re.length)%re.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=re.findIndex(i=>i.id===r.activeTab),s=re[(o+1)%re.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=re.findIndex(i=>i.id===r.activeTab),s=re[(o+1)%re.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 cp(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function up(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 AS=new Set(re.filter(e=>e.focus!=="list").map(e=>e.focus));function Oo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Ve.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function dp({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Ve(h=>h.query),a=Ve(h=>h.setQuery),l=Ve(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Ve.getState();g(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo(La(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo(La("",g,{activeTab:w}));},{isActive:AS.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo(lp(h,g,{activeTab:w,selectedIndex:b},u.current));},{isActive:t==="list"}),useInput((h,g)=>{Oo(cp(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=up(h,g,Ve.getState().query),b=w.queryUpdate;if(Oo(w.actions),b==="reset")l(),d("");else if(b!==null){let{query:D,cursorPosition:R,setCursorPosition:P}=Ve.getState();if("backspace"in b)R>0&&(a(D.slice(0,R-1)+D.slice(R)),P(R-1));else if("append"in b)a(D.slice(0,R)+b.append+D.slice(R)),P(R+b.append.length);else if("cursorMove"in b){let $=R+b.cursorMove;$>=0&&$<=D.length&&P($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();h===0?g(0):w>=h&&g(h-1);},[]),f=useCallback(h=>{if(!c)return u.current=h.length,h;let g=c.toLowerCase(),w=h.filter(b=>b.name.toLowerCase().includes(g)||b.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function mp(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Qe(a=>a.justAuthenticated),o=Qe(a=>a.credentials),s=Qe(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Oe(e,t,r=false){return r?true:!yl.valid(e)||!yl.valid(t)?false:yl.gt(t,e)}K();L();var Yt=x("updater");async function $S(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:Y().interfaceType});}catch(i){Yt.warn(`Failed to send update metrics: ${String(i)}`);}}function LS(e){let t=ot(),r=`${e}@${pe}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function mi(e,t={}){let r=Date.now(),n=null;try{Yt.debug(`[${e}] Acquiring lock...`),n=await Pr();let o=LS(e);if(!o)throw Yt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Yt.debug(`[${e}] Fetching manifest...`);let u=(await _n(e,t.source)).version;if(!i||!Oe(i,u,t.force))throw Yt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new vr(e,i??"unknown");Yt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Re(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await $S(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Yt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Yt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Pr();let d=ot(),m=`${e}@${pe}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,nt(d),Yt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Er();L();var fi=x("dispatcher");async function MS(e,t,r,n,o){let s=$n(e);return fi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Qs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),fi.debug(`[${e}] Retrying install after marketplace add`),Ce(t)}async function fp(e,t,r,n){let o=Ln(e,n),s=$n(e);r?.onStatus?.(`Installing ${s}...`),fi.debug(`[${e}] Attempting install: ${o}`);let i=await Ce(o);if(i.exitCode===0)return i;fi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return MS(e,o,a,t,r)}async function gp(e,t,r){let n=e.type??"bundle",o=await Ut.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 hp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await gp(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=se().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Ut.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 Po(i,u,a),t();},[e,t]),s=useCallback(async i=>{await mi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}V();L();var hi=x("mcp");function Uo(e,t){e.silent?Ze({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function wp(e,t){e.silent?je({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(le(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function RS(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function wl(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function Sp(e,t,r){if(!await ue())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Uo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}hi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=RS(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Rt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|