@ciandt-flow/cli 2.0.1-beta.226 → 2.0.1-beta.228
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 +74 -74
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {execa}from'execa';import
|
|
3
|
-
`;try{Ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=me.dirname(this.filePath);Ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(Ie.statSync(this.filePath).size>
|
|
2
|
+
import {execa}from'execa';import Vl,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Bm,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as kr from'crypto';import {randomUUID,createHash}from'crypto';import*as Ie from'fs';import Ie__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as me from'path';import me__default,{join,dirname,normalize,resolve,sep,relative,isAbsolute,basename}from'path';import*as Me from'os';import Me__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as Ii from'readline';import {createInterface}from'readline';import $ from'chalk';import Fs from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Im from'jsonwebtoken';import Mm from'ink-big-text';import af from'ink-spinner';import*as pt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import bf from'proper-lockfile';import Df from'extract-zip';import {simpleGit}from'simple-git';import $i from'semver';import ia from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var yp=Object.defineProperty;var vs=(e,t)=>()=>(e&&(t=e(e=0)),t);var hp=(e,t)=>{for(var r in t)yp(e,r,{get:t[r],enumerable:true});};function Yp(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 Js(e){if(Na.some(r=>r.test(e)))return true;let t=Yp(e);return !!(t&&Na.some(r=>r.test(t)))}function Zp(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function _r(e,t){let r=Zp(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Js(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Na,dn=vs(()=>{Na=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function Lf(){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 jl(){return Bl??=Lf(),Bl}var Bl,Kl=vs(()=>{});var Jl={};hp(Jl,{GitRepoAdapter:()=>jr});function Hl(e,t){if(!Rf.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Rf,jr,ui=vs(()=>{Kl();dn();Rf=/^[a-zA-Z0-9_.-]+$/;jr=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(Js(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Hl(a,"owner"),Hl(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 Vl.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 Vl.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 jl();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 false}}};});var Bn="FLOW",re="flow-skills",bs="flow-cli",nn="internal",Cr="external",Tr={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},ya={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ps=new Set(["internal","external"]),on={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"}},ie="flow-claude-md-setup",Be=5,or=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var ha=new Set(["skill","mcp","plugin"]),w=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,catalogFilters:{types:new Set(ha),origins:new Set(Ps)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:""}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(ha)},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(Ps)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1}))}));var jn="aes-256-gcm",wp=16,Sa=16,sn=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=kr.randomBytes(wp),n=kr.createCipheriv(jn,this.key,r,{authTagLength:Sa}),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:jn}}decrypt(t){if(t.algorithm!==jn)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=kr.createDecipheriv(jn,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Sa});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var xp=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Ip=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,vp=/[A-Za-z0-9+/]{40,}={0,2}/g;function Es(e){return e.replace(xp,"Bearer ***").replace(Ip,"***").replace(vp,"***")}var an=".claude",Kn=".flow";function wa(e,t){return Ts(re,e,t)}function Cs(e){return me.join(Me.homedir(),an,"plugins","marketplaces",re,"plugins","native",e)}function Vn(){return me.join(Me.homedir(),an,"plugins","marketplaces",re,".claude-plugin","marketplace.json")}function Hn(){return me.join(Me.homedir(),an,"plugins","known_marketplaces.json")}function xa(){return me.join(Me.homedir(),an,"plugins","marketplaces",re)}function Ia(){return me.join(Me.homedir(),Kn,"cache","install.lock")}function va(){return me.join(Me.homedir(),Kn,"logs","flowsetup.log")}function Ts(e,t,r){return me.join(Me.homedir(),an,"plugins","cache",e,t,r)}function sr(e){let t=e==="global"?Me.homedir():process.cwd();return me.join(t,".claude","skills")}function ln(e){let t=e==="global"?Me.homedir():process.cwd();return me.join(t,".claude","skills-lock.json")}function Jn(e="user"){return e==="project"?me.join(process.cwd(),".opencode","plugins"):me.join(Me.homedir(),".config","opencode","plugins")}function ba(){return me.join(Me.homedir(),Kn,"flow-catalogs.json")}function Pa(){let e=process.env.FLOW_HOME??me.join(Me.homedir(),Kn);return me.join(e,"config.json")}var bp=5*1024*1024,Pp=3,Gn=class{filePath;constructor(){this.filePath=va(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
+
`;try{Ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=me.dirname(this.filePath);Ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(Ie.statSync(this.filePath).size>bp){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=me.dirname(this.filePath),r=me.basename(this.filePath,".log"),n=Ie.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Pp))Ie.unlinkSync(me.join(t,o));}catch{}}};var Wn=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 zn=class{write(t){process.stdout.write(t.message+`
|
|
5
|
-
`);}};var Xn=[],ks=new Set;function As(){return Xn}function
|
|
5
|
+
`);}};var Xn=[],ks=new Set;function As(){return Xn}function Ea(e){return ks.add(e),()=>{ks.delete(e);}}var qn=class{write(t){Xn.push(t),Xn.length>100&&Xn.shift();for(let r of ks)r();}};var Ar={debug:0,info:1,warn:2,error:3},ar={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Ep(){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 Ke(e,t){if(e==="tui"){let r=Ep();ar={context:e,transports:[new qn,new Gn],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?ar={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?ar={context:e,transports:[new Wn("cli")],minLevel:"debug",debugModules:null}:ar={context:e,transports:[new zn],minLevel:"info",debugModules:null};}function Ca(){return ar.transports}function Ta(e,t){let{debugModules:r,minLevel:n}=ar;return ar.context==="tui"&&r&&r!=="all"?r.has(t)?Ar[e]>=Ar.debug:Ar[e]>=Ar.warn:Ar[e]>=Ar[n]}var ka=new Map;function Yn(e,t,r){if(!Ta(e,t))return;let n={level:e,module:t,message:Es(r),timestamp:new Date};for(let o of Ca())o.write(n);}function x(e){let t=ka.get(e);if(t)return t;let r={debug:n=>Yn("debug",e,n),info:n=>Yn("info",e,n),warn:n=>Yn("warn",e,n),error:n=>Yn("error",e,n)};return ka.set(e,r),r}var Ms=x("encryption"),$s="__encrypted__";function Cp(e){return typeof e=="object"&&e!==null&&$s in e&&e[$s]===true}function Ls(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[$s]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Ms.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Cp(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Ms.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Ms.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Rs=promisify(execFile),Ap=promisify(exec),tt=x("encryption:macos-keyvault"),Mr=class{static async isAvailable(){try{let{stdout:t}=await Ap("command -v security");return tt.debug(`security binary found at: ${t.trim()}`),!0}catch{return tt.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{tt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Rs("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return tt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return tt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{tt.debug(`Storing secret: service=${t}, account=${r}`),await Rs("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),tt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw tt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return tt.debug(`Deleting secret: service=${t}, account=${r}`),await Rs("security",["delete-generic-password","-a",r,"-s",t]),tt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return tt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}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\x0e-\x1f\x7f]/g,"")}function ce(e){process.stdout.write($.green(` \u2713 ${y(e)}
|
|
6
6
|
`));}function C(e){process.stderr.write($.red(` \u2717 ${y(e)}
|
|
7
7
|
`));}function E(e){process.stdout.write($.cyan(` \u2139 ${y(e)}
|
|
8
8
|
`));}function $r(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(c=>(c[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,c)=>l.padEnd(o[c])).join(" ");process.stdout.write(`
|
|
@@ -13,7 +13,7 @@ import {execa}from'execa';import Kl,{HTTPError}from'ky';import {Box,Text,render,
|
|
|
13
13
|
`);}function Lr(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
14
|
`);}function $e(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
15
|
`);}function Ve(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
-
`);}function Q(e){return e instanceof Error?e.message:String(e)}function Nt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var _s=promisify(execFile),Ds=promisify(exec),
|
|
16
|
+
`);}function Q(e){return e instanceof Error?e.message:String(e)}function Nt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var _s=promisify(execFile),Ds=promisify(exec),Rp=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],z=x("encryption:linux-keyvault");async function _p(e,t){let r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,o=setInterval(()=>{process.stderr.write(`\r${r[n++%r.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function Dp(e){let t=Ii.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Ut=class e{static async isAvailable(){try{let{stdout:t}=await Ds("command -v secret-tool");z.debug(`secret-tool found at: ${t.trim()}`);}catch{return z.debug("secret-tool binary not found in PATH"),false}try{return await _s("secret-tool",["lookup","service","__flow_connectivity_check__"]),z.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(z.debug(`Secret Service D-Bus not available: ${n}`),false):(z.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of Rp)try{return await Ds(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;z.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return z.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await Dp(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return z.info(`Running: ${t.command}`),await _p("Installing secret-tool...",()=>Ds(t.command)),e.isAvailable()}catch{return z.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{z.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await _s("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return z.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return z.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){z.debug(`Storing secret: service=${t}, account=${r}`),z.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),z.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),z.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(z.debug("secret-tool store succeeded"),o()):(z.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{z.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return z.debug(`Deleting secret: service=${t}, account=${r}`),await _s("secret-tool",["clear","service",t,"account",r]),z.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return z.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var Up=promisify(execFile),rt=x("encryption:windows-keyvault"),Os=1,Fp=1,Bp=2,jp=3;function Ns(e,t){return `${e}:${t}`}var Us=`
|
|
17
17
|
using System;
|
|
18
18
|
using System.Runtime.InteropServices;
|
|
19
19
|
using System.Text;
|
|
@@ -63,7 +63,7 @@ public class FlowCredManager {
|
|
|
63
63
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
64
64
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
65
65
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
66
|
-
int[] persistLevels = new int[] { ${
|
|
66
|
+
int[] persistLevels = new int[] { ${Bp}, ${jp}, ${Fp} };
|
|
67
67
|
int lastErr = 0;
|
|
68
68
|
try {
|
|
69
69
|
foreach (int persist in persistLevels) {
|
|
@@ -92,47 +92,47 @@ public class FlowCredManager {
|
|
|
92
92
|
return CredDelete(target, ${Os}, 0);
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
`;function un(e){return e.replace(/'/g,"''")}function Zn(e){return ["-NoProfile","-NonInteractive","-Command",e]}function
|
|
95
|
+
`;function un(e){return e.replace(/'/g,"''")}function Zn(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Kp(e){return `Add-Type -TypeDefinition @'
|
|
96
96
|
${Us}
|
|
97
97
|
'@
|
|
98
|
-
[FlowCredManager]::Read('${un(e)}')`}function
|
|
98
|
+
[FlowCredManager]::Read('${un(e)}')`}function Vp(e,t,r){return `Add-Type -TypeDefinition @'
|
|
99
99
|
${Us}
|
|
100
100
|
'@
|
|
101
|
-
[FlowCredManager]::Write('${un(e)}', '${un(t)}', '${un(r)}')`}function
|
|
101
|
+
[FlowCredManager]::Write('${un(e)}', '${un(t)}', '${un(r)}')`}function Hp(e){return `Add-Type -TypeDefinition @'
|
|
102
102
|
${Us}
|
|
103
103
|
'@
|
|
104
|
-
[FlowCredManager]::Delete('${un(e)}')`}async function Qn(e){return
|
|
105
|
-
`)[0]:"unknown error";return rt.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Ns(t,r);rt.debug(`Looking up secret: target=${n}`);let o=
|
|
106
|
-
`)[0]:"unknown error";return rt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Ns(t,r);rt.debug(`Storing secret: target=${o}`);let s=
|
|
107
|
-
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw rt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Ns(t,r);rt.debug(`Deleting secret: target=${n}`);let o=
|
|
108
|
-
`)[0]:"unknown error";return rt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var
|
|
104
|
+
[FlowCredManager]::Delete('${un(e)}')`}async function Qn(e){return Up("powershell.exe",e)}var Rr=class{static async isAvailable(){try{let{stdout:t}=await Qn(Zn('Write-Output "ok"')),r=t.trim()==="ok";return rt.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return rt.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Ns(t,r);rt.debug(`Looking up secret: target=${n}`);let o=Kp(n),{stdout:s}=await Qn(Zn(o)),i=s.trim();return rt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return rt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Ns(t,r);rt.debug(`Storing secret: target=${o}`);let s=Vp(o,n,r),{stdout:i}=await Qn(Zn(s)),a=i.trim();if(a.startsWith("OK:")){let c=a.split(":")[1];rt.debug(`CredWrite succeeded (persist=${c})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
+
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw rt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Ns(t,r);rt.debug(`Deleting secret: target=${n}`);let o=Hp(n),{stdout:s}=await Qn(Zn(o)),i=s.trim()==="True";return rt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return rt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var Jp=32,Gp="flow-plugins-cli-fallback",Bs="flow-plugins-cli-fallback",Wp={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function zp(){let e=`${Me.hostname()}${Me.userInfo().username}`;return kr.scryptSync(e,Gp,Jp)}function Xp(){let e=zp(),t=new sn(e),r=Ls(t);return new Fs({projectName:Bs,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var to=null;function eo(){return to||(to=Xp()),to}var Le=class{warned=false;async getSecret(t,r){return eo().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Wp[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=true;}eo().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=eo(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return eo().path}static hasExistingData(){try{let t=new Fs({projectName:Bs});return Ie.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Fs({projectName:Bs});Ie.rmSync(t.path,{force:!0});}catch{}to=null;}};async function js(){if(Le.hasExistingData())return new Le;switch(process.platform){case "darwin":return await Mr.isAvailable()?new Mr:new Le;case "linux":return await Ut.isAvailable()?new Ut:await Ut.ensureInstalled()?new Ut:new Le;case "win32":return await Rr.isAvailable()?new Rr:new Le;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Wp=x("config:credentials"),vt="flow-plugins-cli",Ks="credentials",Vs="token-cache",Hs="user-info",oo=null;async function Ft(){return oo||(oo=js()),oo}function so(){oo=null;}async function ne(){let t=await(await Ft()).getSecret(vt,Ks);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function bt(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 Wp.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ft()).setSecret(vt,Ks,JSON.stringify(e));}async function La(){let e=await Ft();await e.deleteSecret(vt,Ks),await e.deleteSecret(vt,Vs),await e.deleteSecret(vt,Hs);}async function Ra(){return (await Ft()).getStoragePath()}async function _a(e){await(await Ft()).setSecret(vt,Vs,JSON.stringify(e));}async function io(){let t=await(await Ft()).getSecret(vt,Vs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ao(e){await(await Ft()).setSecret(vt,Hs,JSON.stringify(e));}async function Da(){let t=await(await Ft()).getSecret(vt,Hs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Bt(){let e=await io();return e?new Date(e.expiresAt)>new Date:false}function lo(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")}}dn();var Gs=x("api:auth");function Zp(e){if(!or.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Na={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 Qp(e){if(e instanceof HTTPError){let t=e.response.status;Gs.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Na[r]?new Error(Na[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?(Gs.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Gs.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function lr(e){let t=_r("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Zp(e.tenant);let r;try{r=await Kl.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Qp(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await bt(e),await _a({accessToken:r.access_token,expiresAt:n});let o=lo(r.access_token);await ao({sub:o.sub,name:o.name,email:o.email});}var Ua=x("lib:tokenProvider");async function jt(){if(await Bt()){let n=await io();if(n)return n.accessToken}Ua.debug("Token expired or missing, re-authenticating...");let t=await ne();if(!t)throw new Error("Not authenticated. Run: flow auth login");Le.clearFallbackFile(),so(),await lr(t);let r=await io();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Ua.debug("Token refreshed successfully"),r.accessToken}dn();var co=x("api:metrics");function Fa(){return _r("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ba(e,t,r){return Kl.post(e,{json:t,headers:r})}async function tm(e){let t=await Da();if(t)return t;let r=lo(e),n={sub:r.sub,name:r.name,email:r.email};return await ao(n),n}async function P(e,t){let r=await jt(),n=await tm(r),o=await ne();if(!or.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:bs,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Ba(Fa(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),co.debug(`Metrics event sent: ${e}`);}catch(i){throw co.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function ja(e,t,r){try{let n=r&&or.test(r)?r:"unknown",o={action:e,booster:bs,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Ba(Fa(),o,{FlowTenant:n}),co.debug(`Anonymous metrics event sent: ${e}`);}catch(n){co.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var v={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"};var rm={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},nt={...rm};function Ka(e){let t=Date.now();nt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function cr(e){nt.currentStep=e,nt.stepStart=Date.now();}function G(){return {...nt}}function Pt(){return nt.sessionStart===0?0:Date.now()-nt.sessionStart}function ur(){return nt.stepStart===0?0:Date.now()-nt.stepStart}function Va(){nt.tuiSessionStart=Date.now();}function Ha(){return nt.tuiSessionStart===0?0:Date.now()-nt.tuiSessionStart}var nm=3e3,om=x("abandonment");async function uo(e){let{currentStep:t,sessionStart:r}=G();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Pt()};try{await Promise.race([P(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),nm))]);}catch(o){om.warn(`Abandonment event failed: ${String(o)}`);}}function Ja(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var sm=3e3,im=x("session-end");async function mn(e,t,r){let n=Ha(),s=[P(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(uo(e));try{await Ja(Promise.all(s).then(()=>{}),sm);}catch(i){im.warn(`Session end event failed: ${String(i)}`);}}var um=2e3;function Wa(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=w(l=>l.pendingExit),o=w(l=>l.setPendingExit),s=w(l=>l.activeTab),i=w(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),mn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},um);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var fm=16;function za({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,c)=>{if(c.backspace){let u=i.current.slice(0,-1);i.current=u,r(u);}else if(l&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let u=i.current+l;i.current=u,r(u);}},{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(fm)}),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]})})]})}var He=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function dr(){return me__default.join(Me__default.homedir(),".claude","settings.json")}function Xs(){let e=dr();if(!Ie__default.existsSync(e))return {status:"missing"};let t=Ie__default.readFileSync(e,"utf-8");try{let r=JSON.parse(t);return r===null||typeof r!="object"||Array.isArray(r)?{status:"malformed",raw:t}:{status:"ok",settings:r}}catch{return {status:"malformed",raw:t}}}function qa(e){let t=dr();Ie__default.mkdirSync(me__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 Ya(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function qs(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var wm=3600,pr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function xm(e){return Sm.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:wm})}function po(e,t={}){let r=Xs();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new pr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?qs(r.settings):null,s=xm(e),i=Ya(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function mo(e){qa(e.merged);}function Za(){let e=Xs();return e.status!=="ok"?false:qs(e.settings)!==null}var Qa="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Qa=e.version);}catch{}var ae=Qa;function Pm(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 ut=["clientId","clientSecret","tenant"],Em={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function tl(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,c]=useState(false),[u,d]=useState("fields"),[m,p]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:I}=He(),T=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),b=()=>{d("fields"),p(null),t(R=>({...R,clientSecret:""})),n("clientSecret");},M=async()=>{g.current=true;let R=T();try{await bt(R);}catch(H){a(H instanceof Error?H.message:"Failed to persist credentials"),b(),g.current=false;return}let{clientSecret:S,..._}=R;h(_),I(true),P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),hn({starterKit:_.starterKit});},k=async R=>{g.current=true;let S=T();try{mo(R),await bt(S);}catch(Z){a(Z instanceof Error?Z.message:"Failed to persist credentials"),b(),g.current=false;return}let{clientSecret:_,...H}=S;h(H),I(true),P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),hn({starterKit:H.starterKit});},F=R=>{try{return po(T(),{allowOverwriteMalformed:R})}catch(S){return S instanceof pr?(d("malformedConfirm"),null):(a(S instanceof Error?S.message:"Failed to read settings.json"),d("fields"),null)}};useInput((R,S)=>{if(!(l||g.current)){if(u==="preview"){S.return&&m?k(m):S.escape?M():R==="q"&&b();return}if(u==="malformedConfirm"){if(S.return){let _=F(true);_&&(p(_),k(_));}else S.escape&&b();return}if(S.shift&&S.tab){let _=ut.indexOf(r);_>0&&n(ut[_-1]);}else if(S.tab){let _=ut.indexOf(r);_<ut.length-1&&n(ut[_+1]);}else if(S.return)if(r==="tenant")J();else {let _=ut.indexOf(r);n(ut[_+1]);}}},{isActive:true});let J=async()=>{let R={};for(let S of ut)e[S].trim()||(R[S]="This field is required");if(Object.keys(R).length>0){s(R);let S=ut.find(_=>R[_]);S&&n(S);return}c(true),a(null),f.current+=1;try{await lr(T());let S=F(!1);S&&(p(S),d("preview"));}catch(S){let _=S instanceof Error?S.message:"Authentication failed";a(_),ja(v.CLI_AUTH_FAILED,{error_code:Pm(S),attempt:f.current},e.tenant.trim()).catch(()=>{}),t(H=>({...H,clientSecret:""}));}finally{c(false);}},Y=R=>S=>{t(_=>({..._,[R]:S})),o[R]&&s(_=>({..._,[R]:void 0}));};return u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Bn," \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:m.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),m.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"})]})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[Bn," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Bn," \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:ut.map(R=>jsx(Box,{marginBottom:1,children:jsx(za,{label:Em[R],value:e[R],onChange:Y(R),masked:R==="clientSecret",isActive:r===R&&!l,error:o[R]})},R))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Dr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Tm,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ae]})})]})}function km(){let e=ba();if(!Ie__default.existsSync(e))return {};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ys=null;function Am(){return Ys===null&&(Ys=km()),Ys}function Kt(){return !!Am().ENABLE_EXPERIMENTAL_BETAS}var oe=Kt()?["discover","installed","updates","marketplaces"]:["discover","installed","updates"];function Zs(e){return e==="marketplaces"?"marketplaces":"list"}function il(e,t,r){if(t.rightArrow||t.tab){let n=oe.indexOf(r.activeTab),o=oe[(n+1)%oe.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Zs(o)}]}if(t.leftArrow){let n=oe.indexOf(r.activeTab),o=oe[(n-1+oe.length)%oe.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Zs(o)}]}return t.downArrow?[{type:"setFocus",focus:Zs(r.activeTab)}]:[]}var cl={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ul({outdatedCount:e=0}){let t=w(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:oe.map(r=>{let n=r===t,o=r==="updates"&&e>0?`${cl[r]} (${e})`:cl[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Re=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function pl(){let e=w(i=>i.focus),t=Re(i=>i.query),r=Re(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..."})]})}var Rm=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...Tr[e]})),_m=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...ga[e]}));function ml(){let e=w(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Rm.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"]})]}),_m.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function fl({type:e}){let{label:t,color:r}=Tr[e];return jsx(Text,{color:r,children:t})}function hl({origin:e}){return e===nn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var go=Nm.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(fl,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(hl,{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 ",Nt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Or({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function xl({items:e,emptyMessage:t}){let r=w(l=>l.selectedIndex);if(e.length===0)return jsx(Or,{message:t});let n=Math.max(0,r-Math.floor(Be/2)),o=Math.min(e.length,n+Be);o===e.length&&(n=Math.max(0,o-Be));let 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,c)=>jsx(go,{item:l,isSelected:n+c===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function bl({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function El({groups:e,emptyMessage:t}){let r=w(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(Or,{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(Be/2)),c=Math.min(n.length,l+Be);c===n.length&&(l=Math.max(0,c-Be));let u=n.slice(l,c),d=l,m=n.length-c;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),u.map(p=>p.kind==="header"?jsx(bl,{label:p.label,pathHint:p.pathHint},p.key):jsx(go,{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 Jm={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Gm({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(pl,{}),jsx(ml,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Jm[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(El,{groups:n,emptyMessage:r}):jsx(xl,{items:e,emptyMessage:r})]})}function Cl({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=w(l=>l.activeTab),s=w(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(Gm,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Xm={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Plugin | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",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"};function yo(){let e=w(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:[Xm[e],t?" | Ctrl+D: debug log":""]})})}function Tl({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 ho({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nf,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function So({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 dt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=w(l=>l.focus),[i,a]=useState(0);return useInput((l,c)=>{c.upArrow?a(u=>u>0?u-1:u):c.downArrow?a(u=>u<t.length-1?u+1:u):c.return?n(t[i]):c.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,c)=>jsxs(Box,{children:[jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},c))})]})}var li=Object.entries(on),_l=[...li.map(([,e])=>e.actionLabel),"Cancel"],Dl=Object.fromEntries(li.map(([,e])=>[e.actionLabel,e.description]));function Ol(e){let t=li.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var cf=x("provider.registry"),uf=3e4,xo=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()+uf}),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"&&cf.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 df={user:"global",project:"project",local:"local"};function Io(e){return e?df[e]:"global"}var _e=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},Ht=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};dn();function Jt(){return Kl.create({prefix:_r("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await jt();e.headers.set("Authorization",`Bearer ${t}`);let r=await ne();r?.tenant&&or.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var mf=x("catalog.registry"),vo=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);mf.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()]}};var If={retries:5,minTimeout:50};async function ci(e,t){mkdirSync(dirname(e),{recursive:true});let r=await xf.lock(e+".lock",{realpath:false,retries:If});try{return await t()}finally{await r();}}var bo=class{filePath;constructor(t){this.filePath=t??va();}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 ci(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 ci(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ci(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));});}};var vf=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function xn(e){if(!e||!vf.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var bf=/^[^@]+@[^@]+$/;function Ur(e){return bf.test(e)}function Fr(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Pf=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Ef(e){if(!Pf.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 Br(e,t){let r=Fr(e);Ef(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Cf=/^[\w./:@?&=+#%-]+$/;function Po(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Cf.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Tf=x("catalog.flow-api"),Eo=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Jt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}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){xn(t);try{return await Jt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await Jt().head("v1/plugins/catalog"),Tf.debug("ping ok"),!0}catch{return false}}};var fe=new vo,Ct=new bo;fe.register(new Eo);var Jl=false;async function Gl(){if(Jl)return;Jl=true;let e=await Ct.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ui(),Hl));for(let r of e)fe.register(new t(r.id,r.name,r.source));}async function Gt(){return fe.fetchAll()}async function Wl(){return fe.fetchAllWithErrors()}async function Kr(e){xn(e);try{return await Jt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function zl(e){xn(e);try{let t=await Jt().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Co(){try{let{profiles:e}=await Jt().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}}async function Xl(e,t){let r=me.resolve(t);await pt.mkdir(r,{recursive:true});let n=me.join(me.dirname(r),`${randomUUID()}.zip`);try{await pt.writeFile(n,e),await Lf(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=me.resolve(r,o.fileName);if(!i.startsWith(r+me.sep)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(me.resolve(me.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await pt.unlink(n);}catch{}}}async function di(e){await pt.rm(e,{recursive:true,force:true});}async function Wt(){let e=xa();await pt.mkdir(me.dirname(e),{recursive:true});try{await pt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await xf.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Df(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:re,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Zl(){let e=Vn();if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return null}}function Of(){let e=Zl();if(e)return e;let t=Df(),r=Vn();return Ie__default.mkdirSync(me__default.dirname(r),{recursive:true}),pi(t),t}function pi(e){let t=Vn(),r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function Nf(){let e=Hn(),t={};try{Ie__default.existsSync(e)&&(t=JSON.parse(Ie__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[re])return;t[re]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:wa(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}function Ql(e,t){To(e.name),Nf();let r=Cs(e.name);Ie__default.mkdirSync(me__default.dirname(r),{recursive:true});try{Ie__default.lstatSync(r),Ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}Ie__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Of();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),pi(n));}function mi(e){To(e);let t=Cs(e);try{Ie__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Zl();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&pi(r);}var Ff=x("mcpConfigReader"),Bf=500,jf=512;function Kf(){return me__default.join(Me__default.homedir(),".claude.json")}function Vf(){return me__default.join(process.cwd(),".mcp.json")}function tc(e){if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return Ff.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fi(e){if(!In(e))return {};let t=e.mcpServers;return In(t)?t:{}}function gi(e,t){return Object.keys(e).slice(0,Bf).map(n=>({name:y(n.slice(0,jf)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function nc(){let e=[],t=Kf(),r=tc(t);if(In(r)){let a=r,l=fi(a);e.push(...gi(l,"user"));let c=process.cwd();if(In(a.projects)){let u=a.projects[c];if(In(u)){let d=fi(u);e.push(...gi(d,"local"));}}}let n=Vf(),o=tc(n),s=fi(o);e.push(...gi(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var We=x("storage");async function Jf(e,t){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:G().interfaceType});}catch(r){We.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function Gf(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:G().interfaceType}).catch(o=>We.warn(`Failed to send ${t} metrics: ${String(o)}`));}function wi(){return me__default.join(Me__default.homedir(),".claude","plugins","installed_plugins.json")}function Wf(){return me__default.join(Me__default.homedir(),".claude","plugins")}function oc(e){let t=me__default.resolve(e),r=me__default.resolve(Wf()),n=me__default.resolve(me__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+me__default.sep)||t===r,s=t.startsWith(n+me__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function sc(e="user"){return e==="local"?me__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?me__default.join(process.cwd(),".claude","settings.json"):me__default.join(Me__default.homedir(),".claude","settings.json")}function kt(){let e=wi();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 ic(){let e=wi();try{let t=await Ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function zf(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function ac(e,t){try{Ie__default.mkdirSync(me__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 zf(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Tt(e){ac(wi(),e);}function vn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Xf(e,t){let r=me__default.join(e,".claude-plugin"),n=me__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=me__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 xi(e="user"){let t=sc(e);if(!Ie__default.existsSync(t))return {};try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function lc(e,t="user"){ac(sc(t),e);}function qf(e,t){let{name:r,marketplace:n}=vn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vn(i).name===r)[0],!o)throw We.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Yf(e,t){let{name:r,marketplace:n}=vn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vn(i).name===r)[0],o?{key:o,name:r}:null}function yi(e="user"){return xi(e).enabledPlugins??{}}function hi(e,t="user"){let r=xi(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,lc(r,t);}function bn(e,t,r="user"){let n=xi(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},lc(n,r);}function Zf(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function se(){let e=kt(),t=yi(),r=yi("project"),n=yi("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=vn(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Zf(p).map(g=>{let h=Xf(g.installPath,d),T=(o[g.scope]??t)[c];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:T===false?"disabled":"enabled"}})}),i=nc(),a=new Set(s.map(c=>`${c.name}@${c.scope}`)),l=i.filter(c=>!a.has(`${c.name}@${c.scope}`));return [...s,...l]}async function ko(e,t){We.debug(`[${e}] Acquiring lock to uninstall`);let r=await Wt();try{let n=kt(),o=Yf(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`);We.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),oc(l.installPath);let c=me__default.dirname(l.installPath);We.debug(`[${i}] Removing directory: ${c}`),Ie__default.rmSync(c,{recursive:!0,force:!0});let u=a.filter(d=>d.scope!==t);if(u.length===0){let{[s]:d,...m}=n.plugins;Tt({...n,plugins:m}),hi(s,t),mi(i);}else n.plugins[s]=u,Tt(n),hi(s,t);}else {We.debug(`[${i}] Resolved key: ${s}`);for(let u of a){oc(u.installPath);let d=me__default.dirname(u.installPath);We.debug(`[${i}] Removing directory: ${d}`),Ie__default.rmSync(d,{recursive:!0,force:!0}),hi(s,u.scope);}mi(i);let{[s]:l,...c}=n.plugins;Tt({...n,plugins:c});}await Jf(i,a[0].origin??"internal"),We.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Pn(e,t,r){We.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Wt();try{let o=kt(),{key:s,name:i}=qf(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";We.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),bn(s,t==="enabled",l),Gf(i,t,c),We.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Qf=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,eg=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function To(e){if(!Qf.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function tg(e){if(!eg.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 zt=x("installer");function rg(e,t){let r=`${e}@${re}`,o=kt().plugins[r];if(o&&!t)throw new _e(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function ng(e,t,r){r&&await di(t);try{zt.debug(`[${t}] Extracting archive...`),await Xl(e,t);}catch(n){throw await di(t),n}}function og(e,t,r,n,o,s="claude-code"){let i=kt(),a={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s},l=i.plugins[e]??[];i.plugins[e]=[...l.filter(c=>c.scope!==n),a],Tt(i),bn(e,true,n);}async function sg(e,t,r,n,o){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:G().interfaceType});}catch(s){zt.warn(`Failed to send install metrics: ${String(s)}`);}}async function ig(e,t,r){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:G().interfaceType});}catch(n){zt.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function be(e,t={}){let r=Date.now(),n=null;try{zt.debug(`[${e}] Acquiring lock...`),n=await Wt();let{pluginKey:o,alreadyInstalled:s}=rg(e,t.force);zt.debug(`[${e}] Fetching manifest...`);let i=await Kr(e);To(i.name),tg(i.version),zt.debug(`[${e}] Downloading archive...`);let a=await zl(e),l=t.scope??"user",c=Sa(i.name,i.version);await ng(a,c,!!s&&!!t.force),og(o,c,i.version,l,"internal",t.providerId),Ql(i,c);let u=Date.now()-r;zt.debug(`[${e}] Installed successfully in ${u}ms`);let d={name:i.name,version:i.version,path:c,duration_ms:u};return t.skipMetrics||await sg(i.name,i.version,u,Io(l),"internal"),d}catch(o){throw await ig(e,o,"internal"),zt.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var ag=x("commands:helpers");async function Se(){let e=await ne();if(!e)return C("Not authenticated. Run: flow auth login"),false;try{await jt();}catch(t){return ag.debug(`Token validation failed: ${String(t)}`),C("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(C("Starter kit not set. Run: flow auth login"),false):true}async function Xt(e){let t=Ii.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 cc(e){let t=Ii.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var En=x("claudeProxy"),Pi="claude ",uc="flow ",vi=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},bi=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";}},lg=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,cg=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,ug=/^(flow|claude)\s+auth\s+login(\s|$)/;function dg(e){pc(e);let t=e.slice(Pi.length);if(!lg.test(t))throw new bi(e)}var Ao=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function pc(e){if(!e||!/^claude /.test(e))throw new vi(e)}async function we(e){pc(e);let t=e.slice(Pi.length).split(/\s+/).filter(Boolean),r=pg(t);En.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 En.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 mc(o)?new Ao:o}}function pg(e){return e.length>=3?e[2]:e.join(" ")}function mc(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function mg(e){return e.startsWith(uc)?Pi+e.slice(uc.length):e}function fg(e){return cg.test(e)||ug.test(e)}function gg(e){let t=0;for(;t<e.length&&fg(e[t]);)t++;return e.slice(t)}var yg=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function hg(e,t){return !t||e.includes("--scope")||!yg.test(e)?e:`${e} --scope ${t}`}async function Ei(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=gg(r).map(i=>mg(i)).map(i=>hg(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)dg(i);En.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await we(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await we(o[i]),s.exitCode!==0)return s;return s}async function Mo(e,t,r){let n=Fr(e),o=t?.trim();if(!o&&(o=(await cc(`Plugin "${n}" could not be installed.
|
|
111
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Po(o),r?.(),En.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"}`);En.debug(`[${n}] Marketplace added successfully`);}catch(s){throw
|
|
112
|
-
`)}function vc(){return {async install(e,t){let r=e.catalogId?fe.getAdapter(e.catalogId):void 0,n=$o(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Yt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Jn(t.scope??"user"),a=join(s,".opencode","plugins");if(Ie__default.existsSync(a)){let l=Ie__default.readdirSync(a).filter(c=>c.endsWith(".js")||c.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`),Dg(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 Zt(o).catch(()=>{});}},async uninstall(e,t){let r=Jn(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(Jn(t),`${e}.js`)}}}var Do=class{id="opencode";name="OpenCode";async isAvailable(){return wr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:_g,skill:vc(),plugin:vc()}};var mt=new xo;mt.register(new Lo);Kt()&&(mt.register(new _o),mt.register(new Do));function bc({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,c]=useState([]),[u,d]=useState(void 0);useEffect(()=>{mt.getAvailableProviders(t??"plugin").then(c).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let I=l.find(T=>T.name===h);I?(d(I.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let I=Ol(h);I?r(I,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(I=>I.name),"Cancel"];return jsx(dt,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(dt,{itemName:`${e} \u2014 Choose scope`,actions:_l,descriptions:Dl,onAction:f,onClose:g},"scope"):jsx(dt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Uo({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=w(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")}}function Cc({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=Uo({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(c)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(dt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function Ac({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Uo({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(dt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var ge=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:se()})}));function Mc({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,c=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}),c&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Nt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function $c({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:c,stored:u}=e,d=c.removable!==false,m=u?.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:c.name}),jsx(Text,{dimColor:true,children:c.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`:"",u?.lastUpdated?` \xB7 Updated ${Nt(u.lastUpdated)}`:""]})}),u&&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((g,h)=>{let I=h===o;return jsxs(Box,{children:[jsx(Text,{color:I?"cyan":void 0,children:I?"\u203A ":" "}),jsx(Text,{bold:I,color:g.danger?"yellow":void 0,dimColor:!I,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Lc(e){return e.adapter.removable!==false?4:2}function Rc({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((c,u)=>{if(u.escape){n();return}if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(i.length-1,d+1));return}u.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((c,u)=>jsxs(Box,{children:[jsx(Text,{color:u===a?"cyan":void 0,children:u===a?"\u203A ":" "}),jsx(Text,{bold:u===a,color:c.danger?"yellow":void 0,dimColor:u!==a,children:c.label})]},c.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Dc({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 Oc({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(k=>r.has(`${k.name}@${o}`)),i=t.filter(k=>!r.has(`${k.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((k,F)=>{if(F.escape){n();return}if(F.return){d(a[l]??null);return}if(F.upArrow){c(J=>Math.max(0,J-1));return}F.downArrow&&c(J=>Math.min(a.length-1,J+1));},{isActive:u===null}),u!==null)return jsx(Rc,{item:u,adapterName:e.adapter.name,isInstalled:r.has(`${u.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(Be/2)),p=Math.min(a.length,m+Be);p===a.length&&(m=Math.max(0,p-Be));let f=a.slice(m,p),g=m,h=a.length-p,I=s.length>0&&m<s.length,T=p>s.length,b=f.filter(k=>r.has(`${k.name}@${o}`)),M=f.filter(k=>!r.has(`${k.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:g>0?`\u2191 ${g} more above`:" "})}),I&&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"]}),b.map(k=>jsx(Dc,{item:k,isSelected:a.indexOf(k)===l,isInstalled:true},k.name))]}),T&&jsxs(Box,{flexDirection:"column",marginTop:I?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),M.map(k=>jsx(Dc,{item:k,isSelected:a.indexOf(k)===l,isInstalled:false},k.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ui();var Hg=/^https?:\/\/.+/;function Jg(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Gg(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Bc(e){let t=w(h=>h.showNotification),r=w(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[c,u]=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(""),u(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,I=d.current;if(!Hg.test(h)){u("URL must start with http:// or https://");return}u(null),o("adding");let T=randomUUID(),b=new jr(T,I,h);try{await b.fetchItems(),await Ct.add({id:T,name:I,source:h}),fe.register(new jr(T,I,h)),r(),e(),t(`Catalog "${I}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let k=Jg(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Gg(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(k,"error"),o("add-url");}},[e,t,r]);return useInput((h,I)=>{if(I.escape){o("idle");return}if(I.return){d.current.trim().length>0&&o("add-url");return}if(I.backspace||I.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!I.ctrl&&!I.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,I)=>{if(I.escape){o("add-name");return}if(I.return){g();return}if(I.backspace||I.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}h&&!I.ctrl&&!I.meta&&(m.current=m.current+h,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function jc(e){let t=w(o=>o.showNotification),r=w(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Ct.remove(o),fe.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 Vc(){let e=w(A=>A.focus),t=w(A=>A.setFocus),r=w(A=>A.setActiveTab),n=w(A=>A.showNotification),o=ge(A=>A.installedItems),[s,i]=useState(()=>fe.listAdapters().map(A=>({adapter:A,stored:null}))),[a,l]=useState(0),[c,u]=useState("list"),[d,m]=useState(0),[p,f]=useState(null),[g,h]=useState("main"),I=useRef(s);useEffect(()=>{I.current=s;},[s]),useEffect(()=>{g==="browse"&&!s[a-1]&&h("main");},[g,s,a]);let T=useCallback(()=>{(async()=>{let A=fe.listAdapters(),O=await Ct.read(),B=new Map(O.map(N=>[N.id,N]));i(A.map(N=>({adapter:N,stored:B.get(N.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),T();},[t,T]),useEffect(()=>{if(a===0){f(null);return}let A=I.current[a-1];if(!A)return;let O=false;return f({items:[],loading:true,error:null}),A.adapter.fetchItems().then(B=>{O||f({items:B,loading:false,error:null});}).catch(B=>{O||f({items:[],loading:false,error:B instanceof Error?B.message:"Failed to load catalog"});}),()=>{O=true;}},[a]);let b=Bc(T),M=useCallback(()=>{T(),l(0),u("list"),f(null),h("main");},[T]),{handleRemove:k}=jc(M),F=useCallback(async A=>{h("removing"),await k(A);},[k]),J=useCallback(async A=>{try{let O=await A.adapter.fetchItems();if(f({items:O,loading:!1,error:null}),A.stored){let B=new Date().toISOString();await Ct.updateField(A.stored.id,{lastUpdated:B}),T();}n("Marketplace updated","success");}catch(O){n(O instanceof Error?O.message:"Update failed","error");}},[T,n]),Y=useCallback(async A=>{if(!A.stored)return;let O=A.stored.autoUpdate!==false;await Ct.updateField(A.stored.id,{autoUpdate:!O}),T();},[T]),R=useCallback(()=>h("browse"),[]),S=useCallback(A=>{let O=s[a-1];if(!O)return;let B=O.adapter.removable!==false;[R,()=>{J(O);},...B?[()=>{Y(O);},()=>{F(O.adapter.id);}]:[]][A]?.();},[s,a,R,J,Y,F]),_=useCallback(()=>h("main"),[]),H=useCallback(()=>{let A=s[a-1];A&&J(A);},[s,a,J]),Z=useCallback(()=>{let A=s[a-1];A&&Y(A);},[s,a,Y]),rn=useCallback(()=>{let A=s[a-1];A&&F(A.adapter.id);},[s,a,F]);if(useInput((A,O)=>{if(O.upArrow){l(B=>Math.max(0,B-1));return}if(O.downArrow){l(B=>Math.min(s.length,B+1));return}if(O.leftArrow||O.rightArrow){let B=["discover","installed","marketplaces"],N=B.indexOf("marketplaces"),Is=O.leftArrow?B[(N-1+B.length)%B.length]:B[(N+1)%B.length];r(Is),t("list");return}(O.return||O.tab)&&(a===0?b.startAdd():(u("detail"),m(0)));},{isActive:g==="main"&&b.phase==="idle"&&c==="list"&&e==="marketplaces"}),useInput((A,O)=>{if(O.escape||O.tab){u("list");return}if(O.upArrow){m(B=>Math.max(0,B-1));return}if(O.downArrow){let B=s[a-1],N=B?Lc(B)-1:0;m(Is=>Math.min(Is+1,N));return}O.return&&S(d);},{isActive:g==="main"&&b.phase==="idle"&&c==="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(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let A=s[a-1];if(!A)return jsx(Box,{});let O=A.adapter.id??"default",B=new Set(o.filter(N=>N.marketplace===A.adapter.name).map(N=>`${N.name}@${O}`));return jsx(Oc,{entry:A,items:p?.items??[],installedKeys:B,onBack:_})}if(s.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 It=s[a-1]??null,Fn=It?o.filter(A=>A.marketplace===It.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Mc,{entries:s,selectedIndex:a,focusPanel:c})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:c==="detail"&&It?jsx($c,{entry:It,detailData:p,installedCount:Fn,focusPanel:c,actionIndex:d,onBrowse:R,onUpdate:H,onToggleAutoUpdate:Z,onRemove:rn}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:It?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:c==="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 Hc(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=oe.indexOf(r.activeTab),s=oe[(o-1+oe.length)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.rightArrow){let o=oe.indexOf(r.activeTab),s=oe[(o+1)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.tab){let o=oe.indexOf(r.activeTab),s=oe[(o+1)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="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 Jc(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Gc(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function Ho(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=w.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:c}=Re.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?w.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?w.getState().selectAllTypes():s.type==="toggleOriginFilter"?w.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&w.getState().selectAllOrigins();}function Wc({listLength:e}){let t=w(g=>g.focus),r=w(g=>g.selectedIndex),n=w(g=>g.actionMenuOpen),o=w(g=>g.setFocus),s=w(g=>g.setActionMenuOpen),i=Re(g=>g.query),a=Re(g=>g.setQuery),l=Re(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Re.getState();h(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:I,selectedIndex:T,actionMenuOpen:b}=w.getState();Ho(il(g,h,{activeTab:I}));},{isActive:t==="tabs"}),useInput((g,h)=>{let{activeTab:I,selectedIndex:T,actionMenuOpen:b}=w.getState();Ho(Hc(g,h,{activeTab:I,selectedIndex:T},c.current));},{isActive:t==="list"}),useInput((g,h)=>{Ho(Jc(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let I=Gc(g,h,Re.getState().query),T=I.queryUpdate;if(Ho(I.actions),T==="reset")l(),d("");else if(T!==null){let{query:b,cursorPosition:M,setCursorPosition:k}=Re.getState();if("backspace"in T)M>0&&(a(b.slice(0,M-1)+b.slice(M)),k(M-1));else if("append"in T)a(b.slice(0,M)+T.append+b.slice(M)),k(M+T.append.length);else if("cursorMove"in T){let F=M+T.cursorMove;F>=0&&F<=b.length&&k(F);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:I}=w.getState();g===0?h(0):I>=g&&h(g-1);},[]),f=useCallback(g=>{if(!u)return c.current=g.length,g;let h=u.toLowerCase(),I=g.filter(T=>T.name.toLowerCase().includes(h)||T.description?.toLowerCase().includes(h));return c.current=I.length,I},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Xc(){let e=w(a=>a.notification),t=w(a=>a.showNotification),r=w(a=>a.clearNotification),n=He(a=>a.justAuthenticated),o=He(a=>a.credentials),s=He(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 Ee(e,t,r=false){return r?true:!$i.valid(e)||!$i.valid(t)?false:$i.gt(t,e)}var $t=x("updater");async function Yg(e,t,r,n,o){try{await P(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:G().interfaceType});}catch(s){$t.warn(`Failed to send update metrics: ${String(s)}`);}}function Zg(e){let t=kt(),r=`${e}@${re}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Jo(e,t={}){let r=Date.now(),n=null;try{$t.debug(`[${e}] Acquiring lock...`),n=await Wt();let o=Zg(e);if(!o)throw $t.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;$t.debug(`[${e}] Fetching manifest...`);let c=(await Kr(e)).version;if(!i||!Ee(i,c,t.force))throw $t.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Ht(e,i??"unknown");$t.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await be(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Yg(u.name,i,u.version,d,s.origin??"internal"),$t.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){$t.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Wt();let d=kt(),m=`${e}@${re}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Tt(d),$t.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var Go=x("dispatcher");async function Qg(e,t,r,n,o){let s=Fr(e);return Go.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Mo(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Go.debug(`[${e}] Retrying install after marketplace add`),we(t)}async function qc(e,t,r,n){let o=Br(e,n),s=Fr(e);r?.onStatus?.(`Installing ${s}...`),Go.debug(`[${e}] Attempting install: ${o}`);let i=await we(o);if(i.exitCode===0)return i;Go.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Qg(e,o,a,t,r)}async function Yc(e,t,r){let n=e.type??"plugin",o=await mt.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 Zc(){let e=ge(i=>i.installedItems),t=ge(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Yc(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),c=l?.providerId??"claude-code",u=mt.getAdapter(c);if(!u)throw new Error(`Provider "${c}" not found`);let d=l?.type??"plugin",m=u.installers[d];if(!m)throw new Error(`Provider "${c}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let c=e.find(u=>u.name===i)?.status==="enabled"?"disabled":"enabled";await Pn(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Jo(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var zo=x("mcp");function $n(e,t){e.silent?Ve({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):C(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function eu(e,t){e.silent?$e({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ce(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&E(t.stdout));}function ey(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 Li(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 tu(e,t,r){if(!await Se())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return $n(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}zo.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=ey(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Xt(`Install external MCP "${s}"?
|
|
110
|
+
`),this.warned=true;}eo().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=eo(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return eo().path}static hasExistingData(){try{let t=new Fs({projectName:Bs});return Ie.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Fs({projectName:Bs});Ie.rmSync(t.path,{force:!0});}catch{}to=null;}};async function js(){if(Le.hasExistingData())return new Le;switch(process.platform){case "darwin":return await Mr.isAvailable()?new Mr:new Le;case "linux":return await Ut.isAvailable()?new Ut:await Ut.ensureInstalled()?new Ut:new Le;case "win32":return await Rr.isAvailable()?new Rr:new Le;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var qp=x("config:credentials"),vt="flow-plugins-cli",Ks="credentials",Vs="token-cache",Hs="user-info",oo=null;async function Ft(){return oo||(oo=js()),oo}function so(){oo=null;}async function ne(){let t=await(await Ft()).getSecret(vt,Ks);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function bt(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 qp.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ft()).setSecret(vt,Ks,JSON.stringify(e));}async function Ra(){let e=await Ft();await e.deleteSecret(vt,Ks),await e.deleteSecret(vt,Vs),await e.deleteSecret(vt,Hs);}async function _a(){return (await Ft()).getStoragePath()}async function Da(e){await(await Ft()).setSecret(vt,Vs,JSON.stringify(e));}async function io(){let t=await(await Ft()).getSecret(vt,Vs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ao(e){await(await Ft()).setSecret(vt,Hs,JSON.stringify(e));}async function Oa(){let t=await(await Ft()).getSecret(vt,Hs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Bt(){let e=await io();return e?new Date(e.expiresAt)>new Date:false}function lo(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")}}dn();var Gs=x("api:auth");function tm(e){if(!or.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ua={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 rm(e){if(e instanceof HTTPError){let t=e.response.status;Gs.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Ua[r]?new Error(Ua[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?(Gs.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Gs.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function lr(e){let t=_r("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");tm(e.tenant);let r;try{r=await Vl.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await rm(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await bt(e),await Da({accessToken:r.access_token,expiresAt:n});let o=lo(r.access_token);await ao({sub:o.sub,name:o.name,email:o.email});}var Fa=x("lib:tokenProvider");async function jt(){if(await Bt()){let n=await io();if(n)return n.accessToken}Fa.debug("Token expired or missing, re-authenticating...");let t=await ne();if(!t)throw new Error("Not authenticated. Run: flow auth login");Le.clearFallbackFile(),so(),await lr(t);let r=await io();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Fa.debug("Token refreshed successfully"),r.accessToken}dn();var co=x("api:metrics");function Ba(){return _r("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ja(e,t,r){return Vl.post(e,{json:t,headers:r})}async function om(e){let t=await Oa();if(t)return t;let r=lo(e),n={sub:r.sub,name:r.name,email:r.email};return await ao(n),n}async function P(e,t){let r=await jt(),n=await om(r),o=await ne();if(!or.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:bs,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await ja(Ba(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),co.debug(`Metrics event sent: ${e}`);}catch(i){throw co.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Ka(e,t,r){try{let n=r&&or.test(r)?r:"unknown",o={action:e,booster:bs,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ja(Ba(),o,{FlowTenant:n}),co.debug(`Anonymous metrics event sent: ${e}`);}catch(n){co.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var v={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"};var sm={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},nt={...sm};function Va(e){let t=Date.now();nt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function cr(e){nt.currentStep=e,nt.stepStart=Date.now();}function G(){return {...nt}}function Pt(){return nt.sessionStart===0?0:Date.now()-nt.sessionStart}function ur(){return nt.stepStart===0?0:Date.now()-nt.stepStart}function Ha(){nt.tuiSessionStart=Date.now();}function Ja(){return nt.tuiSessionStart===0?0:Date.now()-nt.tuiSessionStart}var im=3e3,am=x("abandonment");async function uo(e){let{currentStep:t,sessionStart:r}=G();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Pt()};try{await Promise.race([P(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),im))]);}catch(o){am.warn(`Abandonment event failed: ${String(o)}`);}}function Ga(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var lm=3e3,cm=x("session-end");async function mn(e,t,r){let n=Ja(),s=[P(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(uo(e));try{await Ga(Promise.all(s).then(()=>{}),lm);}catch(i){cm.warn(`Session end event failed: ${String(i)}`);}}var mm=2e3;function za(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=w(l=>l.pendingExit),o=w(l=>l.setPendingExit),s=w(l=>l.activeTab),i=w(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),mn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},mm);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var hm=16;function Xa({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,c)=>{if(c.backspace){let u=i.current.slice(0,-1);i.current=u,r(u);}else if(l&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let u=i.current+l;i.current=u,r(u);}},{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(hm)}),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]})})]})}var He=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function dr(){return me__default.join(Me__default.homedir(),".claude","settings.json")}function Xs(){let e=dr();if(!Ie__default.existsSync(e))return {status:"missing"};let t=Ie__default.readFileSync(e,"utf-8");try{let r=JSON.parse(t);return r===null||typeof r!="object"||Array.isArray(r)?{status:"malformed",raw:t}:{status:"ok",settings:r}}catch{return {status:"malformed",raw:t}}}function Ya(e){let t=dr();Ie__default.mkdirSync(me__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 Za(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function qs(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var vm=3600,pr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function bm(e){return Im.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:vm})}function po(e,t={}){let r=Xs();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new pr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?qs(r.settings):null,s=bm(e),i=Za(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function mo(e){Ya(e.merged);}function Qa(){let e=Xs();return e.status!=="ok"?false:qs(e.settings)!==null}var el="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(el=e.version);}catch{}var ae=el;function Tm(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 ut=["clientId","clientSecret","tenant"],km={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function rl(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,c]=useState(false),[u,d]=useState("fields"),[m,p]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:I}=He(),T=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),b=()=>{d("fields"),p(null),t(R=>({...R,clientSecret:""})),n("clientSecret");},M=async()=>{g.current=true;let R=T();try{await bt(R);}catch(H){a(H instanceof Error?H.message:"Failed to persist credentials"),b(),g.current=false;return}let{clientSecret:S,..._}=R;h(_),I(true),P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),hn({starterKit:_.starterKit});},k=async R=>{g.current=true;let S=T();try{mo(R),await bt(S);}catch(Z){a(Z instanceof Error?Z.message:"Failed to persist credentials"),b(),g.current=false;return}let{clientSecret:_,...H}=S;h(H),I(true),P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),hn({starterKit:H.starterKit});},F=R=>{try{return po(T(),{allowOverwriteMalformed:R})}catch(S){return S instanceof pr?(d("malformedConfirm"),null):(a(S instanceof Error?S.message:"Failed to read settings.json"),d("fields"),null)}};useInput((R,S)=>{if(!(l||g.current)){if(u==="preview"){S.return&&m?k(m):S.escape?M():R==="q"&&b();return}if(u==="malformedConfirm"){if(S.return){let _=F(true);_&&(p(_),k(_));}else S.escape&&b();return}if(S.shift&&S.tab){let _=ut.indexOf(r);_>0&&n(ut[_-1]);}else if(S.tab){let _=ut.indexOf(r);_<ut.length-1&&n(ut[_+1]);}else if(S.return)if(r==="tenant")J();else {let _=ut.indexOf(r);n(ut[_+1]);}}},{isActive:true});let J=async()=>{let R={};for(let S of ut)e[S].trim()||(R[S]="This field is required");if(Object.keys(R).length>0){s(R);let S=ut.find(_=>R[_]);S&&n(S);return}c(true),a(null),f.current+=1;try{await lr(T());let S=F(!1);S&&(p(S),d("preview"));}catch(S){let _=S instanceof Error?S.message:"Authentication failed";a(_),Ka(v.CLI_AUTH_FAILED,{error_code:Tm(S),attempt:f.current},e.tenant.trim()).catch(()=>{}),t(H=>({...H,clientSecret:""}));}finally{c(false);}},Y=R=>S=>{t(_=>({..._,[R]:S})),o[R]&&s(_=>({..._,[R]:void 0}));};return u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Bn," \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:m.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),m.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"})]})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[Bn," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Bn," \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:ut.map(R=>jsx(Box,{marginBottom:1,children:jsx(Xa,{label:km[R],value:e[R],onChange:Y(R),masked:R==="clientSecret",isActive:r===R&&!l,error:o[R]})},R))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Dr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Mm,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ae]})})]})}function $m(){let e=Pa();if(!Ie__default.existsSync(e))return {};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ys=null;function Lm(){return Ys===null&&(Ys=$m()),Ys}function Kt(){return !!Lm().ENABLE_EXPERIMENTAL_BETAS}var oe=Kt()?["discover","installed","updates","marketplaces"]:["discover","installed","updates"];function Zs(e){return e==="marketplaces"?"marketplaces":"list"}function al(e,t,r){if(t.rightArrow||t.tab){let n=oe.indexOf(r.activeTab),o=oe[(n+1)%oe.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Zs(o)}]}if(t.leftArrow){let n=oe.indexOf(r.activeTab),o=oe[(n-1+oe.length)%oe.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Zs(o)}]}return t.downArrow?[{type:"setFocus",focus:Zs(r.activeTab)}]:[]}var ul={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function dl({outdatedCount:e=0}){let t=w(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:oe.map(r=>{let n=r===t,o=r==="updates"&&e>0?`${ul[r]} (${e})`:ul[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Re=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function ml(){let e=w(i=>i.focus),t=Re(i=>i.query),r=Re(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..."})]})}var Om=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...Tr[e]})),Nm=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...ya[e]}));function fl(){let e=w(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("plugin"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Om.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"]})]}),Nm.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function gl({type:e}){let{label:t,color:r}=Tr[e];return jsx(Text,{color:r,children:t})}function Sl({origin:e}){return e===nn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var go=Bm.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(gl,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Sl,{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 ",Nt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Or({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Il({items:e,emptyMessage:t}){let r=w(l=>l.selectedIndex);if(e.length===0)return jsx(Or,{message:t});let n=Math.max(0,r-Math.floor(Be/2)),o=Math.min(e.length,n+Be);o===e.length&&(n=Math.max(0,o-Be));let 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,c)=>jsx(go,{item:l,isSelected:n+c===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Pl({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Cl({groups:e,emptyMessage:t}){let r=w(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(Or,{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(Be/2)),c=Math.min(n.length,l+Be);c===n.length&&(l=Math.max(0,c-Be));let u=n.slice(l,c),d=l,m=n.length-c;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),u.map(p=>p.kind==="header"?jsx(Pl,{label:p.label,pathHint:p.pathHint},p.key):jsx(go,{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 zm={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Xm({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(ml,{}),jsx(fl,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:zm[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Cl,{groups:n,emptyMessage:r}):jsx(Il,{items:e,emptyMessage:r})]})}function Tl({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=w(l=>l.activeTab),s=w(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(Xm,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Zm={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Plugin | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",bundleDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",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"};function yo(){let e=w(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:[Zm[e],t?" | Ctrl+D: debug log":""]})})}function kl({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 ho({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(af,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function So({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 dt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=w(l=>l.focus),[i,a]=useState(0);return useInput((l,c)=>{c.upArrow?a(u=>u>0?u-1:u):c.downArrow?a(u=>u<t.length-1?u+1:u):c.return?n(t[i]):c.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,c)=>jsxs(Box,{children:[jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},c))})]})}var li=Object.entries(on),Dl=[...li.map(([,e])=>e.actionLabel),"Cancel"],Ol=Object.fromEntries(li.map(([,e])=>[e.actionLabel,e.description]));function Nl(e){let t=li.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var pf=x("provider.registry"),mf=3e4,xo=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()+mf}),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"&&pf.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 ff={user:"global",project:"project",local:"local"};function Io(e){return e?ff[e]:"global"}var _e=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},Ht=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};dn();function Jt(){return Vl.create({prefix:_r("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await jt();e.headers.set("Authorization",`Bearer ${t}`);let r=await ne();r?.tenant&&or.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var yf=x("catalog.registry"),vo=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);yf.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()]}};var Pf={retries:5,minTimeout:50};async function ci(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bf.lock(e+".lock",{realpath:false,retries:Pf});try{return await t()}finally{await r();}}var bo=class{filePath;constructor(t){this.filePath=t??ba();}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 ci(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 ci(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ci(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));});}};var Ef=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function xn(e){if(!e||!Ef.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var Cf=/^[^@]+@[^@]+$/;function Ur(e){return Cf.test(e)}function Fr(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Tf=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function kf(e){if(!Tf.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 Br(e,t){let r=Fr(e);kf(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Af=/^[\w./:@?&=+#%-]+$/;function Po(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Af.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Mf=x("catalog.flow-api"),Eo=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Jt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}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){xn(t);try{return await Jt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await Jt().head("v1/plugins/catalog"),Mf.debug("ping ok"),!0}catch{return false}}};var fe=new vo,Ct=new bo;fe.register(new Eo);var Gl=false;async function Wl(){if(Gl)return;Gl=true;let e=await Ct.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ui(),Jl));for(let r of e)fe.register(new t(r.id,r.name,r.source));}async function Gt(){return fe.fetchAll()}async function zl(){return fe.fetchAllWithErrors()}async function Kr(e){xn(e);try{return await Jt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function Xl(e){xn(e);try{let t=await Jt().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function Co(){try{let{profiles:e}=await Jt().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}}async function ql(e,t){let r=me.resolve(t);await pt.mkdir(r,{recursive:true});let n=me.join(me.dirname(r),`${randomUUID()}.zip`);try{await pt.writeFile(n,e),await Df(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=me.resolve(r,o.fileName);if(!i.startsWith(r+me.sep)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(me.resolve(me.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await pt.unlink(n);}catch{}}}async function di(e){await pt.rm(e,{recursive:true,force:true});}async function Wt(){let e=Ia();await pt.mkdir(me.dirname(e),{recursive:true});try{await pt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await bf.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Uf(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:re,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Ql(){let e=Vn();if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return null}}function Ff(){let e=Ql();if(e)return e;let t=Uf(),r=Vn();return Ie__default.mkdirSync(me__default.dirname(r),{recursive:true}),pi(t),t}function pi(e){let t=Vn(),r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function Bf(){let e=Hn(),t={};try{Ie__default.existsSync(e)&&(t=JSON.parse(Ie__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[re])return;t[re]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:xa(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}function ec(e,t){To(e.name),Bf();let r=Cs(e.name);Ie__default.mkdirSync(me__default.dirname(r),{recursive:true});try{Ie__default.lstatSync(r),Ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}Ie__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Ff();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),pi(n));}function mi(e){To(e);let t=Cs(e);try{Ie__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Ql();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&pi(r);}var Kf=x("mcpConfigReader"),Vf=500,Hf=512;function Jf(){return me__default.join(Me__default.homedir(),".claude.json")}function Gf(){return me__default.join(process.cwd(),".mcp.json")}function rc(e){if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return Kf.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fi(e){if(!In(e))return {};let t=e.mcpServers;return In(t)?t:{}}function gi(e,t){return Object.keys(e).slice(0,Vf).map(n=>({name:y(n.slice(0,Hf)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function oc(){let e=[],t=Jf(),r=rc(t);if(In(r)){let a=r,l=fi(a);e.push(...gi(l,"user"));let c=process.cwd();if(In(a.projects)){let u=a.projects[c];if(In(u)){let d=fi(u);e.push(...gi(d,"local"));}}}let n=Gf(),o=rc(n),s=fi(o);e.push(...gi(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var We=x("storage");async function zf(e,t){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:G().interfaceType});}catch(r){We.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function Xf(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:G().interfaceType}).catch(o=>We.warn(`Failed to send ${t} metrics: ${String(o)}`));}function wi(){return me__default.join(Me__default.homedir(),".claude","plugins","installed_plugins.json")}function qf(){return me__default.join(Me__default.homedir(),".claude","plugins")}function sc(e){let t=me__default.resolve(e),r=me__default.resolve(qf()),n=me__default.resolve(me__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+me__default.sep)||t===r,s=t.startsWith(n+me__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function ic(e="user"){return e==="local"?me__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?me__default.join(process.cwd(),".claude","settings.json"):me__default.join(Me__default.homedir(),".claude","settings.json")}function kt(){let e=wi();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 ac(){let e=wi();try{let t=await Ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Yf(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function lc(e,t){try{Ie__default.mkdirSync(me__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 Yf(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Tt(e){lc(wi(),e);}function vn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Zf(e,t){let r=me__default.join(e,".claude-plugin"),n=me__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=me__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 xi(e="user"){let t=ic(e);if(!Ie__default.existsSync(t))return {};try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function cc(e,t="user"){lc(ic(t),e);}function Qf(e,t){let{name:r,marketplace:n}=vn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vn(i).name===r)[0],!o)throw We.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function eg(e,t){let{name:r,marketplace:n}=vn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>vn(i).name===r)[0],o?{key:o,name:r}:null}function yi(e="user"){return xi(e).enabledPlugins??{}}function hi(e,t="user"){let r=xi(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,cc(r,t);}function bn(e,t,r="user"){let n=xi(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},cc(n,r);}function tg(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function se(){let e=kt(),t=yi(),r=yi("project"),n=yi("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=vn(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return tg(p).map(g=>{let h=Zf(g.installPath,d),T=(o[g.scope]??t)[c];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:T===false?"disabled":"enabled"}})}),i=oc(),a=new Set(s.map(c=>`${c.name}@${c.scope}`)),l=i.filter(c=>!a.has(`${c.name}@${c.scope}`));return [...s,...l]}async function ko(e,t){We.debug(`[${e}] Acquiring lock to uninstall`);let r=await Wt();try{let n=kt(),o=eg(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`);We.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),sc(l.installPath);let c=me__default.dirname(l.installPath);We.debug(`[${i}] Removing directory: ${c}`),Ie__default.rmSync(c,{recursive:!0,force:!0});let u=a.filter(d=>d.scope!==t);if(u.length===0){let{[s]:d,...m}=n.plugins;Tt({...n,plugins:m}),hi(s,t),mi(i);}else n.plugins[s]=u,Tt(n),hi(s,t);}else {We.debug(`[${i}] Resolved key: ${s}`);for(let u of a){sc(u.installPath);let d=me__default.dirname(u.installPath);We.debug(`[${i}] Removing directory: ${d}`),Ie__default.rmSync(d,{recursive:!0,force:!0}),hi(s,u.scope);}mi(i);let{[s]:l,...c}=n.plugins;Tt({...n,plugins:c});}await zf(i,a[0].origin??"internal"),We.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Pn(e,t,r){We.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Wt();try{let o=kt(),{key:s,name:i}=Qf(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";We.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),bn(s,t==="enabled",l),Xf(i,t,c),We.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var rg=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ng=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function To(e){if(!rg.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function og(e){if(!ng.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 zt=x("installer");function sg(e,t){let r=`${e}@${re}`,o=kt().plugins[r];if(o&&!t)throw new _e(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function ig(e,t,r){r&&await di(t);try{zt.debug(`[${t}] Extracting archive...`),await ql(e,t);}catch(n){throw await di(t),n}}function ag(e,t,r,n,o,s="claude-code"){let i=kt(),a={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s},l=i.plugins[e]??[];i.plugins[e]=[...l.filter(c=>c.scope!==n),a],Tt(i),bn(e,true,n);}async function lg(e,t,r,n,o){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:G().interfaceType});}catch(s){zt.warn(`Failed to send install metrics: ${String(s)}`);}}async function cg(e,t,r){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:G().interfaceType});}catch(n){zt.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function be(e,t={}){let r=Date.now(),n=null;try{zt.debug(`[${e}] Acquiring lock...`),n=await Wt();let{pluginKey:o,alreadyInstalled:s}=sg(e,t.force);zt.debug(`[${e}] Fetching manifest...`);let i=await Kr(e);To(i.name),og(i.version),zt.debug(`[${e}] Downloading archive...`);let a=await Xl(e),l=t.scope??"user",c=wa(i.name,i.version);await ig(a,c,!!s&&!!t.force),ag(o,c,i.version,l,"internal",t.providerId),ec(i,c);let u=Date.now()-r;zt.debug(`[${e}] Installed successfully in ${u}ms`);let d={name:i.name,version:i.version,path:c,duration_ms:u};return t.skipMetrics||await lg(i.name,i.version,u,Io(l),"internal"),d}catch(o){throw await cg(e,o,"internal"),zt.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var ug=x("commands:helpers");async function Se(){let e=await ne();if(!e)return C("Not authenticated. Run: flow auth login"),false;try{await jt();}catch(t){return ug.debug(`Token validation failed: ${String(t)}`),C("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(C("Starter kit not set. Run: flow auth login"),false):true}async function Xt(e){let t=Ii.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 uc(e){let t=Ii.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var En=x("claudeProxy"),Pi="claude ",dc="flow ",vi=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},bi=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";}},dg=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,pg=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,mg=/^(flow|claude)\s+auth\s+login(\s|$)/;function fg(e){mc(e);let t=e.slice(Pi.length);if(!dg.test(t))throw new bi(e)}var Ao=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}};function mc(e){if(!e||!/^claude /.test(e))throw new vi(e)}async function we(e){mc(e);let t=e.slice(Pi.length).split(/\s+/).filter(Boolean),r=gg(t);En.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 En.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 fc(o)?new Ao:o}}function gg(e){return e.length>=3?e[2]:e.join(" ")}function fc(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function yg(e){return e.startsWith(dc)?Pi+e.slice(dc.length):e}function hg(e){return pg.test(e)||mg.test(e)}function Sg(e){let t=0;for(;t<e.length&&hg(e[t]);)t++;return e.slice(t)}var wg=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function xg(e,t){return !t||e.includes("--scope")||!wg.test(e)?e:`${e} --scope ${t}`}async function Ei(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Sg(r).map(i=>yg(i)).map(i=>xg(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)fg(i);En.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await we(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await we(o[i]),s.exitCode!==0)return s;return s}async function Mo(e,t,r){let n=Fr(e),o=t?.trim();if(!o&&(o=(await uc(`Plugin "${n}" could not be installed.
|
|
111
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Po(o),r?.(),En.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"}`);En.debug(`[${n}] Marketplace added successfully`);}catch(s){throw fc(s)?new Ao:s}}var Eg=6e4,qt=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 Yt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Eg}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm$1(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new qt("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new qt(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new qt(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Zt(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function wr(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 Tg(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function kg(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Ag(e){return typeof e=="object"&&e!==null&&e.source==="github"}function $o(e,t){let r=e.source;if(Tg(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(kg(r))return {cloneUrl:r.url,subPath:"."};if(Ag(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}var Qt=x("claude-code.adapter");function $g(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=Hn();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 vc(e,t){let r=e.catalogId?fe.getAdapter(e.catalogId):void 0,n=$o(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="plugin"||e.type==null,s=$g(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ts(s,e.name,"external"):a=join(sr(i==="user"?"global":"project"),e.name);let l=null;try{l=await Yt(n.cloneUrl,n.ref);let c=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(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await ac(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code"},p=d.plugins[u]??[];d.plugins[u]=[...p.filter(f=>f.scope!==i),m],Tt(d),bn(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return Qt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await Zt(l).catch(()=>{});}}async function Ci(e,t,r){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Io(r),version:"unknown",duration_ms:t,interface:G().interfaceType});}catch(n){Qt.warn(`Failed to send external install metrics: ${String(n)}`);}}async function xc(e,t){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"plugin",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:G().interfaceType});}catch(r){Qt.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}var Lg={async install(e,t){if(e.origin===Cr&&!e.installCommand&&!Ur(e.name))return vc(e,t);if(e.origin===Cr&&e.installCommand){let r=await Ei(e.installCommand,t.scope);return r.exitCode===0?(await Ci(e.name,r.duration_ms,t.scope),{success:true,message:`Installed ${e.name}`}):(await xc(e.name,new Error(r.stderr||"Install failed")),{success:false,message:r.stderr||`Install failed with exit code ${r.exitCode}`})}if(Ur(e.name)){let r=Br(e.name,t.scope);Qt.debug(`[${e.name}] Attempting install: ${r}`);let n=await we(r);if(n.exitCode===0)return await Ci(e.name,n.duration_ms,t.scope),{success:true};Qt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Mo(e.name,t.marketplaceSource,()=>{});let o=await we(r);return o.exitCode===0?(await Ci(e.name,o.duration_ms,t.scope),{success:true}):(await xc(e.name,new Error(o.stderr||"Install failed")),{success:false,message:o.stderr||`Install failed with exit code ${o.exitCode}`})}try{let r=await be(e.name,t);return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Qt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await ko(e,t);},getInstallPath(e,t){return ""}};function Ic(e){return {async install(t,r){if(t.origin===Cr&&!t.installCommand&&!Ur(t.name))return vc(t,r);if(!t.installCommand)try{let o=await be(t.name,r);return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Qt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Qt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Ei(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){throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}var Lo=class{id="claude-code";name="Claude Code";async isAvailable(){return wr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={plugin:Lg,skill:Ic("skill"),mcp:Ic("mcp")}};function Ro(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 _g=new Set(["gh"]),Dg=Ro(_g,"use: gh copilot mcp remove <name>"),_o=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await wr("gh",["--version"])?wr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Dg}};var Og=new Set(["opencode"]),Ng=Ro(Og,"use: opencode config remove mcp <name>");function Ug(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
+
`)}function bc(){return {async install(e,t){let r=e.catalogId?fe.getAdapter(e.catalogId):void 0,n=$o(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Yt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Jn(t.scope??"user"),a=join(s,".opencode","plugins");if(Ie__default.existsSync(a)){let l=Ie__default.readdirSync(a).filter(c=>c.endsWith(".js")||c.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`),Ug(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 Zt(o).catch(()=>{});}},async uninstall(e,t){let r=Jn(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(Jn(t),`${e}.js`)}}}var Do=class{id="opencode";name="OpenCode";async isAvailable(){return wr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Ng,skill:bc(),plugin:bc()}};var mt=new xo;mt.register(new Lo);Kt()&&(mt.register(new _o),mt.register(new Do));function Pc({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,c]=useState([]),[u,d]=useState(void 0);useEffect(()=>{mt.getAvailableProviders(t??"plugin").then(c).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let I=l.find(T=>T.name===h);I?(d(I.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let I=Nl(h);I?r(I,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(I=>I.name),"Cancel"];return jsx(dt,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(dt,{itemName:`${e} \u2014 Choose scope`,actions:Dl,descriptions:Ol,onAction:f,onClose:g},"scope"):jsx(dt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Uo({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=w(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")}}function Tc({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=Uo({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(c)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(dt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function Mc({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Uo({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(dt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var ge=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:se()})}));function $c({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,c=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}),c&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Nt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function Lc({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:c,stored:u}=e,d=c.removable!==false,m=u?.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:c.name}),jsx(Text,{dimColor:true,children:c.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`:"",u?.lastUpdated?` \xB7 Updated ${Nt(u.lastUpdated)}`:""]})}),u&&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((g,h)=>{let I=h===o;return jsxs(Box,{children:[jsx(Text,{color:I?"cyan":void 0,children:I?"\u203A ":" "}),jsx(Text,{bold:I,color:g.danger?"yellow":void 0,dimColor:!I,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Rc(e){return e.adapter.removable!==false?4:2}function _c({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((c,u)=>{if(u.escape){n();return}if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(i.length-1,d+1));return}u.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((c,u)=>jsxs(Box,{children:[jsx(Text,{color:u===a?"cyan":void 0,children:u===a?"\u203A ":" "}),jsx(Text,{bold:u===a,color:c.danger?"yellow":void 0,dimColor:u!==a,children:c.label})]},c.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Oc({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 Nc({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(k=>r.has(`${k.name}@${o}`)),i=t.filter(k=>!r.has(`${k.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((k,F)=>{if(F.escape){n();return}if(F.return){d(a[l]??null);return}if(F.upArrow){c(J=>Math.max(0,J-1));return}F.downArrow&&c(J=>Math.min(a.length-1,J+1));},{isActive:u===null}),u!==null)return jsx(_c,{item:u,adapterName:e.adapter.name,isInstalled:r.has(`${u.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(Be/2)),p=Math.min(a.length,m+Be);p===a.length&&(m=Math.max(0,p-Be));let f=a.slice(m,p),g=m,h=a.length-p,I=s.length>0&&m<s.length,T=p>s.length,b=f.filter(k=>r.has(`${k.name}@${o}`)),M=f.filter(k=>!r.has(`${k.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:g>0?`\u2191 ${g} more above`:" "})}),I&&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"]}),b.map(k=>jsx(Oc,{item:k,isSelected:a.indexOf(k)===l,isInstalled:true},k.name))]}),T&&jsxs(Box,{flexDirection:"column",marginTop:I?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),M.map(k=>jsx(Oc,{item:k,isSelected:a.indexOf(k)===l,isInstalled:false},k.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ui();var Wg=/^https?:\/\/.+/;function zg(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Xg(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function jc(e){let t=w(h=>h.showNotification),r=w(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[c,u]=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(""),u(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,I=d.current;if(!Wg.test(h)){u("URL must start with http:// or https://");return}u(null),o("adding");let T=randomUUID(),b=new jr(T,I,h);try{await b.fetchItems(),await Ct.add({id:T,name:I,source:h}),fe.register(new jr(T,I,h)),r(),e(),t(`Catalog "${I}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let k=zg(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Xg(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(k,"error"),o("add-url");}},[e,t,r]);return useInput((h,I)=>{if(I.escape){o("idle");return}if(I.return){d.current.trim().length>0&&o("add-url");return}if(I.backspace||I.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!I.ctrl&&!I.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,I)=>{if(I.escape){o("add-name");return}if(I.return){g();return}if(I.backspace||I.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}h&&!I.ctrl&&!I.meta&&(m.current=m.current+h,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Kc(e){let t=w(o=>o.showNotification),r=w(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Ct.remove(o),fe.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 Hc(){let e=w(A=>A.focus),t=w(A=>A.setFocus),r=w(A=>A.setActiveTab),n=w(A=>A.showNotification),o=ge(A=>A.installedItems),[s,i]=useState(()=>fe.listAdapters().map(A=>({adapter:A,stored:null}))),[a,l]=useState(0),[c,u]=useState("list"),[d,m]=useState(0),[p,f]=useState(null),[g,h]=useState("main"),I=useRef(s);useEffect(()=>{I.current=s;},[s]),useEffect(()=>{g==="browse"&&!s[a-1]&&h("main");},[g,s,a]);let T=useCallback(()=>{(async()=>{let A=fe.listAdapters(),O=await Ct.read(),B=new Map(O.map(N=>[N.id,N]));i(A.map(N=>({adapter:N,stored:B.get(N.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),T();},[t,T]),useEffect(()=>{if(a===0){f(null);return}let A=I.current[a-1];if(!A)return;let O=false;return f({items:[],loading:true,error:null}),A.adapter.fetchItems().then(B=>{O||f({items:B,loading:false,error:null});}).catch(B=>{O||f({items:[],loading:false,error:B instanceof Error?B.message:"Failed to load catalog"});}),()=>{O=true;}},[a]);let b=jc(T),M=useCallback(()=>{T(),l(0),u("list"),f(null),h("main");},[T]),{handleRemove:k}=Kc(M),F=useCallback(async A=>{h("removing"),await k(A);},[k]),J=useCallback(async A=>{try{let O=await A.adapter.fetchItems();if(f({items:O,loading:!1,error:null}),A.stored){let B=new Date().toISOString();await Ct.updateField(A.stored.id,{lastUpdated:B}),T();}n("Marketplace updated","success");}catch(O){n(O instanceof Error?O.message:"Update failed","error");}},[T,n]),Y=useCallback(async A=>{if(!A.stored)return;let O=A.stored.autoUpdate!==false;await Ct.updateField(A.stored.id,{autoUpdate:!O}),T();},[T]),R=useCallback(()=>h("browse"),[]),S=useCallback(A=>{let O=s[a-1];if(!O)return;let B=O.adapter.removable!==false;[R,()=>{J(O);},...B?[()=>{Y(O);},()=>{F(O.adapter.id);}]:[]][A]?.();},[s,a,R,J,Y,F]),_=useCallback(()=>h("main"),[]),H=useCallback(()=>{let A=s[a-1];A&&J(A);},[s,a,J]),Z=useCallback(()=>{let A=s[a-1];A&&Y(A);},[s,a,Y]),rn=useCallback(()=>{let A=s[a-1];A&&F(A.adapter.id);},[s,a,F]);if(useInput((A,O)=>{if(O.upArrow){l(B=>Math.max(0,B-1));return}if(O.downArrow){l(B=>Math.min(s.length,B+1));return}if(O.leftArrow||O.rightArrow){let B=["discover","installed","marketplaces"],N=B.indexOf("marketplaces"),Is=O.leftArrow?B[(N-1+B.length)%B.length]:B[(N+1)%B.length];r(Is),t("list");return}(O.return||O.tab)&&(a===0?b.startAdd():(u("detail"),m(0)));},{isActive:g==="main"&&b.phase==="idle"&&c==="list"&&e==="marketplaces"}),useInput((A,O)=>{if(O.escape||O.tab){u("list");return}if(O.upArrow){m(B=>Math.max(0,B-1));return}if(O.downArrow){let B=s[a-1],N=B?Rc(B)-1:0;m(Is=>Math.min(Is+1,N));return}O.return&&S(d);},{isActive:g==="main"&&b.phase==="idle"&&c==="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(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let A=s[a-1];if(!A)return jsx(Box,{});let O=A.adapter.id??"default",B=new Set(o.filter(N=>N.marketplace===A.adapter.name).map(N=>`${N.name}@${O}`));return jsx(Nc,{entry:A,items:p?.items??[],installedKeys:B,onBack:_})}if(s.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 It=s[a-1]??null,Fn=It?o.filter(A=>A.marketplace===It.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx($c,{entries:s,selectedIndex:a,focusPanel:c})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:c==="detail"&&It?jsx(Lc,{entry:It,detailData:p,installedCount:Fn,focusPanel:c,actionIndex:d,onBrowse:R,onUpdate:H,onToggleAutoUpdate:Z,onRemove:rn}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:It?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:c==="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 Jc(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=oe.indexOf(r.activeTab),s=oe[(o-1+oe.length)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.rightArrow){let o=oe.indexOf(r.activeTab),s=oe[(o+1)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.tab){let o=oe.indexOf(r.activeTab),s=oe[(o+1)%oe.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="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 Gc(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Wc(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}function Ho(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=w.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:c}=Re.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?w.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?w.getState().selectAllTypes():s.type==="toggleOriginFilter"?w.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&w.getState().selectAllOrigins();}function zc({listLength:e}){let t=w(g=>g.focus),r=w(g=>g.selectedIndex),n=w(g=>g.actionMenuOpen),o=w(g=>g.setFocus),s=w(g=>g.setActionMenuOpen),i=Re(g=>g.query),a=Re(g=>g.setQuery),l=Re(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Re.getState();h(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:I,selectedIndex:T,actionMenuOpen:b}=w.getState();Ho(al(g,h,{activeTab:I}));},{isActive:t==="tabs"}),useInput((g,h)=>{let{activeTab:I,selectedIndex:T,actionMenuOpen:b}=w.getState();Ho(Jc(g,h,{activeTab:I,selectedIndex:T},c.current));},{isActive:t==="list"}),useInput((g,h)=>{Ho(Gc(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let I=Wc(g,h,Re.getState().query),T=I.queryUpdate;if(Ho(I.actions),T==="reset")l(),d("");else if(T!==null){let{query:b,cursorPosition:M,setCursorPosition:k}=Re.getState();if("backspace"in T)M>0&&(a(b.slice(0,M-1)+b.slice(M)),k(M-1));else if("append"in T)a(b.slice(0,M)+T.append+b.slice(M)),k(M+T.append.length);else if("cursorMove"in T){let F=M+T.cursorMove;F>=0&&F<=b.length&&k(F);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:I}=w.getState();g===0?h(0):I>=g&&h(g-1);},[]),f=useCallback(g=>{if(!u)return c.current=g.length,g;let h=u.toLowerCase(),I=g.filter(T=>T.name.toLowerCase().includes(h)||T.description?.toLowerCase().includes(h));return c.current=I.length,I},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function qc(){let e=w(a=>a.notification),t=w(a=>a.showNotification),r=w(a=>a.clearNotification),n=He(a=>a.justAuthenticated),o=He(a=>a.credentials),s=He(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 Ee(e,t,r=false){return r?true:!$i.valid(e)||!$i.valid(t)?false:$i.gt(t,e)}var $t=x("updater");async function ey(e,t,r,n,o){try{await P(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:G().interfaceType});}catch(s){$t.warn(`Failed to send update metrics: ${String(s)}`);}}function ty(e){let t=kt(),r=`${e}@${re}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Jo(e,t={}){let r=Date.now(),n=null;try{$t.debug(`[${e}] Acquiring lock...`),n=await Wt();let o=ty(e);if(!o)throw $t.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;$t.debug(`[${e}] Fetching manifest...`);let c=(await Kr(e)).version;if(!i||!Ee(i,c,t.force))throw $t.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Ht(e,i??"unknown");$t.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await be(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await ey(u.name,i,u.version,d,s.origin??"internal"),$t.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){$t.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Wt();let d=kt(),m=`${e}@${re}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Tt(d),$t.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var Go=x("dispatcher");async function ry(e,t,r,n,o){let s=Fr(e);return Go.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Mo(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Go.debug(`[${e}] Retrying install after marketplace add`),we(t)}async function Yc(e,t,r,n){let o=Br(e,n),s=Fr(e);r?.onStatus?.(`Installing ${s}...`),Go.debug(`[${e}] Attempting install: ${o}`);let i=await we(o);if(i.exitCode===0)return i;Go.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return ry(e,o,a,t,r)}async function Zc(e,t,r){let n=e.type??"plugin",o=await mt.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 Qc(){let e=ge(i=>i.installedItems),t=ge(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Zc(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),c=l?.providerId??"claude-code",u=mt.getAdapter(c);if(!u)throw new Error(`Provider "${c}" not found`);let d=l?.type??"plugin",m=u.installers[d];if(!m)throw new Error(`Provider "${c}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let c=e.find(u=>u.name===i)?.status==="enabled"?"disabled":"enabled";await Pn(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Jo(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var zo=x("mcp");function $n(e,t){e.silent?Ve({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):C(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function tu(e,t){e.silent?$e({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ce(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&E(t.stdout));}function ny(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 Li(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 ru(e,t,r){if(!await Se())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return $n(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}zo.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=ny(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Xt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|
|
114
|
-
[y/N] `))return zo.debug(`[${e}] Installation cancelled by user`),E("Operation cancelled."),0}let o=r.silent?void 0:
|
|
114
|
+
[y/N] `))return zo.debug(`[${e}] Installation cancelled by user`),E("Operation cancelled."),0}let o=r.silent?void 0:ia({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await we(n);return o?.stop(),s.exitCode!==0?($n(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&E(`stdout: ${s.stdout}`),1):(tu(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),$n(r,{name:e,action:"add",message:Q(s)}),1}}async function nu(e,t){if(!await Se())return 1;zo.debug(`[${e}] Starting MCP remove`);let r=Li(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await Xt(`Remove MCP "${o}"?
|
|
115
115
|
This will run: ${s}
|
|
116
|
-
[y/N] `))return zo.debug(`[${e}] Removal cancelled by user`),E("Operation cancelled."),0}let n=t.silent?void 0:sa({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await we(r);return n?.stop(),o.exitCode!==0?($n(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&E(`stdout: ${o.stdout}`),1):(eu(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),$n(t,{name:e,action:"remove",message:Q(o)}),1}}function nu({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=w(b=>b.setLoading),{install:l,uninstall:c,toggle:u,update:d}=Zc(),m=async(b,M,k)=>{a(true,b),n();try{await M(),o(r.length),s(k,"success");}catch(F){let J=F instanceof Error?F.message:"Something went wrong";i.error(`[withLoading] ${b} failed: ${J}`),s(J,"error");}finally{a(false);}};return {handleInstall:(b,M)=>{e&&t&&m(`Installing ${e.name}...`,()=>l(t,{scope:b,...M!==void 0?{providerId:M}:{}}),"\u2713 Installed successfully");},handleUninstall:b=>{e&&m(`Uninstalling ${e.name}...`,()=>c(e.name,b),"\u2713 Uninstalled");},handleToggleStatus:b=>{if(!e)return;let M=e.status==="enabled";m(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,b),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let b=t?` to v${t.version}`:"";(async()=>{a(true,`Updating ${e.name}${b}...`),n();try{await d(e.name),o(r.length),s(`\u2713 Updated ${e.name}${b}`,"success");}catch(k){if(k instanceof Ht)s(k.message,"info");else {let F=k instanceof Error?k.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${F}`),s(F,"error");}}finally{a(false);}})();},handleBatchUpdate:b=>{if(b.length===0)return;let M=b.length;(async()=>{a(true,`Updating ${M} plugin${M>1?"s":""}...`),n();try{let F=[];for(let R of b)F.push(await d(R.name).then(()=>({status:"fulfilled",value:void 0}),S=>({status:"rejected",reason:S})));let J=F.filter(R=>R.status==="fulfilled").length,Y=F.map((R,S)=>R.status==="rejected"?b[S].name:null).filter(R=>R!==null);o(r.length),Y.length===0?s(`\u2713 Updated ${J}/${M} plugin${M>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${Y.join(", ")}`),s(`Updated ${J}/${M}; failed: ${Y.join(", ")}`,J>0?"info":"error"));}finally{a(false);}})();},handleMcpConfigUninstall:b=>{e&&m(`Removing MCP ${e.name}...`,async()=>{let M=Li(e.name,b),k=await we(M);if(k.exitCode!==0)throw new Error(k.stderr||"MCP removal failed");ge.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Ln=["local","project","user"],ty=new Set(["--transport","--scope","-s"]);function ou(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(ty.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Ir(e,t){return t?`${e}::${t}`:e}function Ri(e){return e===re?nn:Cr}function su(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??nn}}function _i(e,t){let r=Ri(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??r}}function iu(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return Ln.filter(r=>t.has(r)).map(r=>({scope:r,label:on[r].label,pathHint:on[r].pathHint,items:t.get(r)??[]}))}function au(e){let t=r=>{if(!r)return 1/0;let n=Ln.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function lu({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Ir(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[Ir(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let I=f.get(Ir(h.name,h.author?.name))??g.get(h.name),T=I?.version,b=!!T&&!!h.version&&Ee(h.version,T);return {...h,updateAvailable:b,catalogItem:I}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Ir(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?ou(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>su(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>_i(f,f.catalogItem)):a.map(f=>_i(f,f.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(f=>{let g=f.type??"plugin";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),u=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("plugin"))return "plugins"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${u} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>{let f=new Map(e.map(h=>[Ir(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Ir(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Di(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=w(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Wl();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(v.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{u();},[u,c]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:u}}function cu(){return {items:ge(t=>t.installedItems)}}var iy=x("catalog");function du(){let e=w(N=>N.activeTab),t=w(N=>N.notification),r=w(N=>N.loading),n=w(N=>N.loadingMessage),o=w(N=>N.catalogError),s=w(N=>N.setCatalogError),i=w(N=>N.catalogFilters),a=Re(N=>N.query),{catalog:l,isLoading:c,error:u,refetch:d}=Di(),{items:m}=cu(),p=ge(N=>N.loadFromDisk),{items:f,emptyMessage:g,getSelectedCatalogItem:h,outdatedCount:I}=lu({catalog:l,installedItems:m,activeTab:e,catalogFilters:i,searchQuery:a}),{actionMenuOpen:T,closeMenu:b,selectedIndex:M,clampIndex:k,filteredItems:F}=Wc({listLength:f.length}),J=F(f),Y=useMemo(()=>e!=="installed"&&e!=="updates"?J:au(J),[e,J]),R=useMemo(()=>e==="installed"||e==="updates"?iu(Y):[],[e,Y]),S=Y[M]??null,_=useMemo(()=>h(S),[h,S]),{notify:H}=Xc(),{handleInstall:Z,handleUninstall:rn,handleToggleStatus:It,handleUpdate:Fn,handleBatchUpdate:A,handleMcpConfigUninstall:O}=nu({selectedItem:S,selectedCatalogItem:_,items:f,closeMenu:b,clampIndex:k,notify:H}),B=useCallback(()=>A(Y),[A,Y]);return useEffect(()=>{p();},[]),useEffect(()=>{k(Y.length);},[Y.length,k]),useEffect(()=>{u&&(iy.error(`[catalog] ${u instanceof Error?u.message:String(u)}`),s("Failed to load catalog"));},[u]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsx(ul,{outdatedCount:I}),e==="marketplaces"&&Kt()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Vc,{})}):jsx(Cl,{filteredItems:Y,groups:R,emptyMessage:g,onBatchUpdate:B}),(r||c)&&jsx(ho,{message:r?n:"Loading catalog..."}),o&&!c&&e==="discover"&&jsx(So,{message:o,onRetry:()=>{s(null),d();},onBack:()=>s(null)}),t&&jsx(Tl,{message:t.message,type:t.type}),T&&S&&(e==="discover"?jsx(bc,{itemName:S.name,itemType:_?.type,onInstall:Z,onClose:b}):S.type==="mcp"?jsx(Ac,{itemName:S.name,itemScope:S.scope??"user",onUninstall:O,onClose:b}):jsx(Cc,{itemName:S.name,itemScope:S.scope??"user",itemStatus:S.status??"enabled",updateAvailable:S.updateAvailable??false,catalogVersion:_?.version,onUninstall:rn,onToggleStatus:N=>It(N),onUpdate:Fn,onClose:b})),jsx(yo,{})]})}var L=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ge.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var uy=3;function mu(){let e=L(l=>l.setStarterKits),t=L(l=>l.setIsLoadingStarterKits),r=L(l=>l.setStarterKitsError),n=L(l=>l.setPluginStatus),o=L(l=>l.setStep),s=L(l=>l.computeSummary),i=useCallback(async()=>{t(true),r(null);try{let l=await Co();e(l);}catch(l){r(l instanceof Error?l.message:String(l));}finally{t(false);}},[t,r,e]);useEffect(()=>{ge.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let l=L.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of l){n(u.name,"installing");let d="",m=false;for(let p=1;p<=uy;p++)try{await be(u.name),n(u.name,"success"),m=!0;break}catch(f){if(f instanceof _e){n(u.name,"success"),m=true;break}d=f instanceof Error?f.message:"Unknown error";}m||(n(u.name,"failed",d),P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:d,interface:G().interfaceType}).catch(()=>{}));}let c=ur();cr("summary_review"),P(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:c}).catch(()=>{}),ge.getState().loadFromDisk(),s(),o("summary");},[n,s,o]);return {loadStarterKits:i,installSelected:a}}var Rn={cursorDelta:0,confirm:false,back:false};function fu(e,t){return t.upArrow?{...Rn,cursorDelta:-1}:t.downArrow?{...Rn,cursorDelta:1}:t.escape?{...Rn,back:true}:t.return?{...Rn,confirm:true}:Rn}var dy={cursorDelta:0,select:false};function gu(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:dy}var yu=Nm.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var ji=5;function hu({onRetry:e}){let t=L(u=>u.starterKits),r=L(u=>u.selectedStarterKitIndex),n=L(u=>u.isLoadingStarterKits),o=L(u=>u.starterKitsError);if(n)return jsx(ho,{message:"Loading Starter Kits..."});if(o)return jsx(So,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Or,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(ji/2)),i=Math.min(t.length,s+ji);i===t.length&&(s=Math.max(0,i-ji));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(yu,{starterKit:u,isSelected:s+d===r},u.slug)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var wu=Nm.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Hi=8;function xu(){let e=L(u=>u.selectedStarterKit),t=L(u=>u.plugins),r=L(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(v.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,s=Math.max(0,r-Math.floor(Hi/2)),i=Math.min(t.length,s+Hi);i===t.length&&(s=Math.max(0,i-Hi));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(wu,{plugin:u,isCursor:s+d===r},u.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var xy=["Retry failed","Continue anyway"];function Iu({name:e,status:t,error:r}){let n=y(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nf,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function vu({onComplete:e,onRetry:t}){let r=L(c=>c.plugins),n=L(c=>c.step),o=L(c=>c.successCount),s=L(c=>c.failedCount),i=L(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(Iu,{name:c.name,status:c.status,error:c.error},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(Iu,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:xy.map((c,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",c]})},c))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function bu(){let e=L(S=>S.step),t=L(S=>S.starterKits),r=L(S=>S.selectedStarterKitIndex),n=L(S=>S.setSelectedStarterKitIndex),o=L(S=>S.selectStarterKit),s=L(S=>S.plugins),i=L(S=>S.pluginCursorIndex),a=L(S=>S.setPluginCursorIndex),l=L(S=>S.setStep),c=L(S=>S.summaryActionIndex),u=L(S=>S.setSummaryActionIndex),d=L(S=>S.failedCount),m=L(S=>S.resetForRetry),p=L(S=>S.goBackToList),f=w(S=>S.setScreen),g=w(S=>S.setFocus),h=w(S=>S.focus),I=He(S=>S.setJustAuthenticated),T=He(S=>S.justAuthenticated),{loadStarterKits:b,installSelected:M}=mu(),k=useRef(false);useEffect(()=>{e==="bundleList"?(g("bundleList"),k.current||(k.current=true,cr("bundle_selection"))):g(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,g]);let F=useCallback(async()=>{let S=L.getState().selectedStarterKit;if(S){let H=await ne();H&&await bt({...H,starterKit:S.slug});}P(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ur()}).catch(()=>{});let{successCount:_}=L.getState();P(v.CLI_ONBOARDING_COMPLETED,{duration_ms:Pt(),tools_installed_count:_}).catch(()=>{}),I(false),g("verify"),f("verify");},[I,g,f]),J=useCallback(()=>{m(),M();},[m,M]),Y=useCallback(()=>{b();},[b]),R=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((S,_)=>{if(_.escape)uo("esc"),R();else if(_.upArrow&&r>0)n(r-1);else if(_.downArrow&&r<t.length-1)n(r+1);else if(_.return&&t.length>0){let H=ur();o(t[r]),cr("kit_display"),P(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:H}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((S,_)=>{let H=fu(S,_);if(H.cursorDelta!==0){let Z=i+H.cursorDelta;Z>=0&&Z<s.length&&a(Z);}if(H.confirm){let Z=L.getState().selectedStarterKit;Z&&(async()=>(await ne())?.starterKit!==Z.slug&&P(v.CLI_KIT_ACCEPTED,{bundle_slug:Z.slug}).catch(()=>{}))();let rn=ur();cr("kit_confirmation"),P(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:rn}).catch(()=>{});let It=ur();cr("tool_installation"),P(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:It}).catch(()=>{}),l("installing"),M();}if(H.back){let Z=L.getState().selectedStarterKit;Z&&P(v.CLI_KIT_REJECTED,{bundle_slug:Z.slug}).catch(()=>{}),p();}},{isActive:h==="bundleDetail"}),useInput((S,_)=>{if(d===0)return;let H=gu(S,_);if(H.cursorDelta!==0){let Z=c+H.cursorDelta;Z>=0&&Z<=1&&u(Z);}H.select&&(c===0?J():F());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!T&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(hu,{onRetry:Y}),e==="bundleDetail"&&jsx(xu,{}),(e==="installing"||e==="summary")&&jsx(vu,{onComplete:F,onRetry:J})]}),jsx(yo,{})]})}var Cy=x("moduleState");function ns(){let e=process.env.FLOW_HOME??me__default.join(Me__default.homedir(),".flow");return me__default.join(e,"modules.json")}var Ty={retries:5,minTimeout:50};async function Pu(e,t){Ie__default.mkdirSync(me__default.dirname(e),{recursive:true});let r=await xf.lock(e+".lock",{realpath:false,retries:Ty});try{return await t()}finally{await r();}}function Eu(){let e=ns();if(!Ie__default.existsSync(e))return [];try{let t=JSON.parse(Ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Cy.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 br(){return Eu()}function Cu(e){let t=ns();Ie__default.mkdirSync(me__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Ie__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Ie__default.renameSync(r,t);}function Ze(e){return br().find(t=>t.alias===e)??null}async function ht(e){let t=ns();await Pu(t,async()=>{let r=Eu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Cu(r);});}async function zr(){let e=ns();Ie__default.existsSync(e)||await Pu(e,async()=>{Ie__default.existsSync(e)||Cu([]);});}var My=promisify(execFile);function rr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function St(e){let t=process.platform==="win32"?"where":"which";try{return await My(t,[e]),!0}catch{return false}}function _t(){return process.platform==="win32"?"npm.cmd":"npm"}var Tu=promisify(execFile),os=class{type="npm";async isAvailable(){return St("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=rr(t,"npm");if(!r)return null;try{let{stdout:n}=await Tu(_t(),["list","-g",r.package,"--depth=0","--json"],{shell:!0});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=rr(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(_t(),["install","-g",s],{shell:!0}),{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 ku=promisify(execFile),Dy=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ss=class{type="homebrew";async isAvailable(){return St("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=rr(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=rr(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 await ku("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 ku("brew",["list","--versions",t]),n=r.trim().match(Dy);return n?n[2]:null}catch{return null}}};var Xr=promisify(execFile),Fy=x("curlStrategy"),Mu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function $u(){let e=process.env.FLOW_HOME??me__default.join(Me__default.homedir(),".flow");return me__default.join(e,"bin")}var is=class{type="curl";async isAvailable(){return St("curl")}async install(t){let r=Date.now(),n=rr(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=me__default.join($u(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await Xr(n,["--version"]),s=o.match(Mu);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){let s=me__default.join(Me__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Xr("curl",["-sSL","--fail","-o",s,t]),r||Fy.warn(`Installing script for "${n.alias}" without checksum verification \u2014 checksumUrl not provided`),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 Xr("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=$u(),i=me__default.join(s,n.binaryName),a=false;try{if(Ie__default.mkdirSync(s,{recursive:!0}),a=!0,await Xr("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return Ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}Ie__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await Xr(i,["--version"]),u=c.match(Mu);l=u?u[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=me__default.join(Me__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Xr("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{}}}};var Te=x("moduleInstaller");function Dt(e){switch(e){case "npm":return new os;case "homebrew":return new ss;case "curl":return new is}}async function On(e,t,r){try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Te.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Yr(e,t,r){let n=Date.now(),o=e.platforms[process.platform];if(!o)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-n};if(o.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let l={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}if(o.status!=="supported"){let l={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}if(!o.strategies.some(l=>l.type===r)){let l={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}let s=Dt(r),i=false;try{i=await s.isAvailable();}catch(l){Te.warn(`${r} availability check failed: ${String(l)}`);}if(!i){let l={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:t});}catch(l){Te.warn(`Failed to emit install started event: ${String(l)}`);}let a;try{a=await s.install(e);}catch(l){let c=l instanceof Error?l.message:String(l);Te.warn(`${r} install threw: ${c}`),a={success:false,error:{code:"INSTALL_THREW",message:c},durationMs:Date.now()-n};}if(a.success){await ht({alias:e.alias,name:e.name,installedVersion:a.version??null,installMethod:a.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:a.version??"unknown",duration_ms:a.durationMs,os:process.platform,trigger:t});}catch(c){Te.warn(`Failed to emit install completed event: ${String(c)}`);}let l=await jy(e,t);return l?{...a,pendingInteractiveSetup:l}:a}return await On(e,t,a.error??{code:"UNKNOWN",message:"unknown error"}),a}async function jy(e,t){if(!e.postInstall)return null;let r=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return null;let n;if(typeof r=="function"){let o=await ne(),s={credentials:o?{clientId:o.clientId,clientSecret:o.clientSecret,tenant:o.tenant}:null};try{n=r(s);}catch(i){return Te.warn(`postInstall function threw: ${String(i)}`),null}}else n=r;if(n.length===0)return null;if((e.postInstall.mode??"non-interactive")==="interactive")return n[0]??null;for(let o of n){if(o.length===0)continue;let s=spawnSync(o[0],o.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(s.status!==0)return Te.warn(`postInstall "${o.join(" ")}" exited with status ${s.status??"null"}`),s.stderr&&Te.warn(s.stderr),null}return null}async function as(e,t){let r=Date.now(),n=Ze(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=Dt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:"command"});}catch(a){Te.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Te.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await ht({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Te.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Te.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Te.warn(`Failed to emit update failed event: ${String(a)}`);}return i}function Ky(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function _u(e){let[t,r]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[n,o]=useState(false),s=useCallback((u,d)=>{r(m=>m.map(p=>p.alias===u?{...p,...d}:p));},[]),i=useCallback(async()=>{for(let u of e){let d=Ky(u);if(!u.selectedStrategy){let m=d?`No package manager available. Install manually: ${d}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:m,manualInstallHint:d||void 0});continue}s(u.module.alias,{status:"installing"});try{let m=await Yr(u.module,"onboarding",u.selectedStrategy);m.success?s(u.module.alias,{status:"installed",pendingSetupCommand:m.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:m.error?.message??"Installation failed",manualInstallHint:d});}catch(m){s(u.module.alias,{status:"failed",error:m instanceof Error?m.message:"Unknown error",manualInstallHint:d});}}o(true);},[e,s]),a=useMemo(()=>t.filter(u=>u.status==="installed").length,[t]),l=useMemo(()=>t.filter(u=>u.status==="failed").length,[t]),c=useMemo(()=>t.filter(u=>u.status==="skipped").length,[t]);return {modules:t,install:i,isComplete:n,installedCount:a,failedCount:l,skippedCount:c}}function Jy(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function Fu(e,t){let[r,n]=useState(()=>Jy(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),c=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let I=f[p];I&&!I.module.required&&l(I.module.alias);}else if(m.tab){let I=f[p];if(I&&I.availableStrategies.length>1){let T=I.availableStrategies.indexOf(I.selectedStrategy??I.availableStrategies[0]),b=I.availableStrategies[(T+1)%I.availableStrategies.length];n(M=>M.map(k=>k.module.alias===I.module.alias?{...k,selectedStrategy:b}:k));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Gy(){return te.filter(e=>e.platforms[process.platform]?.status==="supported")}function ju(e){let t=Gy();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Bu={alias:"metrics",required:true,name:"flow-ai-obs",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=>{if(!e.credentials)throw new Error("flow-ai-obs setup requires credentials");let{clientId:t,clientSecret:r,tenant:n}=e.credentials;return [["flow-ai-obs","auth","login","--client-id",t,"--client-secret",r,"--tenant",n],["flow-ai-obs","install"]]},onDemand:null,mode:"non-interactive"}},Wy={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"},{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},te=Kt()?[Bu,Wy]:[Bu];var Ku=null;function Vu(){return Ku}async function ls(){let t=br().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=te.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Hu(n);(o||s)&&await ht({...r,installedVersion:o,installMethod:s});}}async function Hu(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Dt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Zr(e){let t=await Promise.all(e.map(r=>Xy(r)));return Ku=t,t}async function Xy(e){let t=qy(e.versionCommand),r=e.platforms[process.platform],n=r?.status==="supported"?r.strategies:[],s=(await Promise.all(n.map(async i=>{try{return await Dt(i.type).isAvailable()?i.type:null}catch{return null}}))).filter(i=>i!==null);if(t&&!Ze(e.alias)){let{installedVersion:i,installMethod:a}=await Hu(e);await ht({alias:e.alias,name:e.name,installedVersion:i,installMethod:a,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:s}}function qy(e){if(e.length===0)return false;try{return spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"}).status===0}catch{return false}}function Zy({module:e}){let t=y(e.name);return e.status==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nf,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]}):e.status==="installed"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["\u2139 Run '",y(e.pendingSetupCommand),"' to complete configuration"]})})]}):e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function Qy({confirmedItems:e}){let t=w(f=>f.setScreen),r=w(f=>f.setFocus),{modules:n,install:o,isComplete:s,installedCount:i,failedCount:a,skippedCount:l}=_u(e),c=useRef(false),u=useRef(false);useEffect(()=>{c.current||(c.current=true,o());},[o]);let d=useCallback(()=>{zr().catch(()=>{}),r("list");let f=se().some(g=>g.name===ie);t(f?"main":"claudeMdSuggestion");},[r,t]);useEffect(()=>{if(s&&a===0&&!u.current){u.current=true;let f=setTimeout(d,1500);return ()=>clearTimeout(f)}},[s,a,d]),useInput((f,g)=>{g.return&&d();},{isActive:s});let m=s,p=[];return i>0&&p.push(jsxs(Text,{color:"green",children:[i," installed"]},"i")),a>0&&p.push(jsxs(Text,{color:"red",children:[a," failed"]},"f")),l>0&&p.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.map(f=>jsx(Zy,{module:f},f.alias))}),m&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:p.reduce((f,g,h)=>(h>0&&f.push(jsx(Text,{children:" | "},`sep-${h}`)),f.push(g),f),[])}),jsx(Box,{paddingX:1,children:a>0?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function eh({probeResults:e,onConfirm:t}){let r=w(p=>p.focus),n=w(p=>p.actionMenuOpen),o=w(p=>p.setActionMenuOpen),s=w(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Fu(e,r==="moduleSetup"),c=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),u=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),c();},[l,t,c]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(dt,{itemName:m,actions:d,onAction:u,onClose:c})]})}function Wu(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),i=w(u=>u.setFocus),a=w(u=>u.setScreen),l=useCallback(u=>{if(ju(u)){zr().catch(()=>{}),i("list");let m=se().some(p=>p.name===ie);a(m?"main":"claudeMdSuggestion");}else n(u),t("selection");},[i,a]);useEffect(()=>{let u=Vu();if(u){l(u);return}Zr(te).then(l).catch(()=>{n([]),t("selection");});},[l]);let c=useCallback(u=>{s(u),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(eh,{probeResults:r,onConfirm:c}),e==="installation"&&jsx(Qy,{confirmedItems:o})]})}var oh=x("ClaudeMdSuggestion"),sh=[`Install ${ie}`,"Skip for now"],ih=["Retry","Skip for now"];function qu(){let e=w(m=>m.setScreen),t=w(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{P(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await be(ie),o("installed");}catch(m){if(m instanceof _e){o("installed");return}oh.warn(`Failed to install ${ie}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?ih:sh;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?c():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),u()):c());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Xu,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nf,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ie,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ie," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",ie]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ie]}),jsx(Xu,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Xu({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var uh=promisify(execFile),cs="@ciandt-flow/cli";async function Yu(){let e=ae;if($i.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:cs};try{let t=await fetch(`https://registry.npmjs.org/${cs}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:cs}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:cs}}}async function us(e){try{return await uh(_t(),["install","-g",e.packageName],{timeout:6e4,shell:!0}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Zu(e){let r=Ze(e.alias)?.installedVersion??null,n=null;try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`);if(!s.ok)throw new Error(`Registry returned ${s.status}`);n=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`);if(!s.ok)throw new Error(`GitHub returned ${s.status}`);n=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=r!==null&&n!==null&&r!==n;return {moduleAlias:e.alias,currentVersion:r,latestVersion:n,isOutdated:o}}async function Qu(e,t){let r=Ze(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Dt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ht({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function ed(e){let r=Ze(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function td(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...te.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([Yu(),Zr(te),Promise.all(te.map(l=>Zu(l)))]);if(ls(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await us(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=te.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await Qu(c,l);u.success?r(l.moduleAlias,{status:"updated",detail:`v${u.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:ed(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await zr(),t(l=>({...l,outcome:"done"}));}catch{await zr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function yh({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(nf,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function hh({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function rd(){let{outcome:e,items:t}=td(),r=w(o=>o.setScreen),n=w(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=se().some(i=>i.name===ie);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(yh,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(hh,{outcome:e})})]})}var Ih={debug:"gray",info:"cyan",warn:"yellow",error:"red"},nd=10;function od(){let[e,t]=useState(As());useEffect(()=>Pa(()=>{t([...As()]);}),[]);let r=e.slice(-nd);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",nd,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:Ih[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Eh=x("app"),Ch={auth:tl,bundleSetup:bu,moduleSetup:Wu,claudeMdSuggestion:qu,verify:rd,main:du};function ad(){let{setScreen:e,setFocus:t}=w.getState();e("auth"),t("auth");}function hn(e){let{setScreen:t,setFocus:r}=w.getState();!e.starterKit||e.starterKit.trim()===""?(t("bundleSetup"),r("bundleList")):(t("verify"),r("verify"));}function ld(){P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{});}async function ud(){let e=await ne();if(e&&Za()&&await Bt()){let{clientSecret:n,...o}=e;He.getState().setCredentials(o),ld(),hn(e);return}if(!e){ad();return}try{await jt();}catch(n){Eh.debug(`Token validation failed: ${String(n)}`),ad();return}ld();let{clientSecret:t,...r}=e;He.getState().setCredentials(r),hn(e);}function dd(){let{columns:e,rows:t}=useWindowSize(),r=w(a=>a.screen),n=Ch[r],{pendingExit:o}=Wa(),s=w(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=w.getState().debugPanelOpen;w.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(od,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function na(e,t={}){let r=po({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return mo(r),await bt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var lt=x("auth");function md(){Le.clearFallbackFile(),so();}var Th=3,pd=3,fd=` \u2139 The data collected during setup is used solely to improve
|
|
116
|
+
[y/N] `))return zo.debug(`[${e}] Removal cancelled by user`),E("Operation cancelled."),0}let n=t.silent?void 0:ia({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await we(r);return n?.stop(),o.exitCode!==0?($n(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&E(`stdout: ${o.stdout}`),1):(tu(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),$n(t,{name:e,action:"remove",message:Q(o)}),1}}function ou({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=w(b=>b.setLoading),{install:l,uninstall:c,toggle:u,update:d}=Qc(),m=async(b,M,k)=>{a(true,b),n();try{await M(),o(r.length),s(k,"success");}catch(F){let J=F instanceof Error?F.message:"Something went wrong";i.error(`[withLoading] ${b} failed: ${J}`),s(J,"error");}finally{a(false);}};return {handleInstall:(b,M)=>{e&&t&&m(`Installing ${e.name}...`,()=>l(t,{scope:b,...M!==void 0?{providerId:M}:{}}),"\u2713 Installed successfully");},handleUninstall:b=>{e&&m(`Uninstalling ${e.name}...`,()=>c(e.name,b),"\u2713 Uninstalled");},handleToggleStatus:b=>{if(!e)return;let M=e.status==="enabled";m(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,b),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let b=t?` to v${t.version}`:"";(async()=>{a(true,`Updating ${e.name}${b}...`),n();try{await d(e.name),o(r.length),s(`\u2713 Updated ${e.name}${b}`,"success");}catch(k){if(k instanceof Ht)s(k.message,"info");else {let F=k instanceof Error?k.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${F}`),s(F,"error");}}finally{a(false);}})();},handleBatchUpdate:b=>{if(b.length===0)return;let M=b.length;(async()=>{a(true,`Updating ${M} plugin${M>1?"s":""}...`),n();try{let F=[];for(let R of b)F.push(await d(R.name).then(()=>({status:"fulfilled",value:void 0}),S=>({status:"rejected",reason:S})));let J=F.filter(R=>R.status==="fulfilled").length,Y=F.map((R,S)=>R.status==="rejected"?b[S].name:null).filter(R=>R!==null);o(r.length),Y.length===0?s(`\u2713 Updated ${J}/${M} plugin${M>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${Y.join(", ")}`),s(`Updated ${J}/${M}; failed: ${Y.join(", ")}`,J>0?"info":"error"));}finally{a(false);}})();},handleMcpConfigUninstall:b=>{e&&m(`Removing MCP ${e.name}...`,async()=>{let M=Li(e.name,b),k=await we(M);if(k.exitCode!==0)throw new Error(k.stderr||"MCP removal failed");ge.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Ln=["local","project","user"],oy=new Set(["--transport","--scope","-s"]);function su(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(oy.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Ir(e,t){return t?`${e}::${t}`:e}function Ri(e){return e===re?nn:Cr}function iu(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??nn}}function _i(e,t){let r=Ri(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"plugin",origin:t?.origin??r}}function au(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return Ln.filter(r=>t.has(r)).map(r=>({scope:r,label:on[r].label,pathHint:on[r].pathHint,items:t.get(r)??[]}))}function lu(e){let t=r=>{if(!r)return 1/0;let n=Ln.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function cu({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Ir(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[Ir(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let I=f.get(Ir(h.name,h.author?.name))??g.get(h.name),T=I?.version,b=!!T&&!!h.version&&Ee(h.version,T);return {...h,updateAvailable:b,catalogItem:I}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Ir(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?su(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>iu(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>_i(f,f.catalogItem)):a.map(f=>_i(f,f.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(f=>{let g=f.type??"plugin";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),u=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("plugin"))return "plugins"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${u} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>{let f=new Map(e.map(h=>[Ir(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Ir(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Di(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=w(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await zl();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(v.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{u();},[u,c]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:u}}function uu(){return {items:ge(t=>t.installedItems)}}var cy=x("catalog");function pu(){let e=w(N=>N.activeTab),t=w(N=>N.notification),r=w(N=>N.loading),n=w(N=>N.loadingMessage),o=w(N=>N.catalogError),s=w(N=>N.setCatalogError),i=w(N=>N.catalogFilters),a=Re(N=>N.query),{catalog:l,isLoading:c,error:u,refetch:d}=Di(),{items:m}=uu(),p=ge(N=>N.loadFromDisk),{items:f,emptyMessage:g,getSelectedCatalogItem:h,outdatedCount:I}=cu({catalog:l,installedItems:m,activeTab:e,catalogFilters:i,searchQuery:a}),{actionMenuOpen:T,closeMenu:b,selectedIndex:M,clampIndex:k,filteredItems:F}=zc({listLength:f.length}),J=F(f),Y=useMemo(()=>e!=="installed"&&e!=="updates"?J:lu(J),[e,J]),R=useMemo(()=>e==="installed"||e==="updates"?au(Y):[],[e,Y]),S=Y[M]??null,_=useMemo(()=>h(S),[h,S]),{notify:H}=qc(),{handleInstall:Z,handleUninstall:rn,handleToggleStatus:It,handleUpdate:Fn,handleBatchUpdate:A,handleMcpConfigUninstall:O}=ou({selectedItem:S,selectedCatalogItem:_,items:f,closeMenu:b,clampIndex:k,notify:H}),B=useCallback(()=>A(Y),[A,Y]);return useEffect(()=>{p();},[]),useEffect(()=>{k(Y.length);},[Y.length,k]),useEffect(()=>{u&&(cy.error(`[catalog] ${u instanceof Error?u.message:String(u)}`),s("Failed to load catalog"));},[u]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsx(dl,{outdatedCount:I}),e==="marketplaces"&&Kt()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Hc,{})}):jsx(Tl,{filteredItems:Y,groups:R,emptyMessage:g,onBatchUpdate:B}),(r||c)&&jsx(ho,{message:r?n:"Loading catalog..."}),o&&!c&&e==="discover"&&jsx(So,{message:o,onRetry:()=>{s(null),d();},onBack:()=>s(null)}),t&&jsx(kl,{message:t.message,type:t.type}),T&&S&&(e==="discover"?jsx(Pc,{itemName:S.name,itemType:_?.type,onInstall:Z,onClose:b}):S.type==="mcp"?jsx(Mc,{itemName:S.name,itemScope:S.scope??"user",onUninstall:O,onClose:b}):jsx(Tc,{itemName:S.name,itemScope:S.scope??"user",itemStatus:S.status??"enabled",updateAvailable:S.updateAvailable??false,catalogVersion:_?.version,onUninstall:rn,onToggleStatus:N=>It(N),onUpdate:Fn,onClose:b})),jsx(yo,{})]})}var L=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ge.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"bundleDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"bundleList"})}));var my=3;function fu(){let e=L(l=>l.setStarterKits),t=L(l=>l.setIsLoadingStarterKits),r=L(l=>l.setStarterKitsError),n=L(l=>l.setPluginStatus),o=L(l=>l.setStep),s=L(l=>l.computeSummary),i=useCallback(async()=>{t(true),r(null);try{let l=await Co();e(l);}catch(l){r(l instanceof Error?l.message:String(l));}finally{t(false);}},[t,r,e]);useEffect(()=>{ge.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let l=L.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of l){n(u.name,"installing");let d="",m=false;for(let p=1;p<=my;p++)try{await be(u.name),n(u.name,"success"),m=!0;break}catch(f){if(f instanceof _e){n(u.name,"success"),m=true;break}d=f instanceof Error?f.message:"Unknown error";}m||(n(u.name,"failed",d),P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:d,interface:G().interfaceType}).catch(()=>{}));}let c=ur();cr("summary_review"),P(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:c}).catch(()=>{}),ge.getState().loadFromDisk(),s(),o("summary");},[n,s,o]);return {loadStarterKits:i,installSelected:a}}var Rn={cursorDelta:0,confirm:false,back:false};function gu(e,t){return t.upArrow?{...Rn,cursorDelta:-1}:t.downArrow?{...Rn,cursorDelta:1}:t.escape?{...Rn,back:true}:t.return?{...Rn,confirm:true}:Rn}var fy={cursorDelta:0,select:false};function yu(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:fy}var hu=Bm.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var ji=5;function Su({onRetry:e}){let t=L(u=>u.starterKits),r=L(u=>u.selectedStarterKitIndex),n=L(u=>u.isLoadingStarterKits),o=L(u=>u.starterKitsError);if(n)return jsx(ho,{message:"Loading Starter Kits..."});if(o)return jsx(So,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Or,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(ji/2)),i=Math.min(t.length,s+ji);i===t.length&&(s=Math.max(0,i-ji));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(hu,{starterKit:u,isSelected:s+d===r},u.slug)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var xu=Bm.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Hi=8;function Iu(){let e=L(u=>u.selectedStarterKit),t=L(u=>u.plugins),r=L(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(v.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,s=Math.max(0,r-Math.floor(Hi/2)),i=Math.min(t.length,s+Hi);i===t.length&&(s=Math.max(0,i-Hi));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(xu,{plugin:u,isCursor:s+d===r},u.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var by=["Retry failed","Continue anyway"];function vu({name:e,status:t,error:r}){let n=y(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(af,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function bu({onComplete:e,onRetry:t}){let r=L(c=>c.plugins),n=L(c=>c.step),o=L(c=>c.successCount),s=L(c=>c.failedCount),i=L(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(vu,{name:c.name,status:c.status,error:c.error},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(vu,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:by.map((c,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",c]})},c))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Pu(){let e=L(S=>S.step),t=L(S=>S.starterKits),r=L(S=>S.selectedStarterKitIndex),n=L(S=>S.setSelectedStarterKitIndex),o=L(S=>S.selectStarterKit),s=L(S=>S.plugins),i=L(S=>S.pluginCursorIndex),a=L(S=>S.setPluginCursorIndex),l=L(S=>S.setStep),c=L(S=>S.summaryActionIndex),u=L(S=>S.setSummaryActionIndex),d=L(S=>S.failedCount),m=L(S=>S.resetForRetry),p=L(S=>S.goBackToList),f=w(S=>S.setScreen),g=w(S=>S.setFocus),h=w(S=>S.focus),I=He(S=>S.setJustAuthenticated),T=He(S=>S.justAuthenticated),{loadStarterKits:b,installSelected:M}=fu(),k=useRef(false);useEffect(()=>{e==="bundleList"?(g("bundleList"),k.current||(k.current=true,cr("bundle_selection"))):g(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,g]);let F=useCallback(async()=>{let S=L.getState().selectedStarterKit;if(S){let H=await ne();H&&await bt({...H,starterKit:S.slug});}P(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ur()}).catch(()=>{});let{successCount:_}=L.getState();P(v.CLI_ONBOARDING_COMPLETED,{duration_ms:Pt(),tools_installed_count:_}).catch(()=>{}),I(false),g("verify"),f("verify");},[I,g,f]),J=useCallback(()=>{m(),M();},[m,M]),Y=useCallback(()=>{b();},[b]),R=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((S,_)=>{if(_.escape)uo("esc"),R();else if(_.upArrow&&r>0)n(r-1);else if(_.downArrow&&r<t.length-1)n(r+1);else if(_.return&&t.length>0){let H=ur();o(t[r]),cr("kit_display"),P(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:H}).catch(()=>{});}},{isActive:h==="bundleList"}),useInput((S,_)=>{let H=gu(S,_);if(H.cursorDelta!==0){let Z=i+H.cursorDelta;Z>=0&&Z<s.length&&a(Z);}if(H.confirm){let Z=L.getState().selectedStarterKit;Z&&(async()=>(await ne())?.starterKit!==Z.slug&&P(v.CLI_KIT_ACCEPTED,{bundle_slug:Z.slug}).catch(()=>{}))();let rn=ur();cr("kit_confirmation"),P(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:rn}).catch(()=>{});let It=ur();cr("tool_installation"),P(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:It}).catch(()=>{}),l("installing"),M();}if(H.back){let Z=L.getState().selectedStarterKit;Z&&P(v.CLI_KIT_REJECTED,{bundle_slug:Z.slug}).catch(()=>{}),p();}},{isActive:h==="bundleDetail"}),useInput((S,_)=>{if(d===0)return;let H=yu(S,_);if(H.cursorDelta!==0){let Z=c+H.cursorDelta;Z>=0&&Z<=1&&u(Z);}H.select&&(c===0?J():F());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!T&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="bundleList"&&jsx(Su,{onRetry:Y}),e==="bundleDetail"&&jsx(Iu,{}),(e==="installing"||e==="summary")&&jsx(bu,{onComplete:F,onRetry:J})]}),jsx(yo,{})]})}var Ay=x("moduleState");function ns(){let e=process.env.FLOW_HOME??me__default.join(Me__default.homedir(),".flow");return me__default.join(e,"modules.json")}var My={retries:5,minTimeout:50};async function Eu(e,t){Ie__default.mkdirSync(me__default.dirname(e),{recursive:true});let r=await bf.lock(e+".lock",{realpath:false,retries:My});try{return await t()}finally{await r();}}function Cu(){let e=ns();if(!Ie__default.existsSync(e))return [];try{let t=JSON.parse(Ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Ay.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 br(){return Cu()}function Tu(e){let t=ns();Ie__default.mkdirSync(me__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Ie__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),Ie__default.renameSync(r,t);}function Ze(e){return br().find(t=>t.alias===e)??null}async function ht(e){let t=ns();await Eu(t,async()=>{let r=Cu(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Tu(r);});}async function zr(){let e=ns();Ie__default.existsSync(e)||await Eu(e,async()=>{Ie__default.existsSync(e)||Tu([]);});}var Ry=promisify(execFile);function rr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function St(e){let t=process.platform==="win32"?"where":"which";try{return await Ry(t,[e]),!0}catch{return false}}function _t(){return process.platform==="win32"?"npm.cmd":"npm"}var ku=promisify(execFile),os=class{type="npm";async isAvailable(){return St("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=rr(t,"npm");if(!r)return null;try{let{stdout:n}=await ku(_t(),["list","-g",r.package,"--depth=0","--json"],{shell:!0});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=rr(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 ku(_t(),["install","-g",s],{shell:!0}),{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 Au=promisify(execFile),Uy=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ss=class{type="homebrew";async isAvailable(){return St("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=rr(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=rr(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 await Au("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 Au("brew",["list","--versions",t]),n=r.trim().match(Uy);return n?n[2]:null}catch{return null}}};var Xr=promisify(execFile),Ky=x("curlStrategy"),$u=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Lu(){let e=process.env.FLOW_HOME??me__default.join(Me__default.homedir(),".flow");return me__default.join(e,"bin")}var is=class{type="curl";async isAvailable(){return St("curl")}async install(t){let r=Date.now(),n=rr(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=me__default.join(Lu(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await Xr(n,["--version"]),s=o.match($u);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){let s=me__default.join(Me__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Xr("curl",["-sSL","--fail","-o",s,t]),r||Ky.warn(`Installing script for "${n.alias}" without checksum verification \u2014 checksumUrl not provided`),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 Xr("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=Lu(),i=me__default.join(s,n.binaryName),a=false;try{if(Ie__default.mkdirSync(s,{recursive:!0}),a=!0,await Xr("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return Ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}Ie__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await Xr(i,["--version"]),u=c.match($u);l=u?u[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=me__default.join(Me__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Xr("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{}}}};var Te=x("moduleInstaller");function Dt(e){switch(e){case "npm":return new os;case "homebrew":return new ss;case "curl":return new is}}async function On(e,t,r){try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Te.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Yr(e,t,r){let n=Date.now(),o=e.platforms[process.platform];if(!o)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-n};if(o.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let l={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}if(o.status!=="supported"){let l={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}if(!o.strategies.some(l=>l.type===r)){let l={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}let s=Dt(r),i=false;try{i=await s.isAvailable();}catch(l){Te.warn(`${r} availability check failed: ${String(l)}`);}if(!i){let l={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await On(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:t});}catch(l){Te.warn(`Failed to emit install started event: ${String(l)}`);}let a;try{a=await s.install(e);}catch(l){let c=l instanceof Error?l.message:String(l);Te.warn(`${r} install threw: ${c}`),a={success:false,error:{code:"INSTALL_THREW",message:c},durationMs:Date.now()-n};}if(a.success){await ht({alias:e.alias,name:e.name,installedVersion:a.version??null,installMethod:a.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:a.version??"unknown",duration_ms:a.durationMs,os:process.platform,trigger:t});}catch(c){Te.warn(`Failed to emit install completed event: ${String(c)}`);}let l=await Hy(e,t);return l?{...a,pendingInteractiveSetup:l}:a}return await On(e,t,a.error??{code:"UNKNOWN",message:"unknown error"}),a}async function Hy(e,t){if(!e.postInstall)return null;let r=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return null;let n;if(typeof r=="function"){let o=await ne(),s={credentials:o?{clientId:o.clientId,clientSecret:o.clientSecret,tenant:o.tenant}:null};try{n=r(s);}catch(i){return Te.warn(`postInstall function threw: ${String(i)}`),null}}else n=r;if(n.length===0)return null;if((e.postInstall.mode??"non-interactive")==="interactive")return n[0]??null;for(let o of n){if(o.length===0)continue;let s=spawnSync(o[0],o.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(s.status!==0)return Te.warn(`postInstall "${o.join(" ")}" exited with status ${s.status??"null"}`),s.stderr&&Te.warn(s.stderr),null}return null}async function as(e,t){let r=Date.now(),n=Ze(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=Dt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:"command"});}catch(a){Te.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Te.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await ht({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Te.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Te.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Te.warn(`Failed to emit update failed event: ${String(a)}`);}return i}function Jy(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function Du(e){let[t,r]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[n,o]=useState(false),s=useCallback((u,d)=>{r(m=>m.map(p=>p.alias===u?{...p,...d}:p));},[]),i=useCallback(async()=>{for(let u of e){let d=Jy(u);if(!u.selectedStrategy){let m=d?`No package manager available. Install manually: ${d}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:m,manualInstallHint:d||void 0});continue}s(u.module.alias,{status:"installing"});try{let m=await Yr(u.module,"onboarding",u.selectedStrategy);m.success?s(u.module.alias,{status:"installed",pendingSetupCommand:m.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:m.error?.message??"Installation failed",manualInstallHint:d});}catch(m){s(u.module.alias,{status:"failed",error:m instanceof Error?m.message:"Unknown error",manualInstallHint:d});}}o(true);},[e,s]),a=useMemo(()=>t.filter(u=>u.status==="installed").length,[t]),l=useMemo(()=>t.filter(u=>u.status==="failed").length,[t]),c=useMemo(()=>t.filter(u=>u.status==="skipped").length,[t]);return {modules:t,install:i,isComplete:n,installedCount:a,failedCount:l,skippedCount:c}}function zy(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function Bu(e,t){let[r,n]=useState(()=>zy(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),c=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let I=f[p];I&&!I.module.required&&l(I.module.alias);}else if(m.tab){let I=f[p];if(I&&I.availableStrategies.length>1){let T=I.availableStrategies.indexOf(I.selectedStrategy??I.availableStrategies[0]),b=I.availableStrategies[(T+1)%I.availableStrategies.length];n(M=>M.map(k=>k.module.alias===I.module.alias?{...k,selectedStrategy:b}:k));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Xy(){return te.filter(e=>e.platforms[process.platform]?.status==="supported")}function Ku(e){let t=Xy();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var ju={alias:"metrics",required:true,name:"flow-ai-obs",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=>{if(!e.credentials)throw new Error("flow-ai-obs setup requires credentials");let{clientId:t,clientSecret:r,tenant:n}=e.credentials;return [["flow-ai-obs","auth","login","--client-id",t,"--client-secret",r,"--tenant",n],["flow-ai-obs","install"]]},onDemand:null,mode:"non-interactive"}},qy={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"},{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},te=Kt()?[ju,qy]:[ju];var Ju=null;function Gu(){return Ju}async function ls(){let t=br().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=te.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Wu(n);(o||s)&&await ht({...r,installedVersion:o,installMethod:s});}}async function Wu(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Dt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Zr(e){let t=await Promise.all(e.map(r=>Yy(r)));return Ju=t,t}async function Yy(e){let t=Vu(e.versionCommand);t==="permission-denied"&&(Zy(e.versionCommand[0]),t=Vu(e.versionCommand));let r=t==="installed",n=e.platforms[process.platform],o=n?.status==="supported"?n.strategies:[],i=(await Promise.all(o.map(async a=>{try{return await Dt(a.type).isAvailable()?a.type:null}catch{return null}}))).filter(a=>a!==null);if(r&&!Ze(e.alias)){let{installedVersion:a,installMethod:l}=await Wu(e);await ht({alias:e.alias,name:e.name,installedVersion:a,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:r,availableStrategies:i}}function Vu(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function Zy(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=Ie__default.realpathSync(r),{mode:o}=Ie__default.statSync(n);Ie__default.chmodSync(n,o|73);}catch{}}function eh({module:e}){let t=y(e.name);return e.status==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(af,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]}):e.status==="installed"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["\u2139 Run '",y(e.pendingSetupCommand),"' to complete configuration"]})})]}):e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function th({confirmedItems:e}){let t=w(f=>f.setScreen),r=w(f=>f.setFocus),{modules:n,install:o,isComplete:s,installedCount:i,failedCount:a,skippedCount:l}=Du(e),c=useRef(false),u=useRef(false);useEffect(()=>{c.current||(c.current=true,o());},[o]);let d=useCallback(()=>{zr().catch(()=>{}),r("list");let f=se().some(g=>g.name===ie);t(f?"main":"claudeMdSuggestion");},[r,t]);useEffect(()=>{if(s&&a===0&&!u.current){u.current=true;let f=setTimeout(d,1500);return ()=>clearTimeout(f)}},[s,a,d]),useInput((f,g)=>{g.return&&d();},{isActive:s});let m=s,p=[];return i>0&&p.push(jsxs(Text,{color:"green",children:[i," installed"]},"i")),a>0&&p.push(jsxs(Text,{color:"red",children:[a," failed"]},"f")),l>0&&p.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.map(f=>jsx(eh,{module:f},f.alias))}),m&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:p.reduce((f,g,h)=>(h>0&&f.push(jsx(Text,{children:" | "},`sep-${h}`)),f.push(g),f),[])}),jsx(Box,{paddingX:1,children:a>0?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function rh({probeResults:e,onConfirm:t}){let r=w(p=>p.focus),n=w(p=>p.actionMenuOpen),o=w(p=>p.setActionMenuOpen),s=w(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Bu(e,r==="moduleSetup"),c=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),u=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),c();},[l,t,c]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(dt,{itemName:m,actions:d,onAction:u,onClose:c})]})}function qu(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),i=w(u=>u.setFocus),a=w(u=>u.setScreen),l=useCallback(u=>{if(Ku(u)){zr().catch(()=>{}),i("list");let m=se().some(p=>p.name===ie);a(m?"main":"claudeMdSuggestion");}else n(u),t("selection");},[i,a]);useEffect(()=>{let u=Gu();if(u){l(u);return}Zr(te).then(l).catch(()=>{n([]),t("selection");});},[l]);let c=useCallback(u=>{s(u),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(rh,{probeResults:r,onConfirm:c}),e==="installation"&&jsx(th,{confirmedItems:o})]})}var ih=x("ClaudeMdSuggestion"),ah=[`Install ${ie}`,"Skip for now"],lh=["Retry","Skip for now"];function Qu(){let e=w(m=>m.setScreen),t=w(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{P(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,P(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await be(ie),o("installed");}catch(m){if(m instanceof _e){o("installed");return}ih.warn(`Failed to install ${ie}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?lh:ah;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?c():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),u()):c());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dr,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Zu,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(af,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ie,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ie," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",ie]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ie]}),jsx(Zu,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Zu({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var ph=promisify(execFile),cs="@ciandt-flow/cli";async function ed(){let e=ae;if($i.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:cs};try{let t=await fetch(`https://registry.npmjs.org/${cs}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:cs}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:cs}}}async function us(e){try{return await ph(_t(),["install","-g",e.packageName],{timeout:6e4,shell:!0}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function td(e){let r=Ze(e.alias)?.installedVersion??null,n=null;try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`);if(!s.ok)throw new Error(`Registry returned ${s.status}`);n=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`);if(!s.ok)throw new Error(`GitHub returned ${s.status}`);n=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=r!==null&&n!==null&&r!==n;return {moduleAlias:e.alias,currentVersion:r,latestVersion:n,isOutdated:o}}async function rd(e,t){let r=Ze(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Dt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ht({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function nd(e){let r=Ze(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function od(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...te.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([ed(),Zr(te),Promise.all(te.map(l=>td(l)))]);if(ls(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await us(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=te.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await rd(c,l);u.success?r(l.moduleAlias,{status:"updated",detail:`v${u.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:nd(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await zr(),t(l=>({...l,outcome:"done"}));}catch{await zr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function Sh({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(af,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",e.label,e.detail?` ${e.detail}...`:""]})]}):e.status==="ok"||e.status==="updated"?jsxs(Box,{children:[jsxs(Text,{color:"green",children:["\u2713 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}):e.status==="missing"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),jsx(Text,{dimColor:true,children:" \u2014 not installed"})]}):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",e.label]}),e.detail&&jsxs(Text,{dimColor:true,children:[" ",e.detail]})]}),e.manualCommand&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["To update manually: ",e.manualCommand]})})]})}function wh({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function sd(){let{outcome:e,items:t}=od(),r=w(o=>o.setScreen),n=w(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=se().some(i=>i.name===ie);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(Sh,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(wh,{outcome:e})})]})}var bh={debug:"gray",info:"cyan",warn:"yellow",error:"red"},id=10;function ad(){let[e,t]=useState(As());useEffect(()=>Ea(()=>{t([...As()]);}),[]);let r=e.slice(-id);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",id,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:bh[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Th=x("app"),kh={auth:rl,bundleSetup:Pu,moduleSetup:qu,claudeMdSuggestion:Qu,verify:sd,main:pu};function ud(){let{setScreen:e,setFocus:t}=w.getState();e("auth"),t("auth");}function hn(e){let{setScreen:t,setFocus:r}=w.getState();!e.starterKit||e.starterKit.trim()===""?(t("bundleSetup"),r("bundleList")):(t("verify"),r("verify"));}function dd(){P(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{});}async function md(){let e=await ne();if(e&&Qa()&&await Bt()){let{clientSecret:n,...o}=e;He.getState().setCredentials(o),dd(),hn(e);return}if(!e){ud();return}try{await jt();}catch(n){Th.debug(`Token validation failed: ${String(n)}`),ud();return}dd();let{clientSecret:t,...r}=e;He.getState().setCredentials(r),hn(e);}function fd(){let{columns:e,rows:t}=useWindowSize(),r=w(a=>a.screen),n=kh[r],{pendingExit:o}=za(),s=w(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=w.getState().debugPanelOpen;w.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(ad,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function oa(e,t={}){let r=po({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return mo(r),await bt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var lt=x("auth");function yd(){Le.clearFallbackFile(),so();}var Ah=3,gd=3,hd=` \u2139 The data collected during setup is used solely to improve
|
|
117
117
|
Flow's internal tools and will not be shared externally.
|
|
118
118
|
`;function Pr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=u=>{if(u===""){l(),n(new Error("SIGINT"));return}if(u==="\r"||u===`
|
|
119
119
|
`){l(),process.stdout.write(`
|
|
120
|
-
`),r(i);return}if(u==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(i+=u,process.stdout.write(o?"*".repeat(u.length):u));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function
|
|
120
|
+
`),r(i);return}if(u==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(i+=u,process.stdout.write(o?"*".repeat(u.length):u));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function Mh(){let e=dr();return process.stdout.write(`
|
|
121
121
|
`+$.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
122
|
-
`),(await Pr($.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function
|
|
122
|
+
`),(await Pr($.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Sd(e,t){try{await oa(e);return}catch(r){if(!(r instanceof pr))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${dr()} and retry.`);if(!await Mh())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await oa(e,{allowOverwriteMalformed:true});}}async function wd(){for(let e=1;e<=gd;e++)try{return await Co()}catch{if(e===gd)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function xd(){let e=await wd();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
123
123
|
`+$.cyan(" ? ")+`Starter Kit:
|
|
124
124
|
`),e.forEach((t,r)=>{process.stdout.write(` ${$.cyan(`${r+1})`)} ${y(t.name)}
|
|
125
125
|
`);}),process.stdout.write(`
|
|
126
126
|
`);;){let t=(await Pr($.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write($.yellow(` \u26A0 Invalid selection. Please try again.
|
|
127
|
-
`));}}async function
|
|
127
|
+
`));}}async function Id(e){if(e.plugins.length===0)return process.stdout.write($.dim(`
|
|
128
128
|
Starter kit '${y(e.name)}' has no plugins to install.
|
|
129
129
|
`)),true;process.stdout.write(`
|
|
130
130
|
Installing ${e.plugins.length} plugins from '${y(e.name)}'...
|
|
131
|
-
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write($.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=
|
|
131
|
+
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write($.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=Ah;a++)try{await be(o),t++,i=!0;break}catch(l){if(l instanceof _e){t++,i=true;break}}i?process.stdout.write($.green(` done
|
|
132
132
|
`)):(r++,process.stdout.write($.red(` failed
|
|
133
133
|
`)));}return r===0?process.stdout.write($.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
|
|
134
134
|
`)):process.stdout.write($.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
|
|
135
|
-
`)),r===0}async function
|
|
135
|
+
`)),r===0}async function vd(){process.stdout.write(`
|
|
136
136
|
`),process.stdout.write($.bold(` Personalize your Claude Code
|
|
137
137
|
`)),process.stdout.write($.dim(` This plugin helps Claude understand your preferences and work style.
|
|
138
138
|
|
|
@@ -146,80 +146,80 @@ This will run: ${s}
|
|
|
146
146
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
147
147
|
`),process.stdout.write($.cyan.bold(` /${ie}
|
|
148
148
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
149
|
-
`);}async function
|
|
150
|
-
`+
|
|
149
|
+
`);}async function $h(e){yd(),process.stdout.write(`
|
|
150
|
+
`+hd+`
|
|
151
151
|
`),lt.debug(`[${e.tenant}] Authenticating tenant`);try{await lr(e);}catch(t){let r=y(t instanceof Error?t.message:"unknown error");return lt.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write($.red(` \u2717 Authentication failed: ${r}
|
|
152
|
-
`)),1}try{let t;if(e.starterKit){let r=await
|
|
152
|
+
`)),1}try{let t;if(e.starterKit){let r=await wd(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write($.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
153
153
|
`)),process.stderr.write(` Available starter kits:
|
|
154
154
|
`);for(let o of r)process.stderr.write(` - ${y(o.slug)} (${y(o.name)})
|
|
155
|
-
`);return 1}t=n;}else t=await
|
|
155
|
+
`);return 1}t=n;}else t=await xd();return await Sd({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug},!1),await Id(t),await vd(),lt.info(`[${e.tenant}] Authentication successful`),process.stdout.write($.green(`
|
|
156
156
|
\u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${dr()}.
|
|
157
157
|
|
|
158
158
|
`)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=y(t instanceof Error?t.message:"unknown error");return lt.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write($.red(` \u2717 Starter kit setup failed: ${r}
|
|
159
|
-
`)),1}}async function
|
|
160
|
-
`),process.stdout.write(
|
|
159
|
+
`)),1}}async function Lh(){yd(),lt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
160
|
+
`),process.stdout.write(hd+`
|
|
161
161
|
`);let e=(await Pr($.cyan(" ? ")+"Client ID: ")).trim(),t=(await Pr($.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await Pr($.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return lt.error("[auth] Validation failed: all fields are required"),process.stderr.write($.red(` \u2717 All fields are required
|
|
162
162
|
`)),1;lt.debug(`[${r}] Authenticating tenant`);try{await lr({clientId:e,clientSecret:t,tenant:r});}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return lt.error(`[${r}] Authentication failed: ${s}`),process.stderr.write($.red(` \u2717 Authentication failed: ${s}
|
|
163
|
-
`)),1}let n=await
|
|
163
|
+
`)),1}let n=await xd();return await Sd({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug},!0),await Id(n),await vd(),lt.info(`[${r}] Authentication successful`),process.stdout.write($.green(`
|
|
164
164
|
\u2713 Setup complete. Tenant: ${r}. JWT written to ${dr()}.
|
|
165
165
|
|
|
166
166
|
`)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=y(e instanceof Error?e.message:"unknown error");return lt.error(`[auth] Unexpected error: ${t}`),process.stderr.write($.red(` \u2717 Unexpected error: ${t}
|
|
167
|
-
`)),1}}async function
|
|
168
|
-
`),130;throw t}}async function
|
|
167
|
+
`)),1}}async function sa(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return $h({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await Lh()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
168
|
+
`),130;throw t}}async function Rh(){try{return process.stdout.write(`
|
|
169
169
|
`),(await Pr($.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write($.yellow(` \u26A0 Logout cancelled
|
|
170
170
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
171
|
-
`),130;throw e}}async function
|
|
172
|
-
`)),0;if(!e){let t=await
|
|
171
|
+
`),130;throw e}}async function bd(e){if(!await ne())return process.stdout.write($.yellow(` \u26A0 You are not authenticated
|
|
172
|
+
`)),0;if(!e){let t=await Rh();if(t!==null)return t}try{return await Ra(),process.stdout.write($.green(` \u2713 Credentials removed successfully
|
|
173
173
|
`)),0}catch{return process.stderr.write($.red(` \u2717 Error removing credentials
|
|
174
|
-
`)),1}}async function
|
|
174
|
+
`)),1}}async function Pd(){let e=await ne();return e?await Bt()?(process.stdout.write(`
|
|
175
175
|
`+$.bold(` Authenticated
|
|
176
176
|
`)),process.stdout.write($.dim(" Tenant: ")+y(e.tenant)+`
|
|
177
177
|
`),process.stdout.write($.dim(" Client ID: ")+y(e.clientId)+`
|
|
178
178
|
`),process.stdout.write($.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
179
|
-
`),process.stdout.write($.dim(" Config: ")+y(await
|
|
179
|
+
`),process.stdout.write($.dim(" Config: ")+y(await _a())+`
|
|
180
180
|
`),process.stdout.write(`
|
|
181
|
-
`),0):(process.stdout.write($.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write($.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function
|
|
181
|
+
`),0):(process.stdout.write($.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write($.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function _h(e){let t=se(),r;try{r=await Gt();}catch{r=[];}let n=new Set(t.map(o=>o.name));return P(v.CLI_CATALOG_VIEWED,{interface:G().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(Lr(r.map(o=>({...o,installed:n.has(o.name)}))),0):($r(["","Name","Version","Category","Status"],r.map(o=>[n.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",n.has(o.name)?"installed":"available"])),0)}async function Dh(e){let t=se(),r=await Gt(),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ee(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(v.CLI_CATALOG_VIEWED,{interface:G().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(E("All plugins are up to date."),0):e.json?(Lr(o),0):($r(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
182
182
|
${o.length} plugin(s) outdated.
|
|
183
|
-
`),0)}async function
|
|
183
|
+
`),0)}async function Oh(e){let t=se();if(P(v.CLI_CATALOG_VIEWED,{interface:G().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return E("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return Lr(t),0;let r=[];try{r=await Gt();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=Ln.indexOf(s.scope??"user"),l=Ln.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return $r(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"plugin",l=i?.origin??Ri(s.marketplace);return [s.name??"",s.version??"n/a",Tr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",Nt(s.installedAt??"")]})),process.stdout.write(`
|
|
184
184
|
${t.length} plugin(s) installed.
|
|
185
|
-
`),0}async function
|
|
185
|
+
`),0}async function Ed(e){if(!await Se())return 1;try{return e.available?await _h(e):e.outdated?await Dh(e):await Oh(e)}catch(t){return C(t instanceof Error?t.message:"Failed to list plugins."),1}}var le=x("manage");function ps(e,t){return t?se().find(r=>r.name===e&&r.scope===t):se().find(r=>r.name===e)}function Nh(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,E(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=ia({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function Uh(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(Br(e,r.scope));if(!await Xt(`${t}Install external plugin "${i}"?
|
|
186
186
|
This will run: ${a}
|
|
187
|
-
[y/N] `))return le.debug(`[${e}] Installation cancelled by user`),r.silent||E(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=
|
|
188
|
-
Installation summary: ${t} succeeded, ${r} failed`);}async function ms(e,t={}){if(!await Se())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await
|
|
189
|
-
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function
|
|
187
|
+
[y/N] `))return le.debug(`[${e}] Installation cancelled by user`),r.silent||E(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=ia({text:`${t}Installing ${e}...`}).start());}let s=o?Nh(t,o):void 0;try{let i=await Yc(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ve({status:"error",plugin:e,message:a}):C(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?$e({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):ce(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=Q(i);return r.silent?Ve({status:"error",plugin:e,message:a}):C(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Fh(e,t,r){let n=r.silent?void 0:ia({text:`${t}Installing ${e}...`}).start();if(Ur(e))return Uh(e,t,r,n);try{let o=await be(e,r);return n?.stop(),r.silent?$e({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):ce(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof _e)return r.silent?$e({status:"already_installed",plugin:e,message:o.message}):E(`${t}${o.message}`),{name:e,success:true};let s=Q(o);return r.silent?Ve({status:"error",plugin:e,message:s}):C(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function Bh(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;E(`
|
|
188
|
+
Installation summary: ${t} succeeded, ${r} failed`);}async function ms(e,t={}){if(!await Se())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await Fh(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?$e({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):Bh(r)),r.some(n=>!n.success)?1:0}async function Cd(e,t){if(!await Se())return 1;if(le.debug(`[${e}] Looking up installed plugin`),!t.force){let r=ps(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await Xt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return le.debug(`[${e}] Uninstall cancelled by user`),E("Operation cancelled."),0}try{return le.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await ko(e,t.scope),le.info(`[${e}] Uninstalled successfully`),ce("Plugin removed successfully"),0}catch(r){return le.error(`[${e}] Failed to uninstall: ${Q(r)}`),C(Q(r)),1}}async function Td(e,t={}){if(!await Se())return 1;le.debug(`[${e}] Looking up installed plugin`);let r=ps(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return le.debug(`[${e}] Already enabled, skipping`),E(`${r.name} is already enabled`),0;try{return le.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Pn(e,"enabled",t.scope),le.info(`[${e}] Enabled successfully`),ce(`${r.name} enabled successfully`),0}catch(n){return le.error(`[${e}] Failed to enable: ${Q(n)}`),C(Q(n)),1}}async function kd(e,t={}){if(!await Se())return 1;le.debug(`[${e}] Looking up installed plugin`);let r=ps(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return le.debug(`[${e}] Already disabled, skipping`),E(`${r.name} is already disabled`),0;try{return le.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Pn(e,"disabled",t.scope),le.info(`[${e}] Disabled successfully`),ce(`${r.name} disabled successfully`),0}catch(n){return le.error(`[${e}] Failed to disable: ${Q(n)}`),C(Q(n)),1}}async function Ad(e,t,r){r.silent||E(`${t}Updating ${e}...`);try{let n=await Jo(e,r);return r.silent?$e({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):ce(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Ht)return r.silent?$e({status:"up_to_date",plugin:e,message:n.message}):E(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=Q(n);return r.silent?Ve({status:"error",plugin:e,message:o}):C(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function jh(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;E(`
|
|
189
|
+
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Kh(e,t,r){try{let n=await Kr(e);Ee(t,n.version,r.force)?E(`Would update ${e}: v${t} \u2192 v${n.version}`):E(`${e} is already up to date (v${t})`);}catch(n){return C(Q(n)),1}return 0}function Vh(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Hh(e,t,r){let n=t.get(e.name);return n?e.version&&Ee(e.version,n,r)?(E(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(E(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(E(`Skipping ${e.name}: not found in catalog`),false)}async function Jh(e,t){try{let r=await Gt(),n=Vh(r),o=0;for(let s of e)Hh(s,n,t.force)&&o++;o===0&&E("All plugins are up to date");}catch(r){return C(Q(r)),1}return 0}async function Gh(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Ad(e[n].name,o,t);r.push(s);}return t.silent?$e({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):jh(r),r.some(n=>!n.success)?1:0}async function Md(e,t={}){if(!await Se())return 1;if(e){let o=ps(e,t.scope);return o?t.dryRun?Kh(e,o.version??"",t):(await Ad(e,"",t)).success?0:1:(t.silent?Ve({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):C(`Plugin "${e}" is not installed`),1)}let n=se().filter(o=>o.marketplace===re);return n.length===0?(t.silent?$e({status:"empty",message:"No plugins installed"}):E("No plugins installed"),0):t.dryRun?Jh(n,t):Gh(n,t)}var $d=x("marketplace");function zh(e){return `claude plugin marketplace add ${e}`}async function Ld(e,t){if(!await Se())return 1;let r;try{r=Po(e);}catch(s){let i=Q(s);return t.silent?Ve({status:"error",source:e,message:i}):C(i),1}$d.debug(`[marketplace] Adding marketplace source: ${r}`);let n=zh(r);if(!t.force){let s=y(r),i=y(n);if(!await Xt(`Add marketplace "${s}"?
|
|
190
190
|
This will run: ${i}
|
|
191
|
-
[y/N] `))return
|
|
191
|
+
[y/N] `))return $d.debug("[marketplace] Operation cancelled by user"),E("Operation cancelled."),0}let o=t.silent?void 0:ia({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await we(n);return o?.stop(),s.exitCode!==0?(t.silent?Ve({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(C(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&E(`stdout: ${s.stdout}`)),1):(t.silent?$e({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(ce(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&E(s.stdout)),0)}catch(s){o?.stop();let i=Q(s);return t.silent?Ve({status:"error",source:r,message:i}):C(`Failed to add marketplace "${r}": ${i}`),1}}async function Zh(){return await ne()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Qh(){let e=Date.now();try{await Gt();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function eS(){return await Bt()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function tS(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Rd(){process.stdout.write(`
|
|
192
192
|
`+$.bold(` FlowSetup CLI Diagnostics
|
|
193
193
|
|
|
194
|
-
`));let e=[{name:"Credentials",fn:
|
|
194
|
+
`));let e=[{name:"Credentials",fn:Zh},{name:"Prompt Manager",fn:Qh},{name:"Valid Token",fn:eS},{name:"Claude Code",fn:tS}],t=true;for(let r of e){let n=await r.fn(),o="",s=$.green;n.passed?o=$.green("[OK] "):(o=$.red("[FAIL]"),s=$.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
|
|
195
195
|
`);}return process.stdout.write(`
|
|
196
196
|
`),t?(process.stdout.write($.green(` \u2713 All checks passed!
|
|
197
197
|
|
|
198
198
|
`)),0):(process.stdout.write($.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
199
199
|
|
|
200
|
-
`)),1)}var
|
|
201
|
-
`,"utf-8");}async function
|
|
200
|
+
`)),1)}var oS=["github.com","www.github.com"],sS=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,iS=/^([^@]+)@(.+)$/;function aS(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function aa(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function lS(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let s=t.slice(4).join("/");o.subpath=aa(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=aa(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function fs(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(aS(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&oS.includes(r.hostname))return lS(r);if(r.protocol==="https:"||r.protocol==="http:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}if(r.protocol==="git:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let r=t,n,o=t.indexOf("#");o!==-1&&(n=t.slice(o+1),r=t.slice(0,o));let s={type:"git",url:r};return n&&(s.ref=n),s}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let s=r.match(sS);if(s){let i=s[1],a=s[2],l=s[3],c,u=a.match(iS);u&&(a=u[1],c=u[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),c&&(d.skillFilter=c),l){let m=l.replace(/^\//,"");m&&(d.subpath=aa(m));}return d}}return {type:"git",url:t}}function gs(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}function _d(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var ca=new Set(["node_modules",".git","dist","build","__pycache__"]);function en(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function Nd(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function mS(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function la(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Un(e){try{let t=await readFile(e,"utf-8"),{data:r}=_d(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function Ud(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([la(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!ca.has(a.name)).map(a=>Ud(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ss(e,t){let r=[],n=new Set;if(t&&!mS(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await la(o)){let i=await Un(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=join(i,l.name);if(await la(c)){let u=await Un(join(c,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let i=await Ud(o);for(let a of i){let l=await Un(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Fd(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}var Kd=1,wS={retries:5,minTimeout:50};async function Vd(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bf.lock(e+".lock",{realpath:false,retries:wS});try{return await t()}finally{await r();}}function Bd(){return {version:Kd,skills:{}}}async function ws(e){let t=ln(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Kd?Bd():n}catch{return Bd()}}function xS(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Hd(e,t){let r=ln(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:xS(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
|
|
201
|
+
`,"utf-8");}async function Jd(e,t,r){let n=ln(r);await Vd(n,async()=>{let o=await ws(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Hd(o,r);});}async function Gd(e,t){let r=ln(t);await Vd(r,async()=>{let n=await ws(t);e in n.skills&&(delete n.skills[e],await Hd(n,t));});}var Wd=x("skillInstaller");async function TS(e,t,r,n){try{await P(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:G().interfaceType});}catch(o){Wd.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function kS(e,t){try{await P(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:G().interfaceType});}catch(r){Wd.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function AS(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!ca.has(basename(r))});}async function MS(e,t,r){let n=en(e.name),o=sr(t),s=join(o,n);if(!Nd(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm$1(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await AS(e.path,s);let a=gs(r)??r.url;return await Jd(n,{source:a,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:s}}catch(i){return {skill:e.name,success:false,path:s,error:i instanceof Error?i.message:String(i)}}}async function zd(e,t){let r=fs(e),n;try{let o;if(r.type==="local"){if(!r.localPath||!existsSync(r.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=r.localPath;}else n=await Yt(r.url,r.ref),o=n;let s=await Ss(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Fd(s,i):s,l=[],c=r.ref??"latest";for(let u of a){let d=Date.now(),m=await MS(u,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await TS(u.name,t.scope,c,p):await kS(u.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(u=>u.success).length,failed:l.filter(u=>!u.success).length}}finally{n&&await Zt(n).catch(()=>{});}}var DS=x("skills");async function OS(e){try{await P(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:G().interfaceType});}catch(t){DS.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function NS(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function US(e){let t=fs(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return C("Invalid local path."),1;n=t.localPath;}else E(`Fetching skills from ${y(e)}...`),r=await Yt(t.url,t.ref),n=r;let o=await Ss(n,t.subpath);if(o.length===0)return E("No skills found in this source."),0;let i=gs(t)??y(e);E(`Found ${o.length} skill(s) in ${i}:
|
|
202
202
|
`);for(let a of o){let l=y(a.name),c=y(a.description);process.stdout.write(` ${$.bold(l)} ${$.dim(c)}
|
|
203
203
|
`);}return process.stdout.write(`
|
|
204
|
-
`),0}catch(n){return n instanceof qt?C(n.message):C(n instanceof Error?n.message:String(n)),1}finally{r&&await Zt(r).catch(()=>{});}}function
|
|
205
|
-
`);let t=e.source;e.installed>0&&E(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&C(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?E("No skills found in this source."):e.results.length===0&&e.discovered>0&&E(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function
|
|
204
|
+
`),0}catch(n){return n instanceof qt?C(n.message):C(n instanceof Error?n.message:String(n)),1}finally{r&&await Zt(r).catch(()=>{});}}function FS(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);ce(`${n} installed ${$.dim(`\u2192 ${o}/`)}`);}else C(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
205
|
+
`);let t=e.source;e.installed>0&&E(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&C(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?E("No skills found in this source."):e.results.length===0&&e.discovered>0&&E(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function qd(e,t){if(t.list)return US(e);let r=t.global?"global":"project";try{let n=await zd(e,{scope:r,skillFilter:t.skill,yes:t.yes});return FS(n),n.failed>0?1:0}catch(n){return n instanceof qt?C(n.message):C(n instanceof Error?n.message:String(n)),1}}async function Yd(e){let t=sr(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=join(t,o.name),i=join(s,"SKILL.md");try{if(!(await stat(i)).isFile())continue}catch{continue}let a=await Un(i);a?r.push({name:a.name,description:a.description,path:s}):r.push({name:o.name,description:"(no metadata)",path:s});}}catch{}return r}async function Zd(e){let t=e.global?"global":"project",r=await Yd(t),n=await ws(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[en(i.name)]?.source}));return Lr(s),0}if(r.length===0)return E(`No skills installed (${t==="global"?"global":"project"} scope).`),0;E(`${t==="global"?"Global":"Project"} skills (${r.length}):
|
|
206
206
|
`);for(let s of r){let i=n.skills[en(s.name)]?.source,a=y(s.name),l=y(s.description),c=l.length>80?l.slice(0,77)+"...":l,u=i?$.dim(` (${i})`):"";process.stdout.write(` ${$.bold(a)}${u}
|
|
207
207
|
`),process.stdout.write(` ${$.dim(c)}
|
|
208
208
|
|
|
209
|
-
`);}return 0}async function
|
|
209
|
+
`);}return 0}async function Qd(e,t){let r=t.global?"global":"project";if(!e){let i=await Yd(r);if(i.length===0)return E("No skills installed."),0;E("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
|
|
210
210
|
`);return process.stdout.write(`
|
|
211
|
-
`),E("Specify a skill name to remove: flow skills remove <name>"),1}let n=en(e),o=sr(r),s=join(o,n);try{await stat(s);}catch{return C(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await
|
|
212
|
-
Import summary: 0 installed, ${o.length} failed`);for(let a of o)C(` ${a.name}: ${a.error}`);return o.length>0?1:0}E(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=
|
|
213
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)C(` ${a.name}: ${a.error}`);return o.length>0?1:0}function U(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var
|
|
211
|
+
`),E("Specify a skill name to remove: flow skills remove <name>"),1}let n=en(e),o=sr(r),s=join(o,n);try{await stat(s);}catch{return C(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await NS(`Remove skill "${y(n)}"?`))return E("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Gd(n,r),await OS(n),ce(`Skill "${y(n)}" removed.`),0}catch(i){return C(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var xs=x("transfer"),da=1;function BS(e){return e.marketplace&&e.marketplace!==re?`${e.name}@${e.marketplace}`:e.name}function jS(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&E(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),E(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function rp(e){let t=me__default.resolve(e.output);try{let r=se(),n={version:da,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return Ie__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),ce(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=Q(r);return xs.error(`Export failed: ${n}`),C(`Failed to export plugins: ${n}`),1}}async function np(e,t={}){if(!await Se())return 1;let r;try{let a=Ie__default.readFileSync(me__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return C(`Failed to read import file "${e}": ${Q(a)}`),1}if(r.version!==da)return C(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${da}`),1;if(!Array.isArray(r.plugins))return C('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return E("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let c=`entry[${a}]`;xs.warn(`Skipping ${c}: missing or invalid name`),o.push({name:c,error:"missing or invalid name"});}else l.type==="mcp"?(xs.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&E(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(se().map(l=>l.name));jS(n,a);}if(t.dryRun)return E("Dry-run mode: no plugins were installed"),0;if(n.length===0){E(`
|
|
212
|
+
Import summary: 0 installed, ${o.length} failed`);for(let a of o)C(` ${a.name}: ${a.error}`);return o.length>0?1:0}E(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=BS(a);xs.debug(`[${a.name}] Installing as "${c}" in scope "${l}"`),await ms([c],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}E(`
|
|
213
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)C(` ${a.name}: ${a.error}`);return o.length>0?1:0}function U(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var VS=x("moduleProxy");function HS(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Ii.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function op(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await P(v.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{VS.warn(`Failed to emit proxy executed event: ${String(s)}`);}),U(o);}async function ip(e,t){let r=te.find(o=>o.alias===e);if(!r){C(`Unknown module alias: '${e}'`),U(1);return}if(!await St(r.binaryName)){C(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),U(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Dt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){C(`No supported installation method available for '${e}' on this platform.`),U(1);return}if(await HS("Would you like to install it now? [Y/n] ")){await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Yr(r,"inline",s);if(!a.success){C(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),U(1);return}await op(r,t);}else E(`To install manually, run: flow modules install ${e}`),await P(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),U(1);return}await op(r,t);}var zS=promisify(execFile);async function XS(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await zS(_t(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:!0});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ae}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(n.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let o=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t.signal,headers:n});return o.ok?(await o.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(r);}}catch{return null}}function qS(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ee(t,r)?"outdated":"installed"}async function pa(){let e=await Promise.all(te.map(async t=>{let[r,n]=await Promise.all([St(t.binaryName),XS(t)]),s=Ze(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=qS(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return $r(["Name","Alias","Version","Status","Platform"],e),0}async function cp(e){let t=te.find(i=>i.alias===e);if(!t)return C(`Unknown module alias: '${e}'`),1;let[r]=await Zr([t]);if(r.alreadyInstalled){let i=Ze(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return E(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?C(`Module ${t.name} is not supported on ${process.platform}.${a}`):C(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=ia({text:`Installing ${t.name}...`}).start(),s;try{s=await Yr(t,"on_demand",n);}finally{o.stop();}return s.success?(ce(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(C(s.error?.message??"Installation failed"),1)}async function ap(e,t){let r=ia({text:`Updating ${e.name}...`}).start(),n;try{n=await as(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function up(e){if(e!==null){let n=te.find(i=>i.alias===e);if(!n)return C(`Unknown module alias: '${e}'`),1;let o=Ze(n.alias);return o?.installMethod?await ap(n,o.installedVersion??"unknown")==="error"?1:0:(C(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=br().filter(n=>n.installMethod!==null);if(t.length===0)return E("No installed modules to update."),0;let r=0;for(let n of t){let o=te.find(i=>i.alias===n.alias);if(!o)continue;await ap(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function dp(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ae}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
214
214
|
Without arguments, opens the interactive interface (TUI).
|
|
215
215
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
216
216
|
Examples:
|
|
217
|
-
$ flow setup init`).action(async()=>{let c=await
|
|
217
|
+
$ flow setup init`).action(async()=>{let c=await sa();U(c);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
|
|
218
218
|
Examples:
|
|
219
219
|
$ flow plugin list
|
|
220
220
|
$ flow plugin list --available
|
|
221
221
|
$ flow plugin list --outdated
|
|
222
|
-
$ flow plugin list --json`).action(async c=>{let u=await
|
|
222
|
+
$ flow plugin list --json`).action(async c=>{let u=await Ed(c);U(u);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
223
223
|
Examples:
|
|
224
224
|
$ flow plugin install flow-adr-writer
|
|
225
225
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -231,7 +231,7 @@ Examples:
|
|
|
231
231
|
Examples:
|
|
232
232
|
$ flow plugin uninstall flow-adr-writer
|
|
233
233
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
234
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,u)=>{let d=await
|
|
234
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,u)=>{let d=await Cd(c,u);U(d);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
235
235
|
Examples:
|
|
236
236
|
$ flow plugin update flow-adr-writer
|
|
237
237
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -240,70 +240,70 @@ Examples:
|
|
|
240
240
|
$ flow plugin update flow-adr-writer --verbose
|
|
241
241
|
$ flow plugin update flow-adr-writer --silent
|
|
242
242
|
$ flow plugin update
|
|
243
|
-
$ flow plugin update --dry-run`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await
|
|
243
|
+
$ flow plugin update --dry-run`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await Md(c??null,u);U(d);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
244
244
|
Examples:
|
|
245
245
|
$ flow plugin enable flow-adr-writer
|
|
246
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,u)=>{Ke("cli");let d=await
|
|
246
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,u)=>{Ke("cli");let d=await Td(c,u);U(d);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
247
247
|
Examples:
|
|
248
248
|
$ flow plugin disable flow-adr-writer
|
|
249
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,u)=>{Ke("cli");let d=await
|
|
249
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,u)=>{Ke("cli");let d=await kd(c,u);U(d);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
250
250
|
Examples:
|
|
251
251
|
$ flow plugin export
|
|
252
|
-
$ flow plugin export --output my-plugins.json`).action(async c=>{let u=await
|
|
252
|
+
$ flow plugin export --output my-plugins.json`).action(async c=>{let u=await rp(c);U(u);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
253
253
|
Examples:
|
|
254
254
|
$ flow plugin import flow-plugins.json
|
|
255
255
|
$ flow plugin import flow-plugins.json --scope user
|
|
256
256
|
$ flow plugin import flow-plugins.json --force
|
|
257
257
|
$ flow plugin import flow-plugins.json --dry-run
|
|
258
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(c,u)=>{let d=await
|
|
258
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(c,u)=>{let d=await np(c,u);U(d);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
259
259
|
Examples:
|
|
260
260
|
$ flow plugin marketplace add anthropics/claude-code
|
|
261
261
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
262
262
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
263
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await
|
|
263
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await Ld(c,u);U(d);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
264
264
|
Examples:
|
|
265
265
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
266
266
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
267
267
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
268
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,u,d)=>{Ke("cli",{verbose:d.verbose,silent:d.silent});let m=await
|
|
268
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,u,d)=>{Ke("cli",{verbose:d.verbose,silent:d.silent});let m=await ru(c,u,d);U(m);}),s.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
269
269
|
Examples:
|
|
270
270
|
$ flow mcp remove notion
|
|
271
271
|
$ flow mcp remove notion --scope project
|
|
272
|
-
$ flow mcp remove playwright-mcp --force`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await
|
|
272
|
+
$ flow mcp remove playwright-mcp --force`).action(async(c,u)=>{Ke("cli",{verbose:u.verbose,silent:u.silent});let d=await nu(c,u);U(d);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
273
273
|
Examples:
|
|
274
274
|
$ flow auth login
|
|
275
275
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
|
|
276
276
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
|
|
277
|
-
$ flow auth login --verbose`).action(async c=>{Ke("cli",{verbose:c.verbose});let u=await
|
|
277
|
+
$ flow auth login --verbose`).action(async c=>{Ke("cli",{verbose:c.verbose});let u=await sa(c);U(u);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
278
278
|
Examples:
|
|
279
279
|
$ flow auth logout
|
|
280
|
-
$ flow auth logout --force`).action(async c=>{let u=await
|
|
280
|
+
$ flow auth logout --force`).action(async c=>{let u=await bd(c.force);U(u);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
281
281
|
Examples:
|
|
282
|
-
$ flow auth status`).action(async()=>{let c=await
|
|
282
|
+
$ flow auth status`).action(async()=>{let c=await Pd();U(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
|
|
283
283
|
Examples:
|
|
284
284
|
$ flow skills add vercel-labs/agent-skills
|
|
285
285
|
$ flow skills add owner/repo -g
|
|
286
286
|
$ flow skills add owner/repo --skill pr-review commit
|
|
287
287
|
$ flow skills add ./local/skills -y
|
|
288
|
-
$ flow skills add owner/repo --list`).action(async(c,u)=>{let d=await
|
|
288
|
+
$ flow skills add owner/repo --list`).action(async(c,u)=>{let d=await qd(c,u);U(d);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
289
289
|
Examples:
|
|
290
290
|
$ flow skills list
|
|
291
291
|
$ flow skills list -g
|
|
292
|
-
$ flow skills list --json`).action(async c=>{let u=await
|
|
292
|
+
$ flow skills list --json`).action(async c=>{let u=await Zd(c);U(u);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
|
|
293
293
|
Examples:
|
|
294
294
|
$ flow skills remove pr-review
|
|
295
|
-
$ flow skills remove pr-review -g --force`).action(async(c,u)=>{let d=await
|
|
295
|
+
$ flow skills remove pr-review -g --force`).action(async(c,u)=>{let d=await Qd(c,u);U(d);}),t.addCommand(a),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
296
296
|
Examples:
|
|
297
|
-
$ flow health`).action(async()=>{let c=await
|
|
297
|
+
$ flow health`).action(async()=>{let c=await Rd();U(c);});let l=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");l.action(async()=>{let c=await pa();U(c);}),l.command("list").description("List available and installed modules").addHelpText("after",`
|
|
298
298
|
Examples:
|
|
299
|
-
$ flow modules list`).action(async()=>{let c=await
|
|
299
|
+
$ flow modules list`).action(async()=>{let c=await pa();U(c);}),l.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
300
300
|
Examples:
|
|
301
301
|
$ flow modules install metrics
|
|
302
|
-
$ flow modules install dashboard`).action(async c=>{let u=await
|
|
302
|
+
$ flow modules install dashboard`).action(async c=>{let u=await cp(c);U(u);}),l.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
303
303
|
Examples:
|
|
304
304
|
$ flow modules update
|
|
305
|
-
$ flow modules update metrics`).action(async c=>{let u=await
|
|
305
|
+
$ flow modules update metrics`).action(async c=>{let u=await up(c??null);U(u);}),t.addCommand(l);for(let c of te)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await ip(c.alias,u);});return t.hook("preAction",()=>{ls();}),t}function QS(){return me__default.join(Me__default.homedir(),".claude","settings.json")}function mp(){let e=QS();try{if(!Ie__default.existsSync(e))return !0;let r=JSON.parse(Ie__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var sw=x("updateChecker"),iw=promisify(execFile),aw=1440*60*1e3,fp=3e4;function lw(){let e=process.env.FLOW_HOME??me__default.join(Me__default.homedir(),".flow");return me__default.join(e,"update.lock")}async function gp(e){try{let{stdout:t}=await iw(_t(),["view",e,"version"],{timeout:fp,shell:!0});return String(t).trim()||null}catch{return null}}async function cw(e){let t=new AbortController,r=setTimeout(()=>t.abort(),fp);try{let n=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:t.signal});return n.ok?(await n.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(r);}}async function uw(e){return e.versionCheck.type==="npm-registry"?gp(e.versionCheck.package):cw(e.versionCheck.repo)}async function dw(){let e=await gp("@ciandt-flow/cli");return e&&Ee(ae,e)?(us({currentVersion:ae,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function pw(){let e=br().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=te.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<aw)return;let s=await uw(r);try{await ht({...t,lastChecked:new Date().toISOString()});}catch(i){sw.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ee(t.installedVersion,s)&&as(r,"background").catch(()=>{});}));}async function fa(){let e=mp();if(e===false)return;let t=lw();Ie__default.mkdirSync(me__default.dirname(t),{recursive:true});let r=null;try{r=await bf.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await dw().catch(()=>null);n&&process.stdout.write(`
|
|
306
306
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
307
307
|
Restart flow to apply the update.
|
|
308
308
|
|
|
309
|
-
`);}await
|
|
309
|
+
`);}await pw().catch(()=>{});}finally{await r().catch(()=>{});}}var fw=x("cli"),ga=dp(async()=>{Ke("tui"),Va("tui"),Ha(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=w.getState();mn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=w.getState();mn("sigterm",t,r).finally(()=>process.exit(143));}),await fa().catch(()=>{}),await Wl().catch(t=>{fw.error(`Failed to init catalog registry: ${String(t)}`);}),await md();let{waitUntilExit:e}=render(jsx(fd,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});ga.hook("preAction",async(e,t)=>{t!==ga&&await fa().catch(()=>{});});ga.parse();
|