@ciandt-flow/cli 2.0.1 → 2.1.0-beta.230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +19 -0
  2. package/dist/index.js +141 -128
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import {execa}from'execa';import jl,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Um,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as Tr from'crypto';import {randomUUID,createHash}from'crypto';import*as xe from'fs';import xe__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as de from'path';import de__default,{join,dirname,normalize,resolve,sep,relative,isAbsolute,basename}from'path';import*as Ae from'os';import Ae__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as wi from'readline';import {createInterface}from'readline';import M from'chalk';import Fs from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Sm from'jsonwebtoken';import Tm from'ink-big-text';import rf from'ink-spinner';import*as mt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import wf from'proper-lockfile';import $f from'extract-zip';import {simpleGit}from'simple-git';import Mi from'semver';import na from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var mp=Object.defineProperty;var vs=(e,t)=>()=>(e&&(t=e(e=0)),t);var fp=(e,t)=>{for(var r in t)mp(e,r,{get:t[r],enumerable:true});};function zp(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(_a.some(r=>r.test(e)))return true;let t=zp(e);return !!(t&&_a.some(r=>r.test(t)))}function Xp(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Rr(e,t){let r=Xp(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 _a,un=vs(()=>{_a=[/^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 kf(){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 Fl(){return Ul??=kf(),Ul}var Ul,Bl=vs(()=>{});var Vl={};fp(Vl,{GitRepoAdapter:()=>Br});function Kl(e,t){if(!Af.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Af,Br,li=vs(()=>{Bl();un();Af=/^[a-zA-Z0-9_.-]+$/;Br=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 Kl(a,"owner"),Kl(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 jl.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 jl.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 Fl();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",ee="flow-skills",bs="flow-cli",rn="internal",Er="external",Cr={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},plugin:{label:"Plugin",color:"magenta"}},ma={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ps=new Set(["internal","external"]),nn={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"}},ne="flow-claude-md-setup",Fe=5,or=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var fa=new Set(["skill","mcp","plugin"]),y=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(fa),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(fa)},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",yp=16,ga=16,on=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=Tr.randomBytes(yp),n=Tr.createCipheriv(jn,this.key,r,{authTagLength:ga}),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=Tr.createDecipheriv(jn,this.key,Buffer.from(t.iv,"hex"),{authTagLength:ga});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var hp=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Sp=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,wp=/[A-Za-z0-9+/]{40,}={0,2}/g;function Es(e){return e.replace(hp,"Bearer ***").replace(Sp,"***").replace(wp,"***")}var sn=".claude",Kn=".flow";function ya(e,t){return Ts(ee,e,t)}function Cs(e){return de.join(Ae.homedir(),sn,"plugins","marketplaces",ee,"plugins","native",e)}function Vn(){return de.join(Ae.homedir(),sn,"plugins","marketplaces",ee,".claude-plugin","marketplace.json")}function Hn(){return de.join(Ae.homedir(),sn,"plugins","known_marketplaces.json")}function ha(){return de.join(Ae.homedir(),sn,"plugins","marketplaces",ee)}function Sa(){return de.join(Ae.homedir(),Kn,"cache","install.lock")}function wa(){return de.join(Ae.homedir(),Kn,"logs","flowsetup.log")}function Ts(e,t,r){return de.join(Ae.homedir(),sn,"plugins","cache",e,t,r)}function sr(e){let t=e==="global"?Ae.homedir():process.cwd();return de.join(t,".claude","skills")}function an(e){let t=e==="global"?Ae.homedir():process.cwd();return de.join(t,".claude","skills-lock.json")}function Jn(e="user"){return e==="project"?de.join(process.cwd(),".opencode","plugins"):de.join(Ae.homedir(),".config","opencode","plugins")}function xa(){return de.join(Ae.homedir(),Kn,"flow-catalogs.json")}function Ia(){let e=process.env.FLOW_HOME??de.join(Ae.homedir(),Kn);return de.join(e,"config.json")}var xp=5*1024*1024,Ip=3,Gn=class{filePath;constructor(){this.filePath=wa(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{xe.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=de.dirname(this.filePath);xe.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(xe.statSync(this.filePath).size>xp){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);xe.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=de.dirname(this.filePath),r=de.basename(this.filePath,".log"),n=xe.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Ip))xe.unlinkSync(de.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
- `);}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 va(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 kr={debug:0,info:1,warn:2,error:3},ar={context:"cli",transports:[],minLevel:"warn",debugModules:null};function vp(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function je(e,t){if(e==="tui"){let r=vp();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 ba(){return ar.transports}function Pa(e,t){let{debugModules:r,minLevel:n}=ar;return ar.context==="tui"&&r&&r!=="all"?r.has(t)?kr[e]>=kr.debug:kr[e]>=kr.warn:kr[e]>=kr[n]}var Ea=new Map;function Yn(e,t,r){if(!Pa(e,t))return;let n={level:e,module:t,message:Es(r),timestamp:new Date};for(let o of ba())o.write(n);}function x(e){let t=Ea.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 Ea.set(e,r),r}var Ms=x("encryption"),$s="__encrypted__";function bp(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(bp(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),Cp=promisify(exec),et=x("encryption:macos-keyvault"),Ar=class{static async isAvailable(){try{let{stdout:t}=await Cp("command -v security");return et.debug(`security binary found at: ${t.trim()}`),!0}catch{return et.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{et.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 et.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return et.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{et.debug(`Storing secret: service=${t}, account=${r}`),await Rs("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),et.debug("security add-generic-password succeeded");}catch(o){let s=o;throw et.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return et.debug(`Deleting secret: service=${t}, account=${r}`),await Rs("security",["delete-generic-password","-a",r,"-s",t]),et.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return et.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function f(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 ie(e){process.stdout.write(M.green(` \u2713 ${f(e)}
6
- `));}function T(e){process.stderr.write(M.red(` \u2717 ${f(e)}
7
- `));}function C(e){process.stdout.write(M.cyan(` \u2139 ${f(e)}
8
- `));}function Mr(e,t){let r=t.map(a=>a.map(f)),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(`
9
- `),process.stdout.write(` ${M.bold(i(e))}
10
- `),process.stdout.write(` ${M.dim(s)}
2
+ import {execa}from'execa';import ac,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Sf,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as $r from'crypto';import {randomUUID,createHash}from'crypto';import*as ve from'fs';import ve__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as fe from'path';import fe__default,{join,dirname,normalize,resolve,sep,relative,isAbsolute,basename}from'path';import*as Le from'os';import Le__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as Bi from'readline';import {createInterface}from'readline';import R from'chalk';import ri from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Zm from'jsonwebtoken';import lf from'ink-big-text';import ru from'ink-spinner';import*as ft from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import eg from'proper-lockfile';import pg from'extract-zip';import {simpleGit}from'simple-git';import qi from'semver';import Ea from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var Wp=Object.defineProperty;var Us=(e,t)=>()=>(e&&(t=e(e=0)),t);var zp=(e,t)=>{for(var r in t)Wp(e,r,{get:t[r],enumerable:true});};function km(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 li(e){if(tl.some(r=>r.test(e)))return true;let t=km(e);return !!(t&&tl.some(r=>r.test(t)))}function Am(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Or(e,t){let r=Am(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&&li(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var tl,xn=Us(()=>{tl=[/^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 cg(){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 sc(){return oc??=cg(),oc}var oc,ic=Us(()=>{});var cc={};zp(cc,{GitRepoAdapter:()=>Vr});function lc(e,t){if(!ug.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var ug,Vr,Ci=Us(()=>{ic();xn();ug=/^[a-zA-Z0-9_.-]+$/;Vr=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(li(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return lc(a,"owner"),lc(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 ac.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 ac.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 sc();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 eo="FLOW",te="flow-skills",Fs="flow-cli",mn="internal",kr="external",Ar={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"}},_a={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},js=new Set(["internal","external"]),fn={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",Ve=5,ir=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Da=new Set(["skill","mcp","bundle"]),S=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,bundleInstallFlow:null,catalogFilters:{types:new Set(Da),origins:new Set(js)},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(Da)},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(js)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var to="aes-256-gcm",qp=16,Oa=16,gn=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=$r.randomBytes(qp),n=$r.createCipheriv(to,this.key,r,{authTagLength:Oa}),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:to}}decrypt(t){if(t.algorithm!==to)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=$r.createDecipheriv(to,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Oa});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var Yp=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Zp=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Qp=/[A-Za-z0-9+/]{40,}={0,2}/g;function Ks(e){return e.replace(Yp,"Bearer ***").replace(Zp,"***").replace(Qp,"***")}var yn=".claude",ro=".flow";function Na(e,t){return Hs(te,e,t)}function Vs(e){return fe.join(Le.homedir(),yn,"plugins","marketplaces",te,"plugins","native",e)}function no(){return fe.join(Le.homedir(),yn,"plugins","marketplaces",te,".claude-plugin","marketplace.json")}function oo(){return fe.join(Le.homedir(),yn,"plugins","known_marketplaces.json")}function Ba(){return fe.join(Le.homedir(),yn,"plugins","marketplaces",te)}function Ua(){return fe.join(Le.homedir(),ro,"cache","install.lock")}function Fa(){return fe.join(Le.homedir(),ro,"logs","flowsetup.log")}function Hs(e,t,r){return fe.join(Le.homedir(),yn,"plugins","cache",e,t,r)}function ar(e){let t=e==="global"?Le.homedir():process.cwd();return fe.join(t,".claude","skills")}function hn(e){let t=e==="global"?Le.homedir():process.cwd();return fe.join(t,".claude","skills-lock.json")}function so(e="user"){return e==="project"?fe.join(process.cwd(),".opencode","plugins"):fe.join(Le.homedir(),".config","opencode","plugins")}function ja(){return fe.join(Le.homedir(),ro,"flow-catalogs.json")}function Ka(){let e=process.env.FLOW_HOME??fe.join(Le.homedir(),ro);return fe.join(e,"config.json")}var em=5*1024*1024,tm=3,io=class{filePath;constructor(){this.filePath=Fa(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{ve.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=fe.dirname(this.filePath);ve.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ve.statSync(this.filePath).size>em){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ve.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=fe.dirname(this.filePath),r=fe.basename(this.filePath,".log"),n=ve.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(tm))ve.unlinkSync(fe.join(t,o));}catch{}}};var ao=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
+ `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var lo=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var co=[],Js=new Set;function Gs(){return co}function Va(e){return Js.add(e),()=>{Js.delete(e);}}var uo=class{write(t){co.push(t),co.length>100&&co.shift();for(let r of Js)r();}};var Mr={debug:0,info:1,warn:2,error:3},cr={context:"cli",transports:[],minLevel:"warn",debugModules:null};function rm(){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 Re(e,t){if(e==="tui"){let r=rm();cr={context:e,transports:[new uo,new io],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?cr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?cr={context:e,transports:[new ao("cli")],minLevel:"debug",debugModules:null}:cr={context:e,transports:[new lo],minLevel:"info",debugModules:null};}function Ha(){return cr.transports}function Ja(e,t){let{debugModules:r,minLevel:n}=cr;return cr.context==="tui"&&r&&r!=="all"?r.has(t)?Mr[e]>=Mr.debug:Mr[e]>=Mr.warn:Mr[e]>=Mr[n]}var Ga=new Map;function po(e,t,r){if(!Ja(e,t))return;let n={level:e,module:t,message:Ks(r),timestamp:new Date};for(let o of Ha())o.write(n);}function x(e){let t=Ga.get(e);if(t)return t;let r={debug:n=>po("debug",e,n),info:n=>po("info",e,n),warn:n=>po("warn",e,n),error:n=>po("error",e,n)};return Ga.set(e,r),r}var Ws=x("encryption"),zs="__encrypted__";function nm(e){return typeof e=="object"&&e!==null&&zs in e&&e[zs]===true}function Xs(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[zs]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Ws.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(nm(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Ws.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Ws.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var qs=promisify(execFile),im=promisify(exec),nt=x("encryption:macos-keyvault"),Lr=class{static async isAvailable(){try{let{stdout:t}=await im("command -v security");return nt.debug(`security binary found at: ${t.trim()}`),!0}catch{return nt.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{nt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await qs("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return nt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return nt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{nt.debug(`Storing secret: service=${t}, account=${r}`),await qs("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),nt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw nt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return nt.debug(`Deleting secret: service=${t}, account=${r}`),await qs("security",["delete-generic-password","-a",r,"-s",t]),nt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return nt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function h(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function re(e){process.stdout.write(R.green(` \u2713 ${h(e)}
6
+ `));}function E(e){process.stderr.write(R.red(` \u2717 ${h(e)}
7
+ `));}function T(e){process.stdout.write(R.cyan(` \u2139 ${h(e)}
8
+ `));}function Rr(e,t){let r=t.map(a=>a.map(h)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
9
+ `),process.stdout.write(` ${R.bold(i(e))}
10
+ `),process.stdout.write(` ${R.dim(s)}
11
11
  `);for(let a of r)process.stdout.write(` ${i(a)}
12
12
  `);process.stdout.write(`
13
- `);}function $r(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function Me(e){process.stdout.write(JSON.stringify(e)+`
15
- `);}function Ke(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function q(e){return e instanceof Error?e.message:String(e)}function Ot(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),Mp=[{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"}],G=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 Lp(e){let t=wi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(f(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Nt=class e{static async isAvailable(){try{let{stdout:t}=await Ds("command -v secret-tool");G.debug(`secret-tool found at: ${t.trim()}`);}catch{return G.debug("secret-tool binary not found in PATH"),false}try{return await _s("secret-tool",["lookup","service","__flow_connectivity_check__"]),G.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(G.debug(`Secret Service D-Bus not available: ${n}`),false):(G.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of Mp)try{return await Ds(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;G.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 G.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await Lp(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return G.info(`Running: ${t.command}`),await $p("Installing secret-tool...",()=>Ds(t.command)),e.isAvailable()}catch{return G.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{G.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await _s("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return G.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return G.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){G.debug(`Storing secret: service=${t}, account=${r}`),G.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),G.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),G.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?(G.debug("secret-tool store succeeded"),o()):(G.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=>{G.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return G.debug(`Deleting secret: service=${t}, account=${r}`),await _s("secret-tool",["clear","service",t,"account",r]),G.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return G.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var Dp=promisify(execFile),tt=x("encryption:windows-keyvault"),Os=1,Op=1,Np=2,Up=3;function Ns(e,t){return `${e}:${t}`}var Us=`
13
+ `);}function _r(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
+ `);}function _e(e){process.stdout.write(JSON.stringify(e)+`
15
+ `);}function Je(e){process.stderr.write(JSON.stringify(e)+`
16
+ `);}function Z(e){return e instanceof Error?e.message:String(e)}function Ft(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var Ys=promisify(execFile),Zs=promisify(exec),um=[{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 dm(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 pm(e){let t=Bi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var jt=class e{static async isAvailable(){try{let{stdout:t}=await Zs("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 Ys("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 um)try{return await Zs(`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 pm(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return z.info(`Running: ${t.command}`),await dm("Installing secret-tool...",()=>Zs(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 Ys("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 Ys("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 gm=promisify(execFile),ot=x("encryption:windows-keyvault"),Qs=1,ym=1,hm=2,Sm=3;function ei(e,t){return `${e}:${t}`}var ti=`
17
17
  using System;
18
18
  using System.Runtime.InteropServices;
19
19
  using System.Text;
@@ -49,7 +49,7 @@ public class FlowCredManager {
49
49
 
50
50
  public static string Read(string target) {
51
51
  IntPtr credPtr;
52
- if (!CredRead(target, ${Os}, 0, out credPtr)) return "";
52
+ if (!CredRead(target, ${Qs}, 0, out credPtr)) return "";
53
53
  try {
54
54
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
55
55
  if (cred.CredentialBlobSize <= 0) return "";
@@ -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[] { ${Np}, ${Up}, ${Op} };
66
+ int[] persistLevels = new int[] { ${hm}, ${Sm}, ${ym} };
67
67
  int lastErr = 0;
68
68
  try {
69
69
  foreach (int persist in persistLevels) {
@@ -71,7 +71,7 @@ public class FlowCredManager {
71
71
  try {
72
72
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
73
73
  var cred = new CREDENTIAL();
74
- cred.Type = ${Os};
74
+ cred.Type = ${Qs};
75
75
  cred.TargetName = targetPtr;
76
76
  cred.CredentialBlobSize = bytes.Length;
77
77
  cred.CredentialBlob = blobPtr;
@@ -89,137 +89,146 @@ public class FlowCredManager {
89
89
  }
90
90
 
91
91
  public static bool Delete(string target) {
92
- return CredDelete(target, ${Os}, 0);
92
+ return CredDelete(target, ${Qs}, 0);
93
93
  }
94
94
  }
95
- `;function cn(e){return e.replace(/'/g,"''")}function Zn(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Fp(e){return `Add-Type -TypeDefinition @'
96
- ${Us}
95
+ `;function wn(e){return e.replace(/'/g,"''")}function mo(e){return ["-NoProfile","-NonInteractive","-Command",e]}function wm(e){return `Add-Type -TypeDefinition @'
96
+ ${ti}
97
97
  '@
98
- [FlowCredManager]::Read('${cn(e)}')`}function Bp(e,t,r){return `Add-Type -TypeDefinition @'
99
- ${Us}
98
+ [FlowCredManager]::Read('${wn(e)}')`}function xm(e,t,r){return `Add-Type -TypeDefinition @'
99
+ ${ti}
100
100
  '@
101
- [FlowCredManager]::Write('${cn(e)}', '${cn(t)}', '${cn(r)}')`}function jp(e){return `Add-Type -TypeDefinition @'
102
- ${Us}
101
+ [FlowCredManager]::Write('${wn(e)}', '${wn(t)}', '${wn(r)}')`}function Im(e){return `Add-Type -TypeDefinition @'
102
+ ${ti}
103
103
  '@
104
- [FlowCredManager]::Delete('${cn(e)}')`}async function Qn(e){return Dp("powershell.exe",e)}var Lr=class{static async isAvailable(){try{let{stdout:t}=await Qn(Zn('Write-Output "ok"')),r=t.trim()==="ok";return tt.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
- `)[0]:"unknown error";return tt.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Ns(t,r);tt.debug(`Looking up secret: target=${n}`);let o=Fp(n),{stdout:s}=await Qn(Zn(o)),i=s.trim();return tt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
- `)[0]:"unknown error";return tt.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);tt.debug(`Storing secret: target=${o}`);let s=Bp(o,n,r),{stdout:i}=await Qn(Zn(s)),a=i.trim();if(a.startsWith("OK:")){let c=a.split(":")[1];tt.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 tt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Ns(t,r);tt.debug(`Deleting secret: target=${n}`);let o=jp(n),{stdout:s}=await Qn(Zn(o)),i=s.trim()==="True";return tt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
- `)[0]:"unknown error";return tt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var Kp=32,Vp="flow-plugins-cli-fallback",Bs="flow-plugins-cli-fallback",Hp={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 Jp(){let e=`${Ae.hostname()}${Ae.userInfo().username}`;return Tr.scryptSync(e,Vp,Kp)}function Gp(){let e=Jp(),t=new on(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=Gp()),to}var $e=class{warned=false;async getSecret(t,r){return eo().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Hp[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
104
+ [FlowCredManager]::Delete('${wn(e)}')`}async function fo(e){return gm("powershell.exe",e)}var Dr=class{static async isAvailable(){try{let{stdout:t}=await fo(mo('Write-Output "ok"')),r=t.trim()==="ok";return ot.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
+ `)[0]:"unknown error";return ot.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=ei(t,r);ot.debug(`Looking up secret: target=${n}`);let o=wm(n),{stdout:s}=await fo(mo(o)),i=s.trim();return ot.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
+ `)[0]:"unknown error";return ot.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=ei(t,r);ot.debug(`Storing secret: target=${o}`);let s=xm(o,n,r),{stdout:i}=await fo(mo(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];ot.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
107
+ `)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw ot.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=ei(t,r);ot.debug(`Deleting secret: target=${n}`);let o=Im(n),{stdout:s}=await fo(mo(o)),i=s.trim()==="True";return ot.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
+ `)[0]:"unknown error";return ot.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var vm=32,bm="flow-plugins-cli-fallback",ni="flow-plugins-cli-fallback",Em={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 Pm(){let e=`${Le.hostname()}${Le.userInfo().username}`;return $r.scryptSync(e,bm,vm)}function Tm(){let e=Pm(),t=new gn(e),r=Xs(t);return new ri({projectName:ni,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var yo=null;function go(){return yo||(yo=Tm()),yo}var De=class{warned=false;async getSecret(t,r){return go().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Em[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 xe.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Fs({projectName:Bs});xe.rmSync(t.path,{force:!0});}catch{}to=null;}};async function js(){if($e.hasExistingData())return new $e;switch(process.platform){case "darwin":return await Ar.isAvailable()?new Ar:new $e;case "linux":return await Nt.isAvailable()?new Nt:await Nt.ensureInstalled()?new Nt:new $e;case "win32":return await Lr.isAvailable()?new Lr:new $e;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 Ut(){return oo||(oo=js()),oo}function so(){oo=null;}async function te(){let t=await(await Ut()).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 Ut()).setSecret(vt,Ks,JSON.stringify(e));}async function Ma(){let e=await Ut();await e.deleteSecret(vt,Ks),await e.deleteSecret(vt,Vs),await e.deleteSecret(vt,Hs);}async function $a(){return (await Ut()).getStoragePath()}async function La(e){await(await Ut()).setSecret(vt,Vs,JSON.stringify(e));}async function io(){let t=await(await Ut()).getSecret(vt,Vs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ao(e){await(await Ut()).setSecret(vt,Hs,JSON.stringify(e));}async function Ra(){let t=await(await Ut()).getSecret(vt,Hs);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ft(){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")}}un();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 Da={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&&Da[r]?new Error(Da[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=Rr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Zp(e.tenant);let r;try{r=await jl.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 La({accessToken:r.access_token,expiresAt:n});let o=lo(r.access_token);await ao({sub:o.sub,name:o.name,email:o.email});}var Oa=x("lib:tokenProvider");async function Bt(){if(await Ft()){let n=await io();if(n)return n.accessToken}Oa.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");$e.clearFallbackFile(),so(),await lr(t);let r=await io();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Oa.debug("Token refreshed successfully"),r.accessToken}un();var co=x("api:metrics");function Na(){return Rr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ua(e,t,r){return jl.post(e,{json:t,headers:r})}async function tm(e){let t=await Ra();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 E(e,t){let r=await Bt(),n=await tm(r),o=await te();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 Ua(Na(),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 Fa(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 Ua(Na(),o,{FlowTenant:n}),co.debug(`Anonymous metrics event sent: ${e}`);}catch(n){co.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var P={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},rt={...rm};function Ba(e){let t=Date.now();rt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function cr(e){rt.currentStep=e,rt.stepStart=Date.now();}function H(){return {...rt}}function Pt(){return rt.sessionStart===0?0:Date.now()-rt.sessionStart}function ur(){return rt.stepStart===0?0:Date.now()-rt.stepStart}function ja(){rt.tuiSessionStart=Date.now();}function Ka(){return rt.tuiSessionStart===0?0:Date.now()-rt.tuiSessionStart}var nm=3e3,om=x("abandonment");async function uo(e){let{currentStep:t,sessionStart:r}=H();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Pt()};try{await Promise.race([E(P.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 Va(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var sm=3e3,im=x("session-end");async function pn(e,t,r){let n=Ka(),s=[E(P.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(uo(e));try{await Va(Promise.all(s).then(()=>{}),sm);}catch(i){im.warn(`Session end event failed: ${String(i)}`);}}var um=2e3;function Ja(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=y(l=>l.pendingExit),o=y(l=>l.setPendingExit),s=y(l=>l.activeTab),i=y(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),pn("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 Ga({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 Ve=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 de__default.join(Ae__default.homedir(),".claude","settings.json")}function Xs(){let e=dr();if(!xe__default.existsSync(e))return {status:"missing"};let t=xe__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 za(e){let t=dr();xe__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;xe__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),xe__default.renameSync(r,t);}function Xa(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=Xa(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function mo(e){za(e.merged);}function qa(){let e=Xs();return e.status!=="ok"?false:qs(e.settings)!==null}var Ya="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Ya=e.version);}catch{}var oe=Ya;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 Qa(){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),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:I}=Ve(),b=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),k=()=>{d("fields"),p(null),t(A=>({...A,clientSecret:""})),n("clientSecret");},R=async()=>{g.current=true;let A=b();try{await bt(A);}catch(V){a(V instanceof Error?V.message:"Failed to persist credentials"),k(),g.current=false;return}let{clientSecret:S,..._}=A;w(_),I(true),E(P.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),yn({starterKit:_.starterKit});},L=async A=>{g.current=true;let S=b();try{mo(A),await bt(S);}catch(X){a(X instanceof Error?X.message:"Failed to persist credentials"),k(),g.current=false;return}let{clientSecret:_,...V}=S;w(V),I(true),E(P.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{}),yn({starterKit:V.starterKit});},B=A=>{try{return po(b(),{allowOverwriteMalformed:A})}catch(S){return S instanceof pr?(d("malformedConfirm"),null):(a(S instanceof Error?S.message:"Failed to read settings.json"),d("fields"),null)}};useInput((A,S)=>{if(!(l||g.current)){if(u==="preview"){S.return&&m?L(m):S.escape?R():A==="q"&&k();return}if(u==="malformedConfirm"){if(S.return){let _=B(true);_&&(p(_),L(_));}else S.escape&&k();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")Q();else {let _=ut.indexOf(r);n(ut[_+1]);}}},{isActive:true});let Q=async()=>{let A={};for(let S of ut)e[S].trim()||(A[S]="This field is required");if(Object.keys(A).length>0){s(A);let S=ut.find(_=>A[_]);S&&n(S);return}c(true),a(null),h.current+=1;try{await lr(b());let S=B(!1);S&&(p(S),d("preview"));}catch(S){let _=S instanceof Error?S.message:"Authentication failed";a(_),Fa(P.CLI_AUTH_FAILED,{error_code:Pm(S),attempt:h.current},e.tenant.trim()).catch(()=>{}),t(V=>({...V,clientSecret:""}));}finally{c(false);}},ct=A=>S=>{t(_=>({..._,[A]:S})),o[A]&&s(_=>({..._,[A]: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(A=>jsx(Box,{marginBottom:1,children:jsx(Ga,{label:Em[A],value:e[A],onChange:ct(A),masked:A==="clientSecret",isActive:r===A&&!l,error:o[A]})},A))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",f(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function _r(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Tm,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",oe]})})]})}function km(){let e=Ia();if(!xe__default.existsSync(e))return {};try{return JSON.parse(xe__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ys=null;function Am(){return Ys===null&&(Ys=km()),Ys}function dt(){return !!Am().ENABLE_EXPERIMENTAL_BETAS}var il={discover:"Discover",installed:"Installed",marketplaces:"Marketplaces"},Mm=dt()?["discover","installed","marketplaces"]:["discover","installed"];function al(){let e=y(t=>t.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Mm.map(t=>jsx(Box,{marginRight:1,children:t===e?jsx(Text,{bold:true,inverse:true,children:` ${il[t]} `}):jsx(Text,{dimColor:true,children:` ${il[t]} `})},t))})}var Le=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function cl(){let e=y(i=>i.focus),t=Le(i=>i.query),r=Le(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 _m=["skill","mcp","plugin"].map((e,t)=>({key:String(t+2),type:e,...Cr[e]})),Dm=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...ma[e]}));function ul(){let e=y(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"]})]}),_m.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"]})]}),Dm.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 dl({type:e}){let{label:t,color:r}=Cr[e];return jsx(Text,{color:r,children:t})}function fl({origin:e}){return e===rn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var go=Um.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(dl,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(fl,{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 ",Ot(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Dr({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function hl({items:e,emptyMessage:t}){let r=y(l=>l.selectedIndex);if(e.length===0)return jsx(Dr,{message:t});let n=Math.max(0,r-Math.floor(Fe/2)),o=Math.min(e.length,n+Fe);o===e.length&&(n=Math.max(0,o-Fe));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 xl({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 vl({groups:e,emptyMessage:t}){let r=y(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 h of p.items)n.push({kind:"item",item:h,itemIndex:o,key:`i-${p.scope}-${h.name}-${h.marketplace??""}`}),o++;}if(o===0)return jsx(Dr,{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(Fe/2)),c=Math.min(n.length,l+Fe);c===n.length&&(l=Math.max(0,c-Fe));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(xl,{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",marketplaces:"Marketplaces"};function Pl({items:e,tabId:t,emptyMessage:r,groups:n}){return jsxs(Box,{flexDirection:"column",children:[jsx(cl,{}),jsx(ul,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Jm[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]})]}),n&&n.length>0?jsx(vl,{groups:n,emptyMessage:r}):jsx(hl,{items:e,emptyMessage:r})]})}function El({filteredItems:e,emptyMessage:t,groups:r}){let n=y(o=>o.activeTab);return jsx(Box,{flexDirection:"column",flexGrow:1,children:n==="discover"?jsx(Pl,{items:e,tabId:"discover",emptyMessage:t},"discover"):jsx(Pl,{items:e,tabId:"installed",emptyMessage:t,groups:r},"installed")})}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=y(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 Cl({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"," ",f(e)]})}):null}function ho({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rf,{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 pt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=y(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 ii=Object.entries(nn),Rl=[...ii.map(([,e])=>e.actionLabel),"Cancel"],_l=Object.fromEntries(ii.map(([,e])=>[e.actionLabel,e.description]));function Dl(e){let t=ii.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var lf=x("provider.registry"),cf=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()+cf}),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"&&lf.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 uf={user:"global",project:"project",local:"local"};function Io(e){return e?uf[e]:"global"}var Re=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},Kt=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};un();function Vt(){return jl.create({prefix:Rr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Bt();e.headers.set("Authorization",`Bearer ${t}`);let r=await te();r?.tenant&&or.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var pf=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);pf.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 xf={retries:5,minTimeout:50};async function ai(e,t){mkdirSync(dirname(e),{recursive:true});let r=await wf.lock(e+".lock",{realpath:false,retries:xf});try{return await t()}finally{await r();}}var bo=class{filePath;constructor(t){this.filePath=t??xa();}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 ai(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 ai(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ai(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 If=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function wn(e){if(!e||!If.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var vf=/^[^@]+@[^@]+$/;function Nr(e){return vf.test(e)}function Ur(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var bf=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Pf(e){if(!bf.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 Fr(e,t){let r=Ur(e);Pf(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Ef=/^[\w./:@?&=+#%-]+$/;function Po(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Ef.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Cf=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 Vt().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){wn(t);try{return await Vt().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 Vt().head("v1/plugins/catalog"),Cf.debug("ping ok"),!0}catch{return false}}};var pe=new vo,Ct=new bo;pe.register(new Eo);var Hl=false;async function Jl(){if(Hl)return;Hl=true;let e=await Ct.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(li(),Vl));for(let r of e)pe.register(new t(r.id,r.name,r.source));}async function Ht(){return pe.fetchAll()}async function Gl(){return pe.fetchAllWithErrors()}async function jr(e){wn(e);try{return await Vt().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 Wl(e){wn(e);try{let t=await Vt().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 Vt().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 zl(e,t){let r=de.resolve(t);await mt.mkdir(r,{recursive:true});let n=de.join(de.dirname(r),`${randomUUID()}.zip`);try{await mt.writeFile(n,e),await $f(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=de.resolve(r,o.fileName);if(!i.startsWith(r+de.sep)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(de.resolve(de.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 mt.unlink(n);}catch{}}}async function ci(e){await mt.rm(e,{recursive:true,force:true});}async function Jt(){let e=Sa();await mt.mkdir(de.dirname(e),{recursive:true});try{await mt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await wf.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function _f(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:ee,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Yl(){let e=Vn();if(!xe__default.existsSync(e))return null;try{return JSON.parse(xe__default.readFileSync(e,"utf-8"))}catch{return null}}function Df(){let e=Yl();if(e)return e;let t=_f(),r=Vn();return xe__default.mkdirSync(de__default.dirname(r),{recursive:true}),ui(t),t}function ui(e){let t=Vn(),r=`${t}.${randomUUID()}.tmp`;xe__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),xe__default.renameSync(r,t);}function Of(){let e=Hn(),t={};try{xe__default.existsSync(e)&&(t=JSON.parse(xe__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[ee])return;t[ee]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:ha(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;xe__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),xe__default.renameSync(r,e);}function Zl(e,t){To(e.name),Of();let r=Cs(e.name);xe__default.mkdirSync(de__default.dirname(r),{recursive:true});try{xe__default.lstatSync(r),xe__default.rmSync(r,{recursive:!0,force:!0});}catch{}xe__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Df();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}),ui(n));}function di(e){To(e);let t=Cs(e);try{xe__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Yl();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&ui(r);}var Uf=x("mcpConfigReader"),Ff=500,Bf=512;function jf(){return de__default.join(Ae__default.homedir(),".claude.json")}function Kf(){return de__default.join(process.cwd(),".mcp.json")}function ec(e){if(!xe__default.existsSync(e))return null;try{return JSON.parse(xe__default.readFileSync(e,"utf-8"))}catch{return Uf.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pi(e){if(!xn(e))return {};let t=e.mcpServers;return xn(t)?t:{}}function mi(e,t){return Object.keys(e).slice(0,Ff).map(n=>({name:f(n.slice(0,Bf)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function rc(){let e=[],t=jf(),r=ec(t);if(xn(r)){let a=r,l=pi(a);e.push(...mi(l,"user"));let c=process.cwd();if(xn(a.projects)){let u=a.projects[c];if(xn(u)){let d=pi(u);e.push(...mi(d,"local"));}}}let n=Kf(),o=ec(n),s=pi(o);e.push(...mi(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 Ge=x("storage");async function Hf(e,t){try{await E(P.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"plugin",source:t,interface:H().interfaceType});}catch(r){Ge.warn(`Failed to send uninstall metrics: ${String(r)}`);}}function Jf(e,t,r){let n=t==="enabled"?P.CLI_TOOL_ENABLED:P.CLI_TOOL_DISABLED;E(n,{tool_id:e,source:r,interface:H().interfaceType}).catch(o=>Ge.warn(`Failed to send ${t} metrics: ${String(o)}`));}function hi(){return de__default.join(Ae__default.homedir(),".claude","plugins","installed_plugins.json")}function Gf(){return de__default.join(Ae__default.homedir(),".claude","plugins")}function nc(e){let t=de__default.resolve(e),r=de__default.resolve(Gf()),n=de__default.resolve(de__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+de__default.sep)||t===r,s=t.startsWith(n+de__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function oc(e="user"){return e==="local"?de__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?de__default.join(process.cwd(),".claude","settings.json"):de__default.join(Ae__default.homedir(),".claude","settings.json")}function kt(){let e=hi();if(!xe__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(xe__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function sc(){let e=hi();try{let t=await xe__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Wf(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function ic(e,t){try{xe__default.mkdirSync(de__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;xe__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),xe__default.renameSync(r,e);}catch(r){throw Wf(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Tt(e){ic(hi(),e);}function In(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=de__default.join(e,".claude-plugin"),n=de__default.join(r,"plugin.json");if(xe__default.existsSync(n))try{return JSON.parse(xe__default.readFileSync(n,"utf-8"))}catch{return null}let o=de__default.join(r,"marketplace.json");if(xe__default.existsSync(o))try{let s=JSON.parse(xe__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Si(e="user"){let t=oc(e);if(!xe__default.existsSync(t))return {};try{return JSON.parse(xe__default.readFileSync(t,"utf-8"))}catch{return {}}}function ac(e,t="user"){ic(oc(t),e);}function Xf(e,t){let{name:r,marketplace:n}=In(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>In(i).name===r)[0],!o)throw Ge.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function qf(e,t){let{name:r,marketplace:n}=In(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>In(i).name===r)[0],o?{key:o,name:r}:null}function fi(e="user"){return Si(e).enabledPlugins??{}}function gi(e,t="user"){let r=Si(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,ac(r,t);}function vn(e,t,r="user"){let n=Si(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},ac(n,r);}function Yf(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 re(){let e=kt(),t=fi(),r=fi("project"),n=fi("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=In(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Yf(p).map(g=>{let w=zf(g.installPath,d),b=(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:w?.description,author:w?.author,status:b===false?"disabled":"enabled"}})}),i=rc(),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){Ge.debug(`[${e}] Acquiring lock to uninstall`);let r=await Jt();try{let n=kt(),o=qf(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`);Ge.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),nc(l.installPath);let c=de__default.dirname(l.installPath);Ge.debug(`[${i}] Removing directory: ${c}`),xe__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}),gi(s,t),di(i);}else n.plugins[s]=u,Tt(n),gi(s,t);}else {Ge.debug(`[${i}] Resolved key: ${s}`);for(let u of a){nc(u.installPath);let d=de__default.dirname(u.installPath);Ge.debug(`[${i}] Removing directory: ${d}`),xe__default.rmSync(d,{recursive:!0,force:!0}),gi(s,u.scope);}di(i);let{[s]:l,...c}=n.plugins;Tt({...n,plugins:c});}await Hf(i,a[0].origin??"internal"),Ge.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function bn(e,t,r){Ge.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Jt();try{let o=kt(),{key:s,name:i}=Xf(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";Ge.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),vn(s,t==="enabled",l),Jf(i,t,c),Ge.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Zf=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Qf=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function To(e){if(!Zf.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function eg(e){if(!Qf.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 Gt=x("installer");function tg(e,t){let r=`${e}@${ee}`,o=kt().plugins[r];if(o&&!t)throw new Re(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function rg(e,t,r){r&&await ci(t);try{Gt.debug(`[${t}] Extracting archive...`),await zl(e,t);}catch(n){throw await ci(t),n}}function ng(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),vn(e,true,n);}async function og(e,t,r,n,o){try{await E(P.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:o,scope:n,version:t,duration_ms:r,interface:H().interfaceType});}catch(s){Gt.warn(`Failed to send install metrics: ${String(s)}`);}}async function sg(e,t,r){try{await E(P.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:H().interfaceType});}catch(n){Gt.warn(`Failed to send install-failed metrics: ${String(n)}`);}}async function ve(e,t={}){let r=Date.now(),n=null;try{Gt.debug(`[${e}] Acquiring lock...`),n=await Jt();let{pluginKey:o,alreadyInstalled:s}=tg(e,t.force);Gt.debug(`[${e}] Fetching manifest...`);let i=await jr(e);To(i.name),eg(i.version),Gt.debug(`[${e}] Downloading archive...`);let a=await Wl(e),l=t.scope??"user",c=ya(i.name,i.version);await rg(a,c,!!s&&!!t.force),ng(o,c,i.version,l,"internal",t.providerId),Zl(i,c);let u=Date.now()-r;Gt.debug(`[${e}] Installed successfully in ${u}ms`);let d={name:i.name,version:i.version,path:c,duration_ms:u};return t.skipMetrics||await og(i.name,i.version,u,Io(l),"internal"),d}catch(o){throw await sg(e,o,"internal"),Gt.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var ig=x("commands:helpers");async function he(){let e=await te();if(!e)return T("Not authenticated. Run: flow auth login"),false;try{await Bt();}catch(t){return ig.debug(`Token validation failed: ${String(t)}`),T("Session expired. Run: flow auth login"),false}return !e.starterKit||e.starterKit.trim()===""?(T("Starter kit not set. Run: flow auth login"),false):true}async function Wt(e){let t=wi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(f(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function lc(e){let t=wi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(f(e),n=>{t.close(),r(n.trim());});})}var Pn=x("claudeProxy"),vi="claude ",cc="flow ",xi=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Ii=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";}},ag=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,lg=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,cg=/^(flow|claude)\s+auth\s+login(\s|$)/;function ug(e){dc(e);let t=e.slice(vi.length);if(!ag.test(t))throw new Ii(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 dc(e){if(!e||!/^claude /.test(e))throw new xi(e)}async function Se(e){dc(e);let t=e.slice(vi.length).split(/\s+/).filter(Boolean),r=dg(t);Pn.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 Pn.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 pc(o)?new Ao:o}}function dg(e){return e.length>=3?e[2]:e.join(" ")}function pc(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function pg(e){return e.startsWith(cc)?vi+e.slice(cc.length):e}function mg(e){return lg.test(e)||cg.test(e)}function fg(e){let t=0;for(;t<e.length&&mg(e[t]);)t++;return e.slice(t)}var gg=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function yg(e,t){return !t||e.includes("--scope")||!gg.test(e)?e:`${e} --scope ${t}`}async function bi(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=fg(r).map(i=>pg(i)).map(i=>yg(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)ug(i);Pn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Se(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Se(o[i]),s.exitCode!==0)return s;return s}async function Mo(e,t,r){let n=Ur(e),o=t?.trim();if(!o&&(o=(await lc(`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?.(),Pn.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"}`);Pn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw pc(s)?new Ao:s}}var Ig=6e4,zt=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 Xt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Ig}}).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 zt("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new zt(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new zt(`Failed to clone ${e}: ${i}`,e,false,false)}}async function qt(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 bg(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Pg(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Eg(e){return typeof e=="object"&&e!==null&&e.source==="github"}function $o(e,t){let r=e.source;if(bg(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(Pg(r))return {cloneUrl:r.url,subPath:"."};if(Eg(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 Yt=x("claude-code.adapter");function Tg(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(!xe__default.existsSync(s))return r;try{let i=JSON.parse(xe__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 xc(e,t){let r=e.catalogId?pe.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=Tg(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 Xt(n.cloneUrl,n.ref);let c=n.subPath==="."?l:join(l,n.subPath);if(xe__default.existsSync(a)&&xe__default.rmSync(a,{recursive:!0,force:!0}),xe__default.mkdirSync(dirname(a),{recursive:!0}),xe__default.cpSync(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await sc(),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(h=>h.scope!==i),m],Tt(d),vn(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return Yt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await qt(l).catch(()=>{});}}async function Pi(e,t,r){try{await E(P.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"plugin",source:"external",scope:Io(r),version:"unknown",duration_ms:t,interface:H().interfaceType});}catch(n){Yt.warn(`Failed to send external install metrics: ${String(n)}`);}}async function Sc(e,t){try{await E(P.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:H().interfaceType});}catch(r){Yt.warn(`Failed to send external install-failed metrics: ${String(r)}`);}}var kg={async install(e,t){if(e.origin===Er&&!e.installCommand&&!Nr(e.name))return xc(e,t);if(e.origin===Er&&e.installCommand){let r=await bi(e.installCommand,t.scope);return r.exitCode===0?(await Pi(e.name,r.duration_ms,t.scope),{success:true,message:`Installed ${e.name}`}):(await Sc(e.name,new Error(r.stderr||"Install failed")),{success:false,message:r.stderr||`Install failed with exit code ${r.exitCode}`})}if(Nr(e.name)){let r=Fr(e.name,t.scope);Yt.debug(`[${e.name}] Attempting install: ${r}`);let n=await Se(r);if(n.exitCode===0)return await Pi(e.name,n.duration_ms,t.scope),{success:true};Yt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Mo(e.name,t.marketplaceSource,()=>{});let o=await Se(r);return o.exitCode===0?(await Pi(e.name,o.duration_ms,t.scope),{success:true}):(await Sc(e.name,new Error(o.stderr||"Install failed")),{success:false,message:o.stderr||`Install failed with exit code ${o.exitCode}`})}try{let r=await ve(e.name,t);return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Yt.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 wc(e){return {async install(t,r){if(t.origin===Er&&!t.installCommand&&!Nr(t.name))return xc(t,r);if(!t.installCommand)try{let o=await ve(t.name,r);return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Yt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Yt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await bi(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:kg,skill:wc("skill"),mcp:wc("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 Mg=new Set(["gh"]),$g=Ro(Mg,"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:$g}};var Lg=new Set(["opencode"]),Rg=Ro(Lg,"use: opencode config remove mcp <name>");function _g(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 Ic(){return {async install(e,t){let r=e.catalogId?pe.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 Xt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Jn(t.scope??"user"),a=join(s,".opencode","plugins");if(xe__default.existsSync(a)){let l=xe__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/"};xe__default.mkdirSync(i,{recursive:!0}),xe__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);xe__default.existsSync(l)&&xe__default.rmSync(l,{recursive:!0,force:!0}),xe__default.mkdirSync(l,{recursive:!0}),xe__default.cpSync(s,l,{recursive:!0}),xe__default.mkdirSync(i,{recursive:!0}),xe__default.writeFileSync(join(i,`${e.name}.js`),_g(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 qt(o).catch(()=>{});}},async uninstall(e,t){let r=Jn(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);xe__default.existsSync(n)&&xe__default.rmSync(n,{force:true}),xe__default.existsSync(o)&&xe__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:Rg,skill:Ic(),plugin:Ic()}};var ft=new xo;ft.register(new Lo);dt()&&(ft.register(new _o),ft.register(new Do));function vc({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(()=>{ft.getAvailableProviders(t??"plugin").then(c).catch(()=>{});},[t]);let m=useCallback(w=>{w==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(w=>{if(w==="Cancel"){a(false);return}let I=l.find(b=>b.name===w);I?(d(I.id),a(false),s(true)):a(false);},[l]),h=useCallback(w=>{let I=Dl(w);I?r(I,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let w=[...l.map(I=>I.name),"Cancel"];return jsx(pt,{itemName:`${e} \u2014 Choose provider`,actions:w,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(pt,{itemName:`${e} \u2014 Choose scope`,actions:Rl,descriptions:_l,onAction:h,onClose:g},"scope"):jsx(pt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Uo({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=y(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 Ec({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&&f(o),p=m?`Update to v${m}`:"Update";return jsx(pt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:w=>{w==="Uninstall"?u():w===d?i(t):w.startsWith("Update")?a?.():l();},onClose:l})}function kc({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(pt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var me=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:re()})}));function Ac({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 ",Ot(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function Mc({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",h=[{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 ${Ot(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:h.map((g,w)=>{let I=w===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 $c(e){return e.adapter.removable!==false?4:2}function Lc({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 ",f(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:f(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",f(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",f(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:f(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 ",f(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",f(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",f(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 _c({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 Dc({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(L=>r.has(`${L.name}@${o}`)),i=t.filter(L=>!r.has(`${L.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((L,B)=>{if(B.escape){n();return}if(B.return){d(a[l]??null);return}if(B.upArrow){c(Q=>Math.max(0,Q-1));return}B.downArrow&&c(Q=>Math.min(a.length-1,Q+1));},{isActive:u===null}),u!==null)return jsx(Lc,{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(Fe/2)),p=Math.min(a.length,m+Fe);p===a.length&&(m=Math.max(0,p-Fe));let h=a.slice(m,p),g=m,w=a.length-p,I=s.length>0&&m<s.length,b=p>s.length,k=h.filter(L=>r.has(`${L.name}@${o}`)),R=h.filter(L=>!r.has(`${L.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"]}),k.map(L=>jsx(_c,{item:L,isSelected:a.indexOf(L)===l,isInstalled:true},L.name))]}),b&&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"]}),R.map(L=>jsx(_c,{item:L,isSelected:a.indexOf(L)===l,isInstalled:false},L.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:w>0?`\u2193 ${w} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}li();var Vg=/^https?:\/\/.+/;function Hg(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Jg(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Fc(e){let t=y(w=>w.showNotification),r=y(w=>w.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");},[]),h=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let w=m.current,I=d.current;if(!Vg.test(w)){u("URL must start with http:// or https://");return}u(null),o("adding");let b=randomUUID(),k=new Br(b,I,w);try{await k.fetchItems(),await Ct.add({id:b,name:I,source:w}),pe.register(new Br(b,I,w)),r(),e(),t(`Catalog "${I}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(R){let L=Hg(R)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Jg(R)?R.message:R instanceof Error?`Could not reach catalog URL: ${R.message}`:"Failed to validate catalog URL";t(L,"error"),o("add-url");}},[e,t,r]);return useInput((w,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}w&&!I.ctrl&&!I.meta&&(d.current=d.current+w,i(d.current));},{isActive:n==="add-name"}),useInput((w,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}w&&!I.ctrl&&!I.meta&&(m.current=m.current+w,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:h}}function Bc(e){let t=y(o=>o.showNotification),r=y(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Ct.remove(o),pe.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 Kc(){let e=y(v=>v.focus),t=y(v=>v.setFocus),r=y(v=>v.setActiveTab),n=y(v=>v.showNotification),o=me(v=>v.installedItems),[s,i]=useState(()=>pe.listAdapters().map(v=>({adapter:v,stored:null}))),[a,l]=useState(0),[c,u]=useState("list"),[d,m]=useState(0),[p,h]=useState(null),[g,w]=useState("main"),I=useRef(s);useEffect(()=>{I.current=s;},[s]),useEffect(()=>{g==="browse"&&!s[a-1]&&w("main");},[g,s,a]);let b=useCallback(()=>{(async()=>{let v=pe.listAdapters(),O=await Ct.read(),F=new Map(O.map(ge=>[ge.id,ge]));i(v.map(ge=>({adapter:ge,stored:F.get(ge.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),b();},[t,b]),useEffect(()=>{if(a===0){h(null);return}let v=I.current[a-1];if(!v)return;let O=false;return h({items:[],loading:true,error:null}),v.adapter.fetchItems().then(F=>{O||h({items:F,loading:false,error:null});}).catch(F=>{O||h({items:[],loading:false,error:F instanceof Error?F.message:"Failed to load catalog"});}),()=>{O=true;}},[a]);let k=Fc(b),R=useCallback(()=>{b(),l(0),u("list"),h(null),w("main");},[b]),{handleRemove:L}=Bc(R),B=useCallback(async v=>{w("removing"),await L(v);},[L]),Q=useCallback(async v=>{try{let O=await v.adapter.fetchItems();if(h({items:O,loading:!1,error:null}),v.stored){let F=new Date().toISOString();await Ct.updateField(v.stored.id,{lastUpdated:F}),b();}n("Marketplace updated","success");}catch(O){n(O instanceof Error?O.message:"Update failed","error");}},[b,n]),ct=useCallback(async v=>{if(!v.stored)return;let O=v.stored.autoUpdate!==false;await Ct.updateField(v.stored.id,{autoUpdate:!O}),b();},[b]),A=useCallback(()=>w("browse"),[]),S=useCallback(v=>{let O=s[a-1];if(!O)return;let F=O.adapter.removable!==false;[A,()=>{Q(O);},...F?[()=>{ct(O);},()=>{B(O.adapter.id);}]:[]][v]?.();},[s,a,A,Q,ct,B]),_=useCallback(()=>w("main"),[]),V=useCallback(()=>{let v=s[a-1];v&&Q(v);},[s,a,Q]),X=useCallback(()=>{let v=s[a-1];v&&ct(v);},[s,a,ct]),tn=useCallback(()=>{let v=s[a-1];v&&B(v.adapter.id);},[s,a,B]);if(useInput((v,O)=>{if(O.upArrow){l(F=>Math.max(0,F-1));return}if(O.downArrow){l(F=>Math.min(s.length,F+1));return}if(O.leftArrow||O.rightArrow){let F=["discover","installed","marketplaces"],ge=F.indexOf("marketplaces"),Is=O.leftArrow?F[(ge-1+F.length)%F.length]:F[(ge+1)%F.length];r(Is),t("list");return}(O.return||O.tab)&&(a===0?k.startAdd():(u("detail"),m(0)));},{isActive:g==="main"&&k.phase==="idle"&&c==="list"&&e==="marketplaces"}),useInput((v,O)=>{if(O.escape||O.tab){u("list");return}if(O.upArrow){m(F=>Math.max(0,F-1));return}if(O.downArrow){let F=s[a-1],ge=F?$c(F)-1:0;m(Is=>Math.min(Is+1,ge));return}O.return&&S(d);},{isActive:g==="main"&&k.phase==="idle"&&c==="detail"&&e==="marketplaces"}),k.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:k.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.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(k.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:k.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:k.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:k.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(k.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 v=s[a-1];if(!v)return jsx(Box,{});let O=v.adapter.id??"default",F=new Set(o.filter(ge=>ge.marketplace===v.adapter.name).map(ge=>`${ge.name}@${O}`));return jsx(Dc,{entry:v,items:p?.items??[],installedKeys:F,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(v=>v.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(Ac,{entries:s,selectedIndex:a,focusPanel:c})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:c==="detail"&&It?jsx(Mc,{entry:It,detailData:p,installedCount:Fn,focusPanel:c,actionIndex:d,onBrowse:A,onUpdate:V,onToggleAutoUpdate:X,onRemove:tn}):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"})})]})}var ce=dt()?["discover","installed","marketplaces"]:["discover","installed"];function Ti(e){return e==="marketplaces"?"marketplaces":"list"}function Vc(e,t,r){if(t.rightArrow||t.tab){let n=ce.indexOf(r.activeTab),o=ce[(n+1)%ce.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Ti(o)}]}if(t.leftArrow){let n=ce.indexOf(r.activeTab),o=ce[(n-1+ce.length)%ce.length];return [{type:"setTab",tab:o},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:Ti(o)}]}return t.downArrow?[{type:"setFocus",focus:Ti(r.activeTab)}]:[]}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=ce.indexOf(r.activeTab),s=ce[(o-1+ce.length)%ce.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.rightArrow){let o=ce.indexOf(r.activeTab),s=ce[(o+1)%ce.length];return [{type:"setTab",tab:s},{type:"setSelectedIndex",index:0},...s==="marketplaces"?[{type:"setFocus",focus:"marketplaces"}]:[]]}if(t.tab){let o=ce.indexOf(r.activeTab),s=ce[(o+1)%ce.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&&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}=y.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}=Le.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?y.getState().selectAllTypes():s.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function Wc({listLength:e}){let t=y(g=>g.focus),r=y(g=>g.selectedIndex),n=y(g=>g.actionMenuOpen),o=y(g=>g.setFocus),s=y(g=>g.setActionMenuOpen),i=Le(g=>g.query),a=Le(g=>g.setQuery),l=Le(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:w}=Le.getState();w(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,w)=>{let{activeTab:I,selectedIndex:b,actionMenuOpen:k}=y.getState();Ho(Vc(g,w,{activeTab:I}));},{isActive:t==="tabs"}),useInput((g,w)=>{let{activeTab:I,selectedIndex:b,actionMenuOpen:k}=y.getState();Ho(Hc(g,w,{activeTab:I,selectedIndex:b},c.current));},{isActive:t==="list"}),useInput((g,w)=>{Ho(Jc(g,w));},{isActive:t==="actionMenu"}),useInput((g,w)=>{let I=Gc(g,w,Le.getState().query),b=I.queryUpdate;if(Ho(I.actions),b==="reset")l(),d("");else if(b!==null){let{query:k,cursorPosition:R,setCursorPosition:L}=Le.getState();if("backspace"in b)R>0&&(a(k.slice(0,R-1)+k.slice(R)),L(R-1));else if("append"in b)a(k.slice(0,R)+b.append+k.slice(R)),L(R+b.append.length);else if("cursorMove"in b){let B=R+b.cursorMove;B>=0&&B<=k.length&&L(B);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:w,selectedIndex:I}=y.getState();g===0?w(0):I>=g&&w(g-1);},[]),h=useCallback(g=>{if(!u)return c.current=g.length,g;let w=u.toLowerCase(),I=g.filter(b=>b.name.toLowerCase().includes(w)||b.description?.toLowerCase().includes(w));return c.current=I.length,I},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:h}}function Xc(){let e=y(a=>a.notification),t=y(a=>a.showNotification),r=y(a=>a.clearNotification),n=Ve(a=>a.justAuthenticated),o=Ve(a=>a.credentials),s=Ve(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 Pe(e,t,r=false){return r?true:!Mi.valid(e)||!Mi.valid(t)?false:Mi.gt(t,e)}var $t=x("updater");async function qg(e,t,r,n,o){try{await E(P.CLI_TOOL_UPDATED,{tool_id:e,tool_type:"plugin",source:o,from_version:t,to_version:r,duration_ms:n,interface:H().interfaceType});}catch(s){$t.warn(`Failed to send update metrics: ${String(s)}`);}}function Yg(e){let t=kt(),r=`${e}@${ee}`,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 Jt();let o=Yg(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 jr(e)).version;if(!i||!Pe(i,c,t.force))throw $t.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Kt(e,i??"unknown");$t.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await ve(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await qg(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 Jt();let d=kt(),m=`${e}@${ee}`;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 Zg(e,t,r,n,o){let s=Ur(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`),Se(t)}async function qc(e,t,r,n){let o=Fr(e,n),s=Ur(e);r?.onStatus?.(`Installing ${s}...`),Go.debug(`[${e}] Attempting install: ${o}`);let i=await Se(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 Zg(e,o,a,t,r)}async function Yc(e,t,r){let n=e.type??"plugin",o=await ft.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=me(i=>i.installedItems),t=me(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=re().find(p=>p.name===i),c=l?.providerId??"claude-code",u=ft.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 bn(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 Mn(e,t){e.silent?Ke({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):T(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function eu(e,t){e.silent?Me({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ie(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function Qg(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 $i(e,t){let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function tu(e,t,r){if(!await he())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Mn(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}zo.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Qg(e,t,r.transport,r.scope);if(!r.force){let s=f(e),i=f(n);if(!await Wt(`Install external MCP "${s}"?
110
+ `),this.warned=true;}go().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=go(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return go().path}static hasExistingData(){try{let t=new ri({projectName:ni});return ve.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new ri({projectName:ni});ve.rmSync(t.path,{force:!0});}catch{}yo=null;}};async function oi(){if(De.hasExistingData())return new De;switch(process.platform){case "darwin":return await Lr.isAvailable()?new Lr:new De;case "linux":return await jt.isAvailable()?new jt:await jt.ensureInstalled()?new jt:new De;case "win32":return await Dr.isAvailable()?new Dr:new De;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Cm=x("config:credentials"),Et="flow-plugins-cli",si="credentials",ii="token-cache",ai="user-info",wo=null;async function Kt(){return wo||(wo=oi()),wo}function xo(){wo=null;}async function ne(){let t=await(await Kt()).getSecret(Et,si);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pt(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 Cm.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Kt()).setSecret(Et,si,JSON.stringify(e));}async function Ya(){let e=await Kt();await e.deleteSecret(Et,si),await e.deleteSecret(Et,ii),await e.deleteSecret(Et,ai);}async function Za(){return (await Kt()).getStoragePath()}async function Qa(e){await(await Kt()).setSecret(Et,ii,JSON.stringify(e));}async function Io(){let t=await(await Kt()).getSecret(Et,ii);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function vo(e){await(await Kt()).setSecret(Et,ai,JSON.stringify(e));}async function el(){let t=await(await Kt()).getSecret(Et,ai);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Vt(){let e=await Io();return e?new Date(e.expiresAt)>new Date:false}function bo(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")}}xn();var ci=x("api:auth");function Lm(e){if(!ir.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var rl={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;ci.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&&rl[r]?new Error(rl[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?(ci.debug(`Non-HTTP error during authentication: ${e.message}`),e):(ci.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function ur(e){let t=Or("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Lm(e.tenant);let r;try{r=await ac.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 Pt(e),await Qa({accessToken:r.access_token,expiresAt:n});let o=bo(r.access_token);await vo({sub:o.sub,name:o.name,email:o.email});}var nl=x("lib:tokenProvider");async function Ht(){if(await Vt()){let n=await Io();if(n)return n.accessToken}nl.debug("Token expired or missing, re-authenticating...");let t=await ne();if(!t)throw new Error("Not authenticated. Run: flow auth login");De.clearFallbackFile(),xo(),await ur(t);let r=await Io();if(!r)throw new Error("Authentication succeeded but token was not persisted");return nl.debug("Token refreshed successfully"),r.accessToken}xn();var Eo=x("api:metrics");function ol(){return Or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function sl(e,t,r){return ac.post(e,{json:t,headers:r})}async function Dm(e){let t=await el();if(t)return t;let r=bo(e),n={sub:r.sub,name:r.name,email:r.email};return await vo(n),n}async function b(e,t){let r=await Ht(),n=await Dm(r),o=await ne();if(!ir.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Fs,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await sl(ol(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Eo.debug(`Metrics event sent: ${e}`);}catch(i){throw Eo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function il(e,t,r){try{let n=r&&ir.test(r)?r:"unknown",o={action:e,booster:Fs,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await sl(ol(),o,{FlowTenant:n}),Eo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Eo.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",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var Om={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},st={...Om};function al(e){let t=Date.now();st={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function dr(e){st.currentStep=e,st.stepStart=Date.now();}function H(){return {...st}}function Tt(){return st.sessionStart===0?0:Date.now()-st.sessionStart}function pr(){return st.stepStart===0?0:Date.now()-st.stepStart}function ll(){st.tuiSessionStart=Date.now();}function cl(){return st.tuiSessionStart===0?0:Date.now()-st.tuiSessionStart}var Nm=3e3,Bm=x("abandonment");async function Po(e){let{currentStep:t,sessionStart:r}=H();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Tt()};try{await Promise.race([b(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Nm))]);}catch(o){Bm.warn(`Abandonment event failed: ${String(o)}`);}}function ul(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Um=3e3,Fm=x("session-end");async function vn(e,t,r){let n=cl(),s=[b(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Po(e));try{await ul(Promise.all(s).then(()=>{}),Um);}catch(i){Fm.warn(`Session end event failed: ${String(i)}`);}}var Hm=2e3;function pl(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),vn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Hm);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var zm=16;function ml({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(zm)}),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 Ge=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 mr(){return fe__default.join(Le__default.homedir(),".claude","settings.json")}function pi(){let e=mr();if(!ve__default.existsSync(e))return {status:"missing"};let t=ve__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 gl(e){let t=mr();ve__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,t);}function yl(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 mi(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 Qm=3600,fr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function ef(e){return Zm.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Qm})}function To(e,t={}){let r=pi();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new fr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?mi(r.settings):null,s=ef(e),i=yl(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function Co(e){gl(e.merged);}function hl(){let e=pi();return e.status!=="ok"?false:mi(e.settings)!==null}var Sl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Sl=e.version);}catch{}var ae=Sl;function of(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 pt=["clientId","clientSecret","tenant"],sf={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function xl(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,u]=useState(false),[c,d]=useState("fields"),[p,f]=useState(null),m=useRef(0),g=useRef(false),{setCredentials:y,setJustAuthenticated:I}=Ge(),C=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),P=()=>{d("fields"),f(null),t($=>({...$,clientSecret:""})),n("clientSecret");},A=async()=>{g.current=true;let $=C();try{await Pt($);}catch(j){a(j instanceof Error?j.message:"Failed to persist credentials"),P(),g.current=false;return}let{clientSecret:w,...k}=$;y(k),I(true),b(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Tt(),interface:"tui"}).catch(()=>{}),Tn({starterKit:k.starterKit});},M=async $=>{g.current=true;let w=C();try{Co($),await Pt(w);}catch(W){a(W instanceof Error?W.message:"Failed to persist credentials"),P(),g.current=false;return}let{clientSecret:k,...j}=w;y(j),I(true),b(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Tt(),interface:"tui"}).catch(()=>{}),Tn({starterKit:j.starterKit});},N=$=>{try{return To(C(),{allowOverwriteMalformed:$})}catch(w){return w instanceof fr?(d("malformedConfirm"),null):(a(w instanceof Error?w.message:"Failed to read settings.json"),d("fields"),null)}};useInput(($,w)=>{if(!(l||g.current)){if(c==="preview"){w.return&&p?M(p):w.escape?A():$==="q"&&P();return}if(c==="malformedConfirm"){if(w.return){let k=N(true);k&&(f(k),M(k));}else w.escape&&P();return}if(w.shift&&w.tab){let k=pt.indexOf(r);k>0&&n(pt[k-1]);}else if(w.tab){let k=pt.indexOf(r);k<pt.length-1&&n(pt[k+1]);}else if(w.return)if(r==="tenant")G();else {let k=pt.indexOf(r);n(pt[k+1]);}}},{isActive:true});let G=async()=>{let $={};for(let w of pt)e[w].trim()||($[w]="This field is required");if(Object.keys($).length>0){s($);let w=pt.find(k=>$[k]);w&&n(w);return}u(true),a(null),m.current+=1;try{await ur(C());let w=N(!1);w&&(f(w),d("preview"));}catch(w){let k=w instanceof Error?w.message:"Authentication failed";a(k),il(v.CLI_AUTH_FAILED,{error_code:of(w),attempt:m.current},e.tenant.trim()).catch(()=>{}),t(j=>({...j,clientSecret:""}));}finally{u(false);}},ye=$=>w=>{t(k=>({...k,[$]:w})),o[$]&&s(k=>({...k,[$]:void 0}));};return c==="preview"&&p?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[eo," \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:p.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),p.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"})]})]}):c==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[eo," \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:[eo," \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:pt.map($=>jsx(Box,{marginBottom:1,children:jsx(ml,{label:sf[$],value:e[$],onChange:ye($),masked:$==="clientSecret",isActive:r===$&&!l,error:o[$]})},$))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",h(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function Nr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(lf,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ae]})})]})}function cf(){let e=Ka();if(!ve__default.existsSync(e))return {};try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return {}}}var fi=null;function uf(){return fi===null&&(fi=cf()),fi}function Jt(){return !!uf().ENABLE_EXPERIMENTAL_BETAS}var oe=Jt()?["discover","installed","updates","marketplaces"]:["discover","installed","updates"];function gi(e){return e==="marketplaces"?"marketplaces":"list"}function Pl(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:gi(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:gi(o)}]}return t.downArrow?[{type:"setFocus",focus:gi(r.activeTab)}]:[]}var kl={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Al({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:oe.map(r=>{let n=r===t,o=r==="updates"&&e>0?`${kl[r]} (${e})`:kl[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Oe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Ml(){let e=S(i=>i.focus),t=Oe(i=>i.query),r=Oe(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 ff=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Ar[e]})),gf=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,..._a[e]}));function Ll(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),ff.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"]})]}),gf.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 Rl({type:e}){let{label:t,color:r}=Ar[e];return jsx(Text,{color:r,children:t})}function Ol({origin:e}){return e===mn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Ao=Sf.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(Rl,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ol,{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 ",Ft(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Br({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Ul({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Br,{message:t});let n=Math.max(0,r-Math.floor(Ve/2)),o=Math.min(e.length,n+Ve);o===e.length&&(n=Math.max(0,o-Ve));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Ao,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Kl({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 Hl({groups:e,emptyMessage:t}){let r=S(f=>f.selectedIndex),n=[],o=0;for(let f of e){n.push({kind:"header",label:f.label,pathHint:f.pathHint,key:`h-${f.scope}`});for(let m of f.items)n.push({kind:"item",item:m,itemIndex:o,key:`i-${f.scope}-${m.name}-${m.marketplace??""}`}),o++;}if(o===0)return jsx(Br,{message:t});let i=n.findIndex(f=>f.kind==="item"&&f.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Ve/2)),u=Math.min(n.length,l+Ve);u===n.length&&(l=Math.max(0,u-Ve));let c=n.slice(l,u),d=l,p=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(f=>f.kind==="header"?jsx(Kl,{label:f.label,pathHint:f.pathHint},f.key):jsx(Ao,{item:f.item,isSelected:f.itemIndex===r},f.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:p>0?`\u2193 ${p} more below`:" "})})]})}var Tf={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Cf({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Ml,{}),jsx(Ll,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Tf[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Hl,{groups:n,emptyMessage:r}):jsx(Ul,{items:e,emptyMessage:r})]})}function Jl({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Cf,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var $f={tabs:"\u2190\u2192: switch tab | \u2193: navigate | Enter: select | Ctrl+C Ctrl+C: quit",list:"\u2191\u2193: navigate | Enter: select | Type: 1=All 2=Skill 3=MCP 4=Bundle | Origin: 5=All 6=Flow 7=External | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",search:"Type to filter | \u2193/Esc: exit search | Enter: confirm",actionMenu:"\u2191\u2193: navigate options | Enter: confirm | Esc: close menu",auth:"Tab: next field | Enter: confirm | Ctrl+C Ctrl+C: quit",starterKitList:"\u2191\u2193: navigate | Enter: select Starter Kit | Esc: skip",starterKitDetail:"\u2191\u2193: navigate | Enter: confirm & install | Esc: back",installProgress:"\u2191\u2193: navigate | Enter: select",moduleSetup:"\u2191\u2193: navigate | Space: toggle | Tab: change method | Enter: confirm",marketplaces:"\u2191\u2193: navigate | a: add catalog | d: remove catalog | r: refresh | \u2190\u2192/Tab: tabs | Ctrl+C\xD72: quit",verify:"\u2191\u2193: navigate | Enter: confirm | Ctrl+C Ctrl+C: quit",bundleInstallProgress:"Enter/Esc: back to catalog"};function $o(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[$f[e],t?" | Ctrl+D: debug log":""]})})}function Gl({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",h(e)]})}):null}function Mo({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ru,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Lo({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 ze({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}var Pi=Object.entries(fn),Ql=[...Pi.map(([,e])=>e.actionLabel),"Cancel"],ec=Object.fromEntries(Pi.map(([,e])=>[e.actionLabel,e.description]));function tc(e){let t=Pi.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var Vf=x("provider.registry"),Hf=3e4,_o=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()+Hf}),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"&&Vf.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 Jf={user:"global",project:"project",local:"local"};function Do(e){return e?Jf[e]:"global"}var Ne=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},Wt=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};xn();function mt(){return ac.create({prefix:Or("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Ht();e.headers.set("Authorization",`Bearer ${t}`);let r=await ne();r?.tenant&&ir.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Wf=x("catalog.registry"),Oo=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);Wf.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 tg={retries:5,minTimeout:50};async function Ti(e,t){mkdirSync(dirname(e),{recursive:true});let r=await eg.lock(e+".lock",{realpath:false,retries:tg});try{return await t()}finally{await r();}}var No=class{filePath;constructor(t){this.filePath=t??ja();}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 Ti(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 Ti(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ti(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 rg=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function An(e){if(!e||!rg.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var ng=/^[^@]+@[^@]+$/;function Fr(e){return ng.test(e)}function jr(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var og=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function sg(e){if(!og.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 Kr(e,t){let r=jr(e);sg(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var ig=/^[\w./:@?&=+#%-]+$/;function Bo(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!ig.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var ag=x("catalog.flow-api"),Uo=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 mt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}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){An(t);try{return await mt().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 mt().head("v1/plugins/catalog"),ag.debug("ping ok"),!0}catch{return false}}};var he=new Oo,kt=new No;he.register(new Uo);var uc=false;async function dc(){if(uc)return;uc=true;let e=await kt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Ci(),cc));for(let r of e)he.register(new t(r.id,r.name,r.source));}async function zt(){return he.fetchAll()}async function pc(){return he.fetchAllWithErrors()}async function Hr(e){An(e);try{return await mt().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 mc(e){An(e);try{let t=await mt().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 Fo(){try{let{profiles:e}=await mt().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 fc(e,t){let r=fe.resolve(t);await ft.mkdir(r,{recursive:true});let n=fe.join(fe.dirname(r),`${randomUUID()}.zip`);try{await ft.writeFile(n,e),await pg(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=fe.resolve(r,o.fileName);if(!i.startsWith(r+fe.sep)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(fe.resolve(fe.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 ft.unlink(n);}catch{}}}async function ki(e){await ft.rm(e,{recursive:true,force:true});}async function Xt(){let e=Ua();await ft.mkdir(fe.dirname(e),{recursive:true});try{await ft.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await eg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function gg(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:te,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function hc(){let e=no();if(!ve__default.existsSync(e))return null;try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return null}}function yg(){let e=hc();if(e)return e;let t=gg(),r=no();return ve__default.mkdirSync(fe__default.dirname(r),{recursive:true}),Ai(t),t}function Ai(e){let t=no(),r=`${t}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,t);}function hg(){let e=oo(),t={};try{ve__default.existsSync(e)&&(t=JSON.parse(ve__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[te])return;t[te]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Ba(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,e);}function Sc(e,t){jo(e.name),hg();let r=Vs(e.name);ve__default.mkdirSync(fe__default.dirname(r),{recursive:true});try{ve__default.lstatSync(r),ve__default.rmSync(r,{recursive:!0,force:!0});}catch{}ve__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=yg();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}),Ai(n));}function $i(e){jo(e);let t=Vs(e);try{ve__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=hc();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Ai(r);}var wg=x("mcpConfigReader"),xg=500,Ig=512;function vg(){return fe__default.join(Le__default.homedir(),".claude.json")}function bg(){return fe__default.join(process.cwd(),".mcp.json")}function xc(e){if(!ve__default.existsSync(e))return null;try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return wg.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function $n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mi(e){if(!$n(e))return {};let t=e.mcpServers;return $n(t)?t:{}}function Li(e,t){return Object.keys(e).slice(0,xg).map(n=>({name:h(n.slice(0,Ig)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function vc(){let e=[],t=vg(),r=xc(t);if($n(r)){let a=r,l=Mi(a);e.push(...Li(l,"user"));let u=process.cwd();if($n(a.projects)){let c=a.projects[u];if($n(c)){let d=Mi(c);e.push(...Li(d,"local"));}}}let n=bg(),o=xc(n),s=Mi(o);e.push(...Li(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 qe=x("storage");async function Pg(e,t,r){try{await b(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:H().interfaceType});}catch(n){qe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Tg(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:H().interfaceType}).catch(o=>qe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Oi(){return fe__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function Cg(){return fe__default.join(Le__default.homedir(),".claude","plugins")}function bc(e){let t=fe__default.resolve(e),r=fe__default.resolve(Cg()),n=fe__default.resolve(fe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+fe__default.sep)||t===r,s=t.startsWith(n+fe__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Ec(e="user"){return e==="local"?fe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?fe__default.join(process.cwd(),".claude","settings.json"):fe__default.join(Le__default.homedir(),".claude","settings.json")}function $t(){let e=Oi();if(!ve__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ve__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Pc(){let e=Oi();try{let t=await ve__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function kg(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Tc(e,t){try{ve__default.mkdirSync(fe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ve__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ve__default.renameSync(r,e);}catch(r){throw kg(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function At(e){Tc(Oi(),e);}function Mn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Ag(e,t){let r=fe__default.join(e,".claude-plugin"),n=fe__default.join(r,"plugin.json");if(ve__default.existsSync(n))try{return JSON.parse(ve__default.readFileSync(n,"utf-8"))}catch{return null}let o=fe__default.join(r,"marketplace.json");if(ve__default.existsSync(o))try{let s=JSON.parse(ve__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Ni(e="user"){let t=Ec(e);if(!ve__default.existsSync(t))return {};try{return JSON.parse(ve__default.readFileSync(t,"utf-8"))}catch{return {}}}function Cc(e,t="user"){Tc(Ec(t),e);}function $g(e,t){let{name:r,marketplace:n}=Mn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Mn(i).name===r)[0],!o)throw qe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Mg(e,t){let{name:r,marketplace:n}=Mn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Mn(i).name===r)[0],o?{key:o,name:r}:null}function Ri(e="user"){return Ni(e).enabledPlugins??{}}function _i(e,t="user"){let r=Ni(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Cc(r,t);}function Ln(e,t,r="user"){let n=Ni(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Cc(n,r);}function Lg(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=$t(),t=Ri(),r=Ri("project"),n=Ri("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:p}=Mn(u),f=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Lg(f).map(g=>{let y=Ag(g.installPath,d),C=(o[g.scope]??t)[u];return {name:d,marketplace:p,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:y?.description,author:y?.author,status:C===false?"disabled":"enabled"}})}),i=vc(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function Ko(e,t){qe.debug(`[${e}] Acquiring lock to uninstall`);let r=await Xt();try{let n=$t(),o=Mg(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`);qe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),bc(l.installPath);let u=fe__default.dirname(l.installPath);qe.debug(`[${i}] Removing directory: ${u}`),ve__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...p}=n.plugins;At({...n,plugins:p}),_i(s,t),$i(i);}else n.plugins[s]=c,At(n),_i(s,t);}else {qe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){bc(c.installPath);let d=fe__default.dirname(c.installPath);qe.debug(`[${i}] Removing directory: ${d}`),ve__default.rmSync(d,{recursive:!0,force:!0}),_i(s,c.scope);}$i(i);let{[s]:l,...u}=n.plugins;At({...n,plugins:u});}await Pg(i,a[0].origin??"internal",a[0].type??"skill"),qe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Rn(e,t,r){qe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Xt();try{let o=$t(),{key:s,name:i}=$g(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";qe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Ln(s,t==="enabled",l),Tg(i,t,u),qe.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]$/,_g=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function jo(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 Dg(e){if(!_g.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 qt=x("installer");function Og(e,t){let r=`${e}@${te}`,o=$t().plugins[r];if(o&&!t)throw new Ne(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Ng(e,t,r){r&&await ki(t);try{qt.debug(`[${t}] Extracting archive...`),await fc(e,t);}catch(n){throw await ki(t),n}}function Bg(e,t,r,n,o,s="claude-code",i){let a=$t(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],At(a),Ln(e,true,n);}async function Ug(e,t,r,n,o,s){try{await b(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:H().interfaceType});}catch(i){qt.warn(`Failed to send install metrics: ${String(i)}`);}}async function Fg(e,t,r,n){try{await b(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:H().interfaceType});}catch(o){qt.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ee(e,t={}){let r=Date.now(),n=null;try{qt.debug(`[${e}] Acquiring lock...`),n=await Xt();let{pluginKey:o,alreadyInstalled:s}=Og(e,t.force);qt.debug(`[${e}] Fetching manifest...`);let i=await Hr(e);jo(i.name),Dg(i.version),qt.debug(`[${e}] Downloading archive...`);let a=await mc(e),l=t.scope??"user",u=t.type??"skill",c=Na(i.name,i.version);await Ng(a,c,!!s&&!!t.force),Bg(o,c,i.version,l,"internal",t.providerId,u),Sc(i,c);let d=Date.now()-r;qt.debug(`[${e}] Installed successfully in ${d}ms`);let p={name:i.name,version:i.version,path:c,duration_ms:d};return t.skipMetrics||await Ug(i.name,i.version,d,Do(l),"internal",u),p}catch(o){throw await Fg(e,o,"internal",t.type??"skill"),qt.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var jg=x("commands:helpers");async function ge(){if(!await ne())return E("Not authenticated. Run: flow auth login"),false;try{await Ht();}catch(t){return jg.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function gt(e){let t=Bi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function kc(e){let t=Bi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(n.trim());});})}var Jr=x("claudeProxy"),Vi="claude ",Ac="flow ",Ui=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Fi=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";}},Kg=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Vg=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Hg=/^(flow|claude)\s+auth\s+login(\s|$)/,$c=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Mc(e){return $c.test(e.trim())}function Jg(e){return $c.exec(e.trim())?.[2]??""}async function Lc(e){let t=Jg(e),r=Date.now();Jr.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw Hi(n)?new ji:n}}function Gg(e){Rc(e);let t=e.slice(Vi.length);if(!Kg.test(t))throw new Fi(e)}var Vo=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},ji=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Rc(e){if(!e||!/^claude /.test(e))throw new Ui(e)}async function xe(e){Rc(e);let t=e.slice(Vi.length).split(/\s+/).filter(Boolean),r=Wg(t);Jr.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 Jr.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 Hi(o)?new Vo:o}}function Wg(e){return e.length>=3?e[2]:e.join(" ")}function Hi(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function zg(e){return e.startsWith(Ac)?Vi+e.slice(Ac.length):e}function Xg(e){return Vg.test(e)||Hg.test(e)}function qg(e){let t=0;for(;t<e.length&&Xg(e[t]);)t++;return e.slice(t)}var Yg=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Zg(e,t){return !t||e.includes("--scope")||!Yg.test(e)?e:`${e} --scope ${t}`}async function _n(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=qg(r).map(i=>zg(i)).map(i=>Zg(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Gg(i);Jr.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await xe(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await xe(o[i]),s.exitCode!==0)return s;return s}async function Ho(e,t,r){let n=jr(e),o=t?.trim();if(!o&&(o=(await kc(`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=Bo(o),r?.(),Jr.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"}`);Jr.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Hi(s)?new Vo:s}}var ny=6e4,Yt=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 Zt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:ny}}).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 Yt("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Yt(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Yt(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Qt(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 Ir(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 sy(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function iy(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ay(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Jo(e,t){let r=e.source;if(sy(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(iy(r))return {cloneUrl:r.url,subPath:"."};if(ay(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 er=x("claude-code.adapter");function cy(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=oo();if(!ve__default.existsSync(s))return r;try{let i=JSON.parse(ve__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function jc(e,t){let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=Jo(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=cy(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Hs(s,e.name,"external"):a=join(ar(i==="user"?"global":"project"),e.name);let l=null;try{l=await Zt(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(ve__default.existsSync(a)&&ve__default.rmSync(a,{recursive:!0,force:!0}),ve__default.mkdirSync(dirname(a),{recursive:!0}),ve__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Pc(),p={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},f=d.plugins[c]??[];d.plugins[c]=[...f.filter(m=>m.scope!==i),p],At(d),Ln(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return er.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Qt(l).catch(()=>{});}}async function Ji(e,t,r,n){try{await b(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Do(n),version:"unknown",duration_ms:t,interface:H().interfaceType});}catch(o){er.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Uc(e,t,r){try{await b(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:H().interfaceType});}catch(n){er.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var uy={async install(e,t){if(e.origin===kr&&!e.installCommand&&!Fr(e.name))return jc(e,t);if(e.origin===kr&&e.installCommand){let r=e.type??"skill",n=await _n(e.installCommand,t.scope);return n.exitCode===0?(await Ji(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Uc(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Fr(e.name)){let r=e.type??"skill",n=Kr(e.name,t.scope);er.debug(`[${e.name}] Attempting install: ${n}`);let o=await xe(n);if(o.exitCode===0)return await Ji(e.name,o.duration_ms,r,t.scope),{success:true};er.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ho(e.name,t.marketplaceSource,()=>{});let s=await xe(n);return s.exitCode===0?(await Ji(e.name,s.duration_ms,r,t.scope),{success:true}):(await Uc(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await Ee(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return er.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 Fc(e){return {async install(t,r){if(t.origin===kr&&!t.installCommand&&!Fr(t.name))return jc(t,r);if(!t.installCommand)try{let o=await Ee(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return er.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}er.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await _n(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 Go=class{id="claude-code";name="Claude Code";async isAvailable(){return Ir("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:uy,skill:Fc("skill"),mcp:Fc("mcp")}};function Wo(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 py=new Set(["gh"]),my=Wo(py,"use: gh copilot mcp remove <name>"),zo=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Ir("gh",["--version"])?Ir("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:my}};var fy=new Set(["opencode"]),gy=Wo(fy,"use: opencode config remove mcp <name>");function yy(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 Kc(){return {async install(e,t){let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=Jo(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Zt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=so(t.scope??"user"),a=join(s,".opencode","plugins");if(ve__default.existsSync(a)){let l=ve__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ve__default.mkdirSync(i,{recursive:!0}),ve__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ve__default.existsSync(l)&&ve__default.rmSync(l,{recursive:!0,force:!0}),ve__default.mkdirSync(l,{recursive:!0}),ve__default.cpSync(s,l,{recursive:!0}),ve__default.mkdirSync(i,{recursive:!0}),ve__default.writeFileSync(join(i,`${e.name}.js`),yy(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 Qt(o).catch(()=>{});}},async uninstall(e,t){let r=so(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ve__default.existsSync(n)&&ve__default.rmSync(n,{force:true}),ve__default.existsSync(o)&&ve__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(so(t),`${e}.js`)}}}var Xo=class{id="opencode";name="OpenCode";async isAvailable(){return Ir("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:gy,skill:Kc(),bundle:Kc()}};var yt=new _o;yt.register(new Go);Jt()&&(yt.register(new zo),yt.register(new Xo));function Vc({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{yt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let p=useCallback(y=>{y==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),f=useCallback(y=>{if(y==="Cancel"){a(false);return}let I=l.find(C=>C.name===y);I?(d(I.id),a(false),s(true)):a(false);},[l]),m=useCallback(y=>{let I=tc(y);I?r(I,c):s(false);},[r,c]),g=useCallback(()=>{s(false);},[]);if(i){let y=[...l.map(I=>I.name),"Cancel"];return jsx(ze,{itemName:`${e} \u2014 Choose provider`,actions:y,onAction:f,onClose:()=>a(false)},"provider")}return o?jsx(ze,{itemName:`${e} \u2014 Choose scope`,actions:Ql,descriptions:ec,onAction:m,onClose:g},"scope"):jsx(ze,{itemName:e,actions:["Install","Cancel"],onAction:p,onClose:n},"main")}function Jc({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(m=>m.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(m=>m.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let p=useCallback((m,g)=>{g.upArrow?a(y=>Math.max(0,y-1)):g.downArrow?a(y=>Math.min(d.length-1,y+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(p,{isActive:s==="actionMenu"&&t!==void 0});let f=useCallback(m=>{m==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(m=>{let g=m.name??m.flowId,y=m.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",y,")"]})]},m.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((m,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",m]})},m))})]}):jsx(ze,{itemName:e,actions:["Install Bundle","Cancel"],onAction:f,onClose:o})}function Zo({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function zc({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Zo({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",p=o&&h(o),f=p?`Update to v${p}`:"Update";return jsx(ze,{itemName:e,actions:n?["Uninstall",d,f,"Cancel"]:["Uninstall",d,"Cancel"],onAction:y=>{y==="Uninstall"?c():y===d?i(t):y.startsWith("Update")?a?.():l();},onClose:l})}function Yc({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Zo({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(ze,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var Xr=x("bundle:installer"),Zc=/already exists/i;async function Ey(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Mc(t)){let r=await Lc(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Zc.test(n))return;throw new Error(n)}}else {let r=await _n(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Zc.test(n))return;throw new Error(n)}}}async function Py(e,t){try{await b(v.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Xr.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Ty(e,t,r){try{await b(v.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Xr.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Qc(e,t,r,n){try{await b(v.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Xr.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function Cy(e,t,r,n,o){try{await b(v.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Xr.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function ts(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(f=>f.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await Py(i,o.length);let l=[],u=0,c=o.length;for(let[f,m]of o.entries()){let g=m.name??m.flowId,y=m.type??"unknown";if(!m.type){Xr.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:y,reason:"unknown artifact type"}),await Qc(i,g,y,"unknown artifact type"),r?.({index:f+1,total:c,artifact:m,success:false,error:"unknown artifact type"});continue}try{await Ey(m),u++,await Ty(i,g,y),r?.({index:f+1,total:c,artifact:m,success:!0});}catch(I){let C=I instanceof Error?I.message:String(I);Xr.error(`Failed to install artifact "${g}": ${C}`),l.push({name:g,type:y,reason:C}),await Qc(i,g,y,C),r?.({index:f+1,total:c,artifact:m,success:false,error:C});}}let d=Date.now()-a,p=l.length;return await Cy(i,u,p,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:p,failures:l}}function nu({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,ts(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(ru,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",r.artifact.name??r.artifact.flowId," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(ru,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ue=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:se()})}));function ou({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Ft(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function su({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,p=c?.autoUpdate!==false,f=n==="detail",m=[{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 f?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Ft(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),p?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:m.map((g,y)=>{let I=y===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:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function iu(e){return e.adapter.removable!==false?4:2}function au({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",h(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:h(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",h(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",h(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:h(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",h(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",h(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",h(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function cu({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 uu({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(M=>r.has(`${M.name}@${o}`)),i=t.filter(M=>!r.has(`${M.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((M,N)=>{if(N.escape){n();return}if(N.return){d(a[l]??null);return}if(N.upArrow){u(G=>Math.max(0,G-1));return}N.downArrow&&u(G=>Math.min(a.length-1,G+1));},{isActive:c===null}),c!==null)return jsx(au,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let p=Math.max(0,l-Math.floor(Ve/2)),f=Math.min(a.length,p+Ve);f===a.length&&(p=Math.max(0,f-Ve));let m=a.slice(p,f),g=p,y=a.length-f,I=s.length>0&&p<s.length,C=f>s.length,P=m.filter(M=>r.has(`${M.name}@${o}`)),A=m.filter(M=>!r.has(`${M.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"]}),P.map(M=>jsx(cu,{item:M,isSelected:a.indexOf(M)===l,isInstalled:true},M.name))]}),C&&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"]}),A.map(M=>jsx(cu,{item:M,isSelected:a.indexOf(M)===l,isInstalled:false},M.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:y>0?`\u2193 ${y} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Ci();var _y=/^https?:\/\/.+/;function Dy(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Oy(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function fu(e){let t=S(y=>y.showNotification),r=S(y=>y.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),p=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{p.current=a;},[a]);let f=useCallback(()=>{d.current="",p.current="",i(""),l(""),c(null),o("add-name");},[]),m=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let y=p.current,I=d.current;if(!_y.test(y)){c("URL must start with http:// or https://");return}c(null),o("adding");let C=randomUUID(),P=new Vr(C,I,y);try{await P.fetchItems(),await kt.add({id:C,name:I,source:y}),he.register(new Vr(C,I,y)),r(),e(),t(`Catalog "${I}" added`,"success"),i(""),l(""),d.current="",p.current="",o("idle");}catch(A){let M=Dy(A)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Oy(A)?A.message:A instanceof Error?`Could not reach catalog URL: ${A.message}`:"Failed to validate catalog URL";t(M,"error"),o("add-url");}},[e,t,r]);return useInput((y,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}y&&!I.ctrl&&!I.meta&&(d.current=d.current+y,i(d.current));},{isActive:n==="add-name"}),useInput((y,I)=>{if(I.escape){o("add-name");return}if(I.return){g();return}if(I.backspace||I.delete){p.current=p.current.slice(0,-1),l(p.current),c(null);return}y&&!I.ctrl&&!I.meta&&(p.current=p.current+y,l(p.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:f,cancelAdd:m}}function gu(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await kt.remove(o),he.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 hu(){let e=S(L=>L.focus),t=S(L=>L.setFocus),r=S(L=>L.setActiveTab),n=S(L=>L.showNotification),o=ue(L=>L.installedItems),[s,i]=useState(()=>he.listAdapters().map(L=>({adapter:L,stored:null}))),[a,l]=useState(0),[u,c]=useState("list"),[d,p]=useState(0),[f,m]=useState(null),[g,y]=useState("main"),I=useRef(s);useEffect(()=>{I.current=s;},[s]),useEffect(()=>{g==="browse"&&!s[a-1]&&y("main");},[g,s,a]);let C=useCallback(()=>{(async()=>{let L=he.listAdapters(),O=await kt.read(),U=new Map(O.map(pe=>[pe.id,pe]));i(L.map(pe=>({adapter:pe,stored:U.get(pe.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),C();},[t,C]),useEffect(()=>{if(a===0){m(null);return}let L=I.current[a-1];if(!L)return;let O=false;return m({items:[],loading:true,error:null}),L.adapter.fetchItems().then(U=>{O||m({items:U,loading:false,error:null});}).catch(U=>{O||m({items:[],loading:false,error:U instanceof Error?U.message:"Failed to load catalog"});}),()=>{O=true;}},[a]);let P=fu(C),A=useCallback(()=>{C(),l(0),c("list"),m(null),y("main");},[C]),{handleRemove:M}=gu(A),N=useCallback(async L=>{y("removing"),await M(L);},[M]),G=useCallback(async L=>{try{let O=await L.adapter.fetchItems();if(m({items:O,loading:!1,error:null}),L.stored){let U=new Date().toISOString();await kt.updateField(L.stored.id,{lastUpdated:U}),C();}n("Marketplace updated","success");}catch(O){n(O instanceof Error?O.message:"Update failed","error");}},[C,n]),ye=useCallback(async L=>{if(!L.stored)return;let O=L.stored.autoUpdate!==false;await kt.updateField(L.stored.id,{autoUpdate:!O}),C();},[C]),$=useCallback(()=>y("browse"),[]),w=useCallback(L=>{let O=s[a-1];if(!O)return;let U=O.adapter.removable!==false;[$,()=>{G(O);},...U?[()=>{ye(O);},()=>{N(O.adapter.id);}]:[]][L]?.();},[s,a,$,G,ye,N]),k=useCallback(()=>y("main"),[]),j=useCallback(()=>{let L=s[a-1];L&&G(L);},[s,a,G]),W=useCallback(()=>{let L=s[a-1];L&&ye(L);},[s,a,ye]),dn=useCallback(()=>{let L=s[a-1];L&&N(L.adapter.id);},[s,a,N]);if(useInput((L,O)=>{if(O.upArrow){l(U=>Math.max(0,U-1));return}if(O.downArrow){l(U=>Math.min(s.length,U+1));return}if(O.leftArrow||O.rightArrow){let U=["discover","installed","marketplaces"],pe=U.indexOf("marketplaces"),pn=O.leftArrow?U[(pe-1+U.length)%U.length]:U[(pe+1)%U.length];r(pn),t("list");return}(O.return||O.tab)&&(a===0?P.startAdd():(c("detail"),p(0)));},{isActive:g==="main"&&P.phase==="idle"&&u==="list"&&e==="marketplaces"}),useInput((L,O)=>{if(O.escape||O.tab){c("list");return}if(O.upArrow){p(U=>Math.max(0,U-1));return}if(O.downArrow){let U=s[a-1],pe=U?iu(U)-1:0;p(pn=>Math.min(pn+1,pe));return}O.return&&w(d);},{isActive:g==="main"&&P.phase==="idle"&&u==="detail"&&e==="marketplaces"}),P.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:P.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.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(P.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:P.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:P.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:P.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(P.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 L=s[a-1];if(!L)return jsx(Box,{});let O=L.adapter.id??"default",U=new Set(o.filter(pe=>pe.marketplace===L.adapter.name).map(pe=>`${pe.name}@${O}`));return jsx(uu,{entry:L,items:f?.items??[],installedKeys:U,onBack:k})}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 bt=s[a-1]??null,Qn=bt?o.filter(L=>L.marketplace===bt.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(ou,{entries:s,selectedIndex:a,focusPanel:u})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:u==="detail"&&bt?jsx(su,{entry:bt,detailData:f,installedCount:Qn,focusPanel:u,actionIndex:d,onBrowse:$,onUpdate:j,onToggleAutoUpdate:W,onRemove:dn}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:bt?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:u==="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 Su(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:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function wu(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function xu(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 is(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Oe.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function Iu({listLength:e}){let t=S(g=>g.focus),r=S(g=>g.selectedIndex),n=S(g=>g.actionMenuOpen),o=S(g=>g.setFocus),s=S(g=>g.setActionMenuOpen),i=Oe(g=>g.query),a=Oe(g=>g.setQuery),l=Oe(g=>g.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:y}=Oe.getState();y(g.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,y)=>{let{activeTab:I,selectedIndex:C,actionMenuOpen:P}=S.getState();is(Pl(g,y,{activeTab:I}));},{isActive:t==="tabs"}),useInput((g,y)=>{let{activeTab:I,selectedIndex:C,actionMenuOpen:P}=S.getState();is(Su(g,y,{activeTab:I,selectedIndex:C},u.current));},{isActive:t==="list"}),useInput((g,y)=>{is(wu(g,y));},{isActive:t==="actionMenu"}),useInput((g,y)=>{let I=xu(g,y,Oe.getState().query),C=I.queryUpdate;if(is(I.actions),C==="reset")l(),d("");else if(C!==null){let{query:P,cursorPosition:A,setCursorPosition:M}=Oe.getState();if("backspace"in C)A>0&&(a(P.slice(0,A-1)+P.slice(A)),M(A-1));else if("append"in C)a(P.slice(0,A)+C.append+P.slice(A)),M(A+C.append.length);else if("cursorMove"in C){let N=A+C.cursorMove;N>=0&&N<=P.length&&M(N);}}},{isActive:t==="search"});let p=useCallback(()=>{s(false),o("list");},[s,o]),f=useCallback(g=>{let{setSelectedIndex:y,selectedIndex:I}=S.getState();g===0?y(0):I>=g&&y(g-1);},[]),m=useCallback(g=>{if(!c)return u.current=g.length,g;let y=c.toLowerCase(),I=g.filter(C=>C.name.toLowerCase().includes(y)||C.description?.toLowerCase().includes(y));return u.current=I.length,I},[c]);return {actionMenuOpen:n,closeMenu:p,selectedIndex:r,clampIndex:f,filteredItems:m}}function bu(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Ge(a=>a.justAuthenticated),o=Ge(a=>a.credentials),s=Ge(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 Te(e,t,r=false){return r?true:!qi.valid(e)||!qi.valid(t)?false:qi.gt(t,e)}var Rt=x("updater");async function jy(e,t,r,n,o,s){try{await b(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:H().interfaceType});}catch(i){Rt.warn(`Failed to send update metrics: ${String(i)}`);}}function Ky(e){let t=$t(),r=`${e}@${te}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function as(e,t={}){let r=Date.now(),n=null;try{Rt.debug(`[${e}] Acquiring lock...`),n=await Xt();let o=Ky(e);if(!o)throw Rt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Rt.debug(`[${e}] Fetching manifest...`);let u=(await Hr(e)).version;if(!i||!Te(i,u,t.force))throw Rt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new Wt(e,i??"unknown");Rt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Ee(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await jy(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Rt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Rt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Xt();let d=$t(),p=`${e}@${te}`;throw d.plugins[p]&&(d.plugins[p][0].version=i,d.plugins[p][0].installPath=a,At(d),Rt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}var ls=x("dispatcher");async function Vy(e,t,r,n,o){let s=jr(e);return ls.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Ho(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),ls.debug(`[${e}] Retrying install after marketplace add`),xe(t)}async function Eu(e,t,r,n){let o=Kr(e,n),s=jr(e);r?.onStatus?.(`Installing ${s}...`),ls.debug(`[${e}] Attempting install: ${o}`);let i=await xe(o);if(i.exitCode===0)return i;ls.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Vy(e,o,a,t,r)}async function Pu(e,t,r){let n=e.type??"bundle",o=await yt.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 Tu(){let e=ue(i=>i.installedItems),t=ue(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Pu(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=se().find(f=>f.name===i),u=l?.providerId??"claude-code",c=yt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",p=c.installers[d];if(!p)throw new Error(`Provider "${u}" does not support type "${d}"`);await p.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Rn(i,u,a),t();},[e,t]),s=useCallback(async i=>{await as(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var us=x("mcp");function Vn(e,t){e.silent?Je({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function ku(e,t){e.silent?_e({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(re(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&T(t.stdout));}function Hy(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 Yi(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 Au(e,t,r){if(!await ge())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Vn(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}us.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Hy(e,t,r.transport,r.scope);if(!r.force){let s=h(e),i=h(n);if(!await gt(`Install external MCP "${s}"?
113
113
  This will run: ${i}
114
- [y/N] `))return zo.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:na({text:`Adding MCP "${f(e)}"...`}).start();try{let s=await Se(n);return o?.stop(),s.exitCode!==0?(Mn(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&C(`stdout: ${s.stdout}`),1):(eu(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Mn(r,{name:e,action:"add",message:q(s)}),1}}async function ru(e,t){if(!await he())return 1;zo.debug(`[${e}] Starting MCP remove`);let r=$i(e,t.scope);if(!t.force){let o=f(e),s=f(r);if(!await Wt(`Remove MCP "${o}"?
114
+ [y/N] `))return us.debug(`[${e}] Installation cancelled by user`),T("Operation cancelled."),0}let o=r.silent?void 0:Ea({text:`Adding MCP "${h(e)}"...`}).start();try{let s=await xe(n);return o?.stop(),s.exitCode!==0?(Vn(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&T(`stdout: ${s.stdout}`),1):(ku(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Vn(r,{name:e,action:"add",message:Z(s)}),1}}async function $u(e,t){if(!await ge())return 1;us.debug(`[${e}] Starting MCP remove`);let r=Yi(e,t.scope);if(!t.force){let o=h(e),s=h(r);if(!await gt(`Remove MCP "${o}"?
115
115
  This will run: ${s}
116
- [y/N] `))return zo.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:na({text:`Removing MCP "${f(e)}"...`}).start();try{let o=await Se(r);return n?.stop(),o.exitCode!==0?(Mn(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`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(),Mn(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=y(b=>b.setLoading),{install:l,uninstall:c,toggle:u,update:d}=Zc(),m=async(b,k,R)=>{a(true,b),n();try{await k(),o(r.length),s(R,"success");}catch(L){let B=L instanceof Error?L.message:"Something went wrong";i.error(`[withLoading] ${b} failed: ${B}`),s(B,"error");}finally{a(false);}};return {handleInstall:(b,k)=>{e&&t&&m(`Installing ${e.name}...`,()=>l(t,{scope:b,...k!==void 0?{providerId:k}:{}}),"\u2713 Installed successfully");},handleUninstall:b=>{e&&m(`Uninstalling ${e.name}...`,()=>c(e.name,b),"\u2713 Uninstalled");},handleToggleStatus:b=>{if(!e)return;let k=e.status==="enabled";m(k?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,b),k?"\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(R){if(R instanceof Kt)s(R.message,"info");else {let L=R instanceof Error?R.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${L}`),s(L,"error");}}finally{a(false);}})();},handleMcpConfigUninstall:b=>{e&&m(`Removing MCP ${e.name}...`,async()=>{let k=$i(e.name,b),R=await Se(k);if(R.exitCode!==0)throw new Error(R.stderr||"MCP removal failed");me.getState().loadFromDisk();},"\u2713 MCP removed");}}}var $n=["local","project","user"],ey=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(ey.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Ln(e,t){return t?`${e}::${t}`:e}function Li(e){return e===ee?rn:Er}function su(e){return {name:f(e.name),version:e.version?f(e.version):e.version,description:e.description?f(e.description):e.description,authorName:e.author?.name?f(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"plugin",origin:e.origin??rn}}function iu(e,t){let r=Li(e.marketplace);return {name:f(e.name),version:e.version?f(e.version):e.version,description:e.description?f(e.description):e.description,authorName:e.author?.name?f(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 $n.filter(r=>t.has(r)).map(r=>({scope:r,label:nn[r].label,pathHint:nn[r].pathHint,items:t.get(r)??[]}))}function lu(e){let t=r=>{if(!r)return 1/0;let n=$n.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(p=>Ln(p.name,p.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(p=>p.type==="mcp").map(p=>p.name.toLowerCase())),[t]),a=useMemo(()=>{let p=new Map(e.map(h=>[Ln(h.name,h.author?.name),h]));return t.map(h=>{let g=p.get(Ln(h.name,h.author?.name)),w=g?.version,I=!!w&&!!h.version&&Pe(h.version,w);return {...h,updateAvailable:I,catalogItem:g}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(p=>{if(s.has(Ln(p.name,p.author?.name)))return false;if(p.type==="mcp"){let h=p.installCommand?ou(p.installCommand)?.toLowerCase():null;if(i.has(p.name.toLowerCase())||h&&i.has(h))return false}return true}).map(p=>su(p)):a.map(p=>iu(p,p.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(p=>{let h=p.type??"plugin";if(!n.types.has(h))return false;let g=p.origin??"internal";return n.origins.has(g)}),[l,n]),u=useMemo(()=>{let{types:p}=n;if(p.size===1){if(p.has("skill"))return "skills";if(p.has("mcp"))return "MCPs";if(p.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!`:o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>p=>p?e.find(h=>h.name===p.name&&h.author?.name===p.authorName)??null:null,[e]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m}}function Ri(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=y(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Gl();if(t(d),m.length>0){let p=m.map(h=>h.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,E(P.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:me(t=>t.installedItems)}}var oy=x("catalog");function pu(){let e=y(v=>v.activeTab),t=y(v=>v.notification),r=y(v=>v.loading),n=y(v=>v.loadingMessage),o=y(v=>v.catalogError),s=y(v=>v.setCatalogError),i=y(v=>v.catalogFilters),a=Le(v=>v.query),{catalog:l,isLoading:c,error:u,refetch:d}=Ri(),{items:m}=uu(),p=me(v=>v.loadFromDisk),{items:h,emptyMessage:g,getSelectedCatalogItem:w}=cu({catalog:l,installedItems:m,activeTab:e,catalogFilters:i,searchQuery:a}),{actionMenuOpen:I,closeMenu:b,selectedIndex:k,clampIndex:R,filteredItems:L}=Wc({listLength:h.length}),B=L(h),Q=useMemo(()=>e!=="installed"?B:lu(B),[e,B]),ct=useMemo(()=>e==="installed"?au(Q):[],[e,Q]),A=Q[k]??null,S=useMemo(()=>w(A),[w,A]),{notify:_}=Xc(),{handleInstall:V,handleUninstall:X,handleToggleStatus:tn,handleUpdate:It,handleMcpConfigUninstall:Fn}=nu({selectedItem:A,selectedCatalogItem:S,items:h,closeMenu:b,clampIndex:R,notify:_});return useEffect(()=>{p();},[]),useEffect(()=>{R(Q.length);},[Q.length,R]),useEffect(()=>{u&&(oy.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(_r,{}),jsx(al,{}),e==="marketplaces"&&dt()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Kc,{})}):jsx(El,{filteredItems:Q,groups:ct,emptyMessage:g}),(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(Cl,{message:t.message,type:t.type}),I&&A&&(e==="discover"?jsx(vc,{itemName:A.name,itemType:S?.type,onInstall:V,onClose:b}):A.type==="mcp"?jsx(kc,{itemName:A.name,itemScope:A.scope??"user",onUninstall:Fn,onClose:b}):jsx(Ec,{itemName:A.name,itemScope:A.scope??"user",itemStatus:A.status??"enabled",updateAvailable:A.updateAvailable??false,catalogVersion:S?.version,onUninstall:X,onToggleStatus:v=>tn(v),onUpdate:It,onClose:b})),jsx(yo,{})]})}var $=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(me.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 ly=3;function fu(){let e=$(l=>l.setStarterKits),t=$(l=>l.setIsLoadingStarterKits),r=$(l=>l.setStarterKitsError),n=$(l=>l.setPluginStatus),o=$(l=>l.setStep),s=$(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(()=>{me.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let 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<=ly;p++)try{await ve(u.name),n(u.name,"success"),m=!0;break}catch(h){if(h instanceof Re){n(u.name,"success"),m=true;break}d=h instanceof Error?h.message:"Unknown error";}m||(n(u.name,"failed",d),E(P.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"plugin",source:"internal",error_code:"install_failed",error_message:d,interface:H().interfaceType}).catch(()=>{}));}let c=ur();cr("summary_review"),E(P.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:c}).catch(()=>{}),me.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 cy={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}:cy}var hu=Um.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:f(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:f(t.description)})})]})});var Fi=5;function Su({onRetry:e}){let t=$(u=>u.starterKits),r=$(u=>u.selectedStarterKitIndex),n=$(u=>u.isLoadingStarterKits),o=$(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(Dr,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Fi/2)),i=Math.min(t.length,s+Fi);i===t.length&&(s=Math.max(0,i-Fi));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=Um.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:[" ",f(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Ki=8;function Iu(){let e=$(u=>u.selectedStarterKit),t=$(u=>u.plugins),r=$(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,E(P.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(Ki/2)),i=Math.min(t.length,s+Ki);i===t.length&&(s=Math.max(0,i-Ki));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:f(e.name)}),jsx(Text,{dimColor:true,children:f(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 Sy=["Retry failed","Continue anyway"];function vu({name:e,status:t,error:r}){let n=f(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rf,{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 ",f(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function bu({onComplete:e,onRetry:t}){let r=$(c=>c.plugins),n=$(c=>c.step),o=$(c=>c.successCount),s=$(c=>c.failedCount),i=$(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:Sy.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=$(S=>S.step),t=$(S=>S.starterKits),r=$(S=>S.selectedStarterKitIndex),n=$(S=>S.setSelectedStarterKitIndex),o=$(S=>S.selectStarterKit),s=$(S=>S.plugins),i=$(S=>S.pluginCursorIndex),a=$(S=>S.setPluginCursorIndex),l=$(S=>S.setStep),c=$(S=>S.summaryActionIndex),u=$(S=>S.setSummaryActionIndex),d=$(S=>S.failedCount),m=$(S=>S.resetForRetry),p=$(S=>S.goBackToList),h=y(S=>S.setScreen),g=y(S=>S.setFocus),w=y(S=>S.focus),I=Ve(S=>S.setJustAuthenticated),b=Ve(S=>S.justAuthenticated),{loadStarterKits:k,installSelected:R}=fu(),L=useRef(false);useEffect(()=>{e==="bundleList"?(g("bundleList"),L.current||(L.current=true,cr("bundle_selection"))):g(e==="bundleDetail"?"bundleDetail":"installProgress");},[e,g]);let B=useCallback(async()=>{let S=$.getState().selectedStarterKit;if(S){let V=await te();V&&await bt({...V,starterKit:S.slug});}E(P.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:ur()}).catch(()=>{});let{successCount:_}=$.getState();E(P.CLI_ONBOARDING_COMPLETED,{duration_ms:Pt(),tools_installed_count:_}).catch(()=>{}),I(false),g("verify"),h("verify");},[I,g,h]),Q=useCallback(()=>{m(),R();},[m,R]),ct=useCallback(()=>{k();},[k]),A=useCallback(()=>{g("verify"),h("verify");},[g,h]);return useInput((S,_)=>{if(_.escape)uo("esc"),A();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 V=ur();o(t[r]),cr("kit_display"),E(P.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:V}).catch(()=>{});}},{isActive:w==="bundleList"}),useInput((S,_)=>{let V=gu(S,_);if(V.cursorDelta!==0){let X=i+V.cursorDelta;X>=0&&X<s.length&&a(X);}if(V.confirm){let X=$.getState().selectedStarterKit;X&&(async()=>(await te())?.starterKit!==X.slug&&E(P.CLI_KIT_ACCEPTED,{bundle_slug:X.slug}).catch(()=>{}))();let tn=ur();cr("kit_confirmation"),E(P.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:tn}).catch(()=>{});let It=ur();cr("tool_installation"),E(P.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:It}).catch(()=>{}),l("installing"),R();}if(V.back){let X=$.getState().selectedStarterKit;X&&E(P.CLI_KIT_REJECTED,{bundle_slug:X.slug}).catch(()=>{}),p();}},{isActive:w==="bundleDetail"}),useInput((S,_)=>{if(d===0)return;let V=yu(S,_);if(V.cursorDelta!==0){let X=c+V.cursorDelta;X>=0&&X<=1&&u(X);}V.select&&(c===0?Q():B());},{isActive:w==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(_r,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!b&&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:ct}),e==="bundleDetail"&&jsx(Iu,{}),(e==="installing"||e==="summary")&&jsx(bu,{onComplete:B,onRetry:Q})]}),jsx(yo,{})]})}var Py=x("moduleState");function ns(){let e=process.env.FLOW_HOME??de__default.join(Ae__default.homedir(),".flow");return de__default.join(e,"modules.json")}var Ey={retries:5,minTimeout:50};async function Eu(e,t){xe__default.mkdirSync(de__default.dirname(e),{recursive:true});let r=await wf.lock(e+".lock",{realpath:false,retries:Ey});try{return await t()}finally{await r();}}function Cu(){let e=ns();if(!xe__default.existsSync(e))return [];try{let t=JSON.parse(xe__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Py.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),xe__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return xe__default.rmSync(e,{force:true}),[]}}function vr(){return Cu()}function Tu(e){let t=ns();xe__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};xe__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),xe__default.renameSync(r,t);}function Ye(e){return vr().find(t=>t.alias===e)??null}async function tr(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 Wr(){let e=ns();xe__default.existsSync(e)||await Eu(e,async()=>{xe__default.existsSync(e)||Tu([]);});}var ky=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 ky(t,[e]),!0}catch{return false}}function Rt(){return process.platform==="win32"?"npm.cmd":"npm"}var ku=promisify(execFile),os=class{type="npm";async isAvailable(){return St("npm")}async install(t){return 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(Rt(),["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(Rt(),["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),Ry=/^(\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(Ry);return n?n[2]:null}catch{return null}}};var zr=promisify(execFile),Ny=x("curlStrategy"),Mu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function $u(){let e=process.env.FLOW_HOME??de__default.join(Ae__default.homedir(),".flow");return de__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=de__default.join($u(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await zr(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=de__default.join(Ae__default.tmpdir(),`flow-install-${Date.now()}-${Math.random().toString(36).slice(2)}.sh`);try{if(await zr("curl",["-sSL","--fail","-o",s,t]),r||Ny.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{xe__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return xe__default.chmodSync(s,448),await zr("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{xe__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=$u(),i=de__default.join(s,n.binaryName),a=false;try{if(xe__default.mkdirSync(s,{recursive:!0}),a=!0,await zr("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return xe__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}xe__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await zr(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{xe__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=de__default.join(Ae__default.tmpdir(),`curl-checksum-${Date.now()}-${Math.random().toString(36).slice(2)}`);try{await zr("curl",["-L","--fail","-o",n,r]);let o=xe__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=xe__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{xe__default.unlinkSync(n);}catch{}}}};var Ce=x("moduleInstaller");function _t(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 E(P.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Ce.warn(`Failed to emit install failed event: ${String(n)}`);}}async function qr(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"){Ce.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=_t(r),i=false;try{i=await s.isAvailable();}catch(l){Ce.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 E(P.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:t});}catch(l){Ce.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);Ce.warn(`${r} install threw: ${c}`),a={success:false,error:{code:"INSTALL_THREW",message:c},durationMs:Date.now()-n};}if(a.success){await tr({alias:e.alias,name:e.name,installedVersion:a.version??null,installMethod:a.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await E(P.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){Ce.warn(`Failed to emit install completed event: ${String(c)}`);}let l=await Fy(e,t);return l?{...a,pendingInteractiveSetup:l}:a}return await On(e,t,a.error??{code:"UNKNOWN",message:"unknown error"}),a}async function Fy(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 te(),s={credentials:o?{clientId:o.clientId,clientSecret:o.clientSecret,tenant:o.tenant}:null};try{n=r(s);}catch(i){return Ce.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"});if(s.status!==0)return Ce.warn(`postInstall "${o.join(" ")}" exited with status ${s.status??"null"}`),s.stderr&&Ce.warn(s.stderr),null}return null}async function as(e,t){let r=Date.now(),n=Ye(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=_t(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await E(P.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:"command"});}catch(a){Ce.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Ce.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await tr({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await E(P.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Ce.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await E(P.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Ce.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await E(P.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Ce.warn(`Failed to emit update failed event: ${String(a)}`);}return i}function By(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=By(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 qr(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 Vy(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(()=>Vy(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(h=>h.module.alias===d?{...h,selectedStrategy:m}:h));},[]);useInput((d,m)=>{let p=i.current,h=a.current,g=m.upArrow||d==="[A",w=m.downArrow||d==="[B";if(g||w)g&&p>0?s(p-1):w&&p<h.length-1&&s(p+1);else if(d===" "){let I=h[p];I&&!I.module.required&&l(I.module.alias);}else if(m.tab){let I=h[p];if(I&&I.availableStrategies.length>1){let b=I.availableStrategies.indexOf(I.selectedStrategy??I.availableStrategies[0]),k=I.availableStrategies[(b+1)%I.availableStrategies.length];n(R=>R.map(L=>L.module.alias===I.module.alias?{...L,selectedStrategy:k}:L));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Hy(){return Z.filter(e=>e.platforms[process.platform]?.status==="supported")}function ju(e){let t=Hy();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"}},Jy={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},Z=dt()?[Bu,Jy]:[Bu];var Ku=null;function Vu(){return Ku}async function ls(){let t=vr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=Z.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Hu(n);(o||s)&&await tr({...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 _t(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Yr(e){let t=await Promise.all(e.map(r=>Wy(r)));return Ku=t,t}async function Wy(e){let t=zy(e.versionCommand),r=e.platforms[process.platform],n=r?.status==="supported"?r.strategies:[],s=(await Promise.all(n.map(async i=>{try{return await _t(i.type).isAvailable()?i.type:null}catch{return null}}))).filter(i=>i!==null);if(t&&!Ye(e.alias)){let{installedVersion:i,installMethod:a}=await Hu(e);await tr({alias:e.alias,name:e.name,installedVersion:i,installMethod:a,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:s}}function zy(e){if(e.length===0)return false;try{return spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe"}).status===0}catch{return false}}function qy({module:e}){let t=f(e.name);return e.status==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rf,{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 '",f(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 ",f(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",f(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 Yy({confirmedItems:e}){let t=y(h=>h.setScreen),r=y(h=>h.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(()=>{Wr().catch(()=>{}),r("list");let h=re().some(g=>g.name===ne);t(h?"main":"claudeMdSuggestion");},[r,t]);useEffect(()=>{if(s&&a===0&&!u.current){u.current=true;let h=setTimeout(d,1500);return ()=>clearTimeout(h)}},[s,a,d]),useInput((h,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(h=>jsx(qy,{module:h},h.alias))}),m&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:p.reduce((h,g,w)=>(w>0&&h.push(jsx(Text,{children:" | "},`sep-${w}`)),h.push(g),h),[])}),jsx(Box,{paddingX:1,children:a>0?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Zy({probeResults:e,onConfirm:t}){let r=y(p=>p.focus),n=y(p=>p.actionMenuOpen),o=y(p=>p.setActionMenuOpen),s=y(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,h)=>{h.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,h)=>{let g=h===a,w=f(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",w," "]}),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] ":" [ ] ",w]}),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:f(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(pt,{itemName:m,actions:d,onAction:u,onClose:c})]})}function Wu(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),i=y(u=>u.setFocus),a=y(u=>u.setScreen),l=useCallback(u=>{if(ju(u)){Wr().catch(()=>{}),i("list");let m=re().some(p=>p.name===ne);a(m?"main":"claudeMdSuggestion");}else n(u),t("selection");},[i,a]);useEffect(()=>{let u=Vu();if(u){l(u);return}Yr(Z).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(Zy,{probeResults:r,onConfirm:c}),e==="installation"&&jsx(Yy,{confirmedItems:o})]})}var rh=x("ClaudeMdSuggestion"),nh=[`Install ${ne}`,"Skip for now"],oh=["Retry","Skip for now"];function qu(){let e=y(m=>m.setScreen),t=y(m=>m.setFocus),r=$(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{E(P.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,E(P.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ve(ne),o("installed");}catch(m){if(m instanceof Re){o("installed");return}rh.warn(`Failed to install ${ne}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?oh:nh;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(_r,{}),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(rf,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ne,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ne," 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:["/",ne]})]}),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 ",ne]}),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 lh=promisify(execFile),cs="@ciandt-flow/cli";async function Yu(){let e=oe;if(Mi.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 lh(Rt(),["install","-g",e.packageName],{timeout:6e4,shell:!0}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Zu(e){let r=Ye(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=Ye(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await _t(r.installMethod).update(e,t.currentVersion??"");return o.success?{success:true,newVersion:o.version}:{success:false,error:o.error?.message}}function ed(e){let r=Ye(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"},...Z.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(),Yr(Z),Promise.all(Z.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=Z.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 Wr(),t(l=>({...l,outcome:"done"}));}catch{await Wr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function fh({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(rf,{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 gh({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=y(o=>o.setScreen),n=y(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=re().some(i=>i.name===ne);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(fh,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(gh,{outcome:e})})]})}var wh={debug:"gray",info:"cyan",warn:"yellow",error:"red"},nd=10;function od(){let[e,t]=useState(As());useEffect(()=>va(()=>{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:wh[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var bh=x("app"),Ph={auth:Qa,bundleSetup:Pu,moduleSetup:Wu,claudeMdSuggestion:qu,verify:rd,main:pu};function ad(){let{setScreen:e,setFocus:t}=y.getState();e("auth"),t("auth");}function yn(e){let{setScreen:t,setFocus:r}=y.getState();!e.starterKit||e.starterKit.trim()===""?(t("bundleSetup"),r("bundleList")):(t("verify"),r("verify"));}function ld(){E(P.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Pt(),interface:"tui"}).catch(()=>{});}async function ud(){let e=await te();if(e&&qa()&&await Ft()){let{clientSecret:n,...o}=e;Ve.getState().setCredentials(o),ld(),yn(e);return}if(!e){ad();return}try{await Bt();}catch(n){bh.debug(`Token validation failed: ${String(n)}`),ad();return}ld();let{clientSecret:t,...r}=e;Ve.getState().setCredentials(r),yn(e);}function dd(){let{columns:e,rows:t}=useWindowSize(),r=y(a=>a.screen),n=Ph[r],{pendingExit:o}=Ja(),s=y(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=y.getState().debugPanelOpen;y.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 ta(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 at=x("auth");function md(){$e.clearFallbackFile(),so();}var Eh=3,pd=3,fd=` \u2139 The data collected during setup is used solely to improve
116
+ [y/N] `))return us.debug(`[${e}] Removal cancelled by user`),T("Operation cancelled."),0}let n=t.silent?void 0:Ea({text:`Removing MCP "${h(e)}"...`}).start();try{let o=await xe(r);return n?.stop(),o.exitCode!==0?(Vn(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&T(`stdout: ${o.stdout}`),1):(ku(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Vn(t,{name:e,action:"remove",message:Z(o)}),1}}function Mu({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=S(P=>P.setLoading),{install:l,uninstall:u,toggle:c,update:d}=Tu(),p=async(P,A,M)=>{a(true,P),n();try{await A(),o(r.length),s(M,"success");}catch(N){let G=N instanceof Error?N.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${G}`),s(G,"error");}finally{a(false);}};return {handleInstall:(P,A)=>{e&&t&&p(`Installing ${e.name}...`,()=>l(t,{scope:P,...A!==void 0?{providerId:A}:{}}),"\u2713 Installed successfully");},handleUninstall:P=>{e&&p(`Uninstalling ${e.name}...`,()=>u(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let A=e.status==="enabled";p(A?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>c(e.name,P),A?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{a(true,`Updating ${e.name}${P}...`),n();try{await d(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(M){if(M instanceof Wt)s(M.message,"info");else {let N=M instanceof Error?M.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${N}`),s(N,"error");}}finally{a(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let A=P.length;(async()=>{a(true,`Updating ${A} plugin${A>1?"s":""}...`),n();try{let N=[];for(let $ of P)N.push(await d($.name).then(()=>({status:"fulfilled",value:void 0}),w=>({status:"rejected",reason:w})));let G=N.filter($=>$.status==="fulfilled").length,ye=N.map(($,w)=>$.status==="rejected"?P[w].name:null).filter($=>$!==null);o(r.length),ye.length===0?s(`\u2713 Updated ${G}/${A} plugin${A>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${ye.join(", ")}`),s(`Updated ${G}/${A}; failed: ${ye.join(", ")}`,G>0?"info":"error"));}finally{a(false);}})();},handleMcpConfigUninstall:P=>{e&&p(`Removing MCP ${e.name}...`,async()=>{let A=Yi(e.name,P),M=await xe(A);if(M.exitCode!==0)throw new Error(M.stderr||"MCP removal failed");ue.getState().loadFromDisk();},"\u2713 MCP removed");}}}var ds=x("api:bundle"),en=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Hn=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}};async function ps(e){let t=encodeURIComponent(e);ds.debug(`Fetching bundle by name "${e}"`);let r;try{r=await mt().get(`v1/use-cases/by-name/${t}`).json(),ds.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){if(n instanceof HTTPError){let o=n.response.status;throw ds.error(`HTTP error fetching bundle '${e}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new en(e):o===StatusCodes.INTERNAL_SERVER_ERROR?new Hn:new Error(`Server error (${o}) \u2014 please try again later.`)}throw ds.error(`Unexpected error fetching bundle '${e}': ${n instanceof Error?n.message:String(n)}`),n}if(r.length===0)throw new en(e);return r[0]}function Ru({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:a=>{let{setLoading:l,setBundleInstallFlow:u}=S.getState();l(true,"Loading bundle..."),ps(a).then(c=>{l(false),S.getState().actionMenuOpen&&u({phase:"detail",bundle:c});}).catch(c=>{l(false),t(c instanceof Error?c.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),ue.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var Jn=["local","project","user"],Gy=new Set(["--transport","--scope","-s"]);function _u(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(Gy.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function br(e,t){return t?`${e}::${t}`:e}function Zi(e){return e===te?mn:kr}function Du(e){return {name:h(e.name),version:e.version?h(e.version):e.version,description:e.description?h(e.description):e.description,authorName:e.author?.name?h(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??mn}}function Qi(e,t){let r=Zi(e.marketplace);return {name:h(e.name),version:e.version?h(e.version):e.version,description:e.description?h(e.description):e.description,authorName:e.author?.name?h(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Ou(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 Jn.filter(r=>t.has(r)).map(r=>({scope:r,label:fn[r].label,pathHint:fn[r].pathHint,items:t.get(r)??[]}))}function Nu(e){let t=r=>{if(!r)return 1/0;let n=Jn.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Bu({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(m=>br(m.name,m.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(m=>m.type==="mcp").map(m=>m.name.toLowerCase())),[t]),a=useMemo(()=>{let m=new Map(e.map(y=>[br(y.name,y.author?.name),y])),g=new Map(e.map(y=>[y.name,y]));return t.map(y=>{let I=m.get(br(y.name,y.author?.name))??g.get(y.name),C=I?.version,P=!!C&&!!y.version&&Te(y.version,C);return {...y,updateAvailable:P,catalogItem:I}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(m=>{if(s.has(br(m.name,m.author?.name)))return false;if(m.type==="mcp"){let g=m.installCommand?_u(m.installCommand)?.toLowerCase():null;if(i.has(m.name.toLowerCase())||g&&i.has(g))return false}return true}).map(m=>Du(m)):r==="updates"?a.filter(m=>m.updateAvailable).map(m=>Qi(m,m.catalogItem)):a.map(m=>Qi(m,m.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(m=>{let g=m.type??"bundle";if(!n.types.has(g))return false;let y=m.origin??"internal";return n.origins.has(y)}),[l,n]),c=useMemo(()=>{let{types:m}=n;if(m.size===1){if(m.has("skill"))return "skills";if(m.has("mcp"))return "MCPs";if(m.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),p=useMemo(()=>{let m=new Map(e.map(y=>[br(y.name,y.author?.name),y])),g=new Map(e.map(y=>[y.name,y]));return y=>y?m.get(br(y.name,y.authorName))??g.get(y.name)??null:null},[e]),f=useMemo(()=>a.filter(m=>m.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:p,outdatedCount:f}}function ea(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:p}=await pc();if(t(d),p.length>0){let f=p.map(m=>m.adapterName).join(", ");a(`Some catalogs failed to load: ${f}`);}l.current||(l.current=!0,b(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(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Uu(){return {items:ue(t=>t.installedItems)}}var Yy=x("catalog");function ju(){let e=S(Y=>Y.bundleInstallFlow),t=S(Y=>Y.activeTab),r=S(Y=>Y.notification),n=S(Y=>Y.loading),o=S(Y=>Y.loadingMessage),s=S(Y=>Y.catalogError),i=S(Y=>Y.setCatalogError),a=S(Y=>Y.catalogFilters),l=Oe(Y=>Y.query),{catalog:u,isLoading:c,error:d,refetch:p}=ea(),{items:f}=Uu(),m=ue(Y=>Y.loadFromDisk),{items:g,emptyMessage:y,getSelectedCatalogItem:I,outdatedCount:C}=Bu({catalog:u,installedItems:f,activeTab:t,catalogFilters:a,searchQuery:l}),{actionMenuOpen:P,closeMenu:A,selectedIndex:M,clampIndex:N,filteredItems:G}=Iu({listLength:g.length}),ye=G(g),$=useMemo(()=>t!=="installed"&&t!=="updates"?ye:Nu(ye),[t,ye]),w=useMemo(()=>t==="installed"||t==="updates"?Ou($):[],[t,$]),k=$[M]??null,j=useMemo(()=>I(k),[I,k]),{notify:W}=bu(),{handleInstall:dn,handleUninstall:bt,handleToggleStatus:Qn,handleUpdate:L,handleBatchUpdate:O,handleMcpConfigUninstall:U}=Mu({selectedItem:k,selectedCatalogItem:j,items:g,closeMenu:A,clampIndex:N,notify:W}),{handleBundleInstallStart:pe,handleBundleDetailConfirm:pn,handleBundleDetailBack:Hp,handleBundleInstallComplete:Jp}=Ru({closeMenu:A,notify:W}),Gp=useCallback(()=>O($),[O,$]);return useEffect(()=>{m();},[]),useEffect(()=>{N($.length);},[$.length,N]),useEffect(()=>{d&&(Yy.error(`[catalog] ${d instanceof Error?d.message:String(d)}`),i("Failed to load catalog"));},[d]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Nr,{}),jsx(Al,{outdatedCount:C}),t==="marketplaces"&&Jt()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(hu,{})}):jsx(Jl,{filteredItems:$,groups:w,emptyMessage:y,onBatchUpdate:Gp}),(n||c)&&jsx(Mo,{message:n?o:"Loading catalog..."}),s&&!c&&t==="discover"&&jsx(Lo,{message:s,onRetry:()=>{i(null),p();},onBack:()=>i(null)}),r&&jsx(Gl,{message:r.message,type:r.type}),P&&k&&(t==="discover"?j?.type==="bundle"?e?.phase==="installing"?jsx(nu,{bundle:e.bundle,onComplete:Jp}):jsx(Jc,{itemName:k.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>pe(k.name),onConfirm:pn,onClose:e?.phase==="detail"?Hp:A}):jsx(Vc,{itemName:k.name,itemType:j?.type,onInstall:dn,onClose:A}):k.type==="mcp"?jsx(Yc,{itemName:k.name,itemScope:k.scope??"user",onUninstall:U,onClose:A}):jsx(zc,{itemName:k.name,itemScope:k.scope??"user",itemStatus:k.status??"enabled",updateAvailable:k.updateAvailable??false,catalogVersion:j?.version,onUninstall:bt,onToggleStatus:Y=>Qn(Y),onUpdate:L,onClose:A})),jsx($o,{})]})}var _=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ue.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));var th=3;function Vu(){let e=_(l=>l.setStarterKits),t=_(l=>l.setIsLoadingStarterKits),r=_(l=>l.setStarterKitsError),n=_(l=>l.setPluginStatus),o=_(l=>l.setStep),s=_(l=>l.computeSummary),i=useCallback(async()=>{t(true),r(null);try{let l=await Fo();e(l);}catch(l){r(l instanceof Error?l.message:String(l));}finally{t(false);}},[t,r,e]);useEffect(()=>{ue.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let l=_.getState().plugins.filter(c=>c.selected&&c.status==="pending");for(let c of l){n(c.name,"installing");let d="",p=false;for(let f=1;f<=th;f++)try{await Ee(c.name),n(c.name,"success"),p=!0;break}catch(m){if(m instanceof Ne){n(c.name,"success"),p=true;break}d=m instanceof Error?m.message:"Unknown error";}p||(n(c.name,"failed",d),b(v.CLI_TOOL_INSTALL_FAILED,{tool_id:c.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:d,interface:H().interfaceType}).catch(()=>{}));}let u=pr();dr("summary_review"),b(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),ue.getState().loadFromDisk(),s(),o("summary");},[n,s,o]);return {loadStarterKits:i,installSelected:a}}var Gn={cursorDelta:0,confirm:false,back:false};function Hu(e,t){return t.upArrow?{...Gn,cursorDelta:-1}:t.downArrow?{...Gn,cursorDelta:1}:t.escape?{...Gn,back:true}:t.return?{...Gn,confirm:true}:Gn}var rh={cursorDelta:0,select:false};function Ju(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:rh}var Gu=Sf.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:h(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:h(t.description)})})]})});var ia=5;function Wu({onRetry:e}){let t=_(c=>c.starterKits),r=_(c=>c.selectedStarterKitIndex),n=_(c=>c.isLoadingStarterKits),o=_(c=>c.starterKitsError);if(n)return jsx(Mo,{message:"Loading Starter Kits..."});if(o)return jsx(Lo,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Br,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(ia/2)),i=Math.min(t.length,s+ia);i===t.length&&(s=Math.max(0,i-ia));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Gu,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var Xu=Sf.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",h(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var ca=8;function qu(){let e=_(c=>c.selectedStarterKit),t=_(c=>c.plugins),r=_(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(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(c=>c.installed).length,s=Math.max(0,r-Math.floor(ca/2)),i=Math.min(t.length,s+ca);i===t.length&&(s=Math.max(0,i-ca));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:h(e.name)}),jsx(Text,{dimColor:true,children:h(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Xu,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var dh=["Retry failed","Continue anyway"];function Yu({name:e,status:t,error:r}){let n=h(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ru,{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 ",h(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function Zu({onComplete:e,onRetry:t}){let r=_(u=>u.plugins),n=_(u=>u.step),o=_(u=>u.successCount),s=_(u=>u.failedCount),i=_(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(Yu,{name:u.name,status:u.status,error:u.error},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(Yu,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:dh.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Qu(){let e=_(w=>w.step),t=_(w=>w.starterKits),r=_(w=>w.selectedStarterKitIndex),n=_(w=>w.setSelectedStarterKitIndex),o=_(w=>w.selectStarterKit),s=_(w=>w.plugins),i=_(w=>w.pluginCursorIndex),a=_(w=>w.setPluginCursorIndex),l=_(w=>w.setStep),u=_(w=>w.summaryActionIndex),c=_(w=>w.setSummaryActionIndex),d=_(w=>w.failedCount),p=_(w=>w.resetForRetry),f=_(w=>w.goBackToList),m=S(w=>w.setScreen),g=S(w=>w.setFocus),y=S(w=>w.focus),I=Ge(w=>w.setJustAuthenticated),C=Ge(w=>w.justAuthenticated),{loadStarterKits:P,installSelected:A}=Vu(),M=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),M.current||(M.current=true,dr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let N=useCallback(async()=>{let w=_.getState().selectedStarterKit;if(w){let j=await ne();j&&await Pt({...j,starterKit:w.slug});}b(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:pr()}).catch(()=>{});let{successCount:k}=_.getState();b(v.CLI_ONBOARDING_COMPLETED,{duration_ms:Tt(),tools_installed_count:k}).catch(()=>{}),I(false),g("verify"),m("verify");},[I,g,m]),G=useCallback(()=>{p(),A();},[p,A]),ye=useCallback(()=>{P();},[P]),$=useCallback(()=>{g("verify"),m("verify");},[g,m]);return useInput((w,k)=>{if(k.escape)Po("esc"),$();else if(k.upArrow&&r>0)n(r-1);else if(k.downArrow&&r<t.length-1)n(r+1);else if(k.return&&t.length>0){let j=pr();o(t[r]),dr("kit_display"),b(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:j}).catch(()=>{});}},{isActive:y==="starterKitList"}),useInput((w,k)=>{let j=Hu(w,k);if(j.cursorDelta!==0){let W=i+j.cursorDelta;W>=0&&W<s.length&&a(W);}if(j.confirm){let W=_.getState().selectedStarterKit;W&&(async()=>(await ne())?.starterKit!==W.slug&&b(v.CLI_KIT_ACCEPTED,{bundle_slug:W.slug}).catch(()=>{}))();let dn=pr();dr("kit_confirmation"),b(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:dn}).catch(()=>{});let bt=pr();dr("tool_installation"),b(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:bt}).catch(()=>{}),l("installing"),A();}if(j.back){let W=_.getState().selectedStarterKit;W&&b(v.CLI_KIT_REJECTED,{bundle_slug:W.slug}).catch(()=>{}),f();}},{isActive:y==="starterKitDetail"}),useInput((w,k)=>{if(d===0)return;let j=Ju(w,k);if(j.cursorDelta!==0){let W=u+j.cursorDelta;W>=0&&W<=1&&c(W);}j.select&&(u===0?G():N());},{isActive:y==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Nr,{}),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."}),!C&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(Wu,{onRetry:ye}),e==="starterKitDetail"&&jsx(qu,{}),(e==="installing"||e==="summary")&&jsx(Zu,{onComplete:N,onRetry:G})]}),jsx($o,{})]})}var hh=x("moduleState");function Is(){let e=process.env.FLOW_HOME??fe__default.join(Le__default.homedir(),".flow");return fe__default.join(e,"modules.json")}var Sh={retries:5,minTimeout:50};async function ed(e,t){ve__default.mkdirSync(fe__default.dirname(e),{recursive:true});let r=await eg.lock(e+".lock",{realpath:false,retries:Sh});try{return await t()}finally{await r();}}function td(){let e=Is();if(!ve__default.existsSync(e))return [];try{let t=JSON.parse(ve__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(hh.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ve__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ve__default.rmSync(e,{force:true}),[]}}function Pr(){return td()}function rd(e){let t=Is();ve__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ve__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),ve__default.renameSync(r,t);}function et(e){return Pr().find(t=>t.alias===e)??null}async function or(e){let t=Is();await ed(t,async()=>{let r=td(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,rd(r);});}async function rn(){let e=Is();ve__default.existsSync(e)||await ed(e,async()=>{ve__default.existsSync(e)||rd([]);});}var Ih=promisify(execFile);function sr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function xt(e){let t=process.platform==="win32"?"where":"which";try{return await Ih(t,[e]),!0}catch{return false}}function Ot(){return process.platform==="win32"?"npm.cmd":"npm"}var nd=promisify(execFile),vs=class{type="npm";async isAvailable(){return xt("npm")}async install(t){return this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=sr(t,"npm");if(!r)return null;try{let{stdout:n}=await nd(Ot(),["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=sr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await nd(Ot(),["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 od=promisify(execFile),Th=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,bs=class{type="homebrew";async isAvailable(){return xt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=sr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=sr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return await od("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 od("brew",["list","--versions",t]),n=r.trim().match(Th);return n?n[2]:null}catch{return null}}};var nn=promisify(execFile),$h=x("curlStrategy"),id=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ad(){let e=process.env.FLOW_HOME??fe__default.join(Le__default.homedir(),".flow");return fe__default.join(e,"bin")}var Es=class{type="curl";async isAvailable(){return xt("curl")}async install(t){let r=Date.now(),n=sr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=fe__default.join(ad(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await nn(n,["--version"]),s=o.match(id);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=fe__default.join(Le__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await nn("curl",["-sSL","--fail","-o",s,t]),r||$h.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{ve__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ve__default.chmodSync(s,448),await nn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{ve__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ad(),i=fe__default.join(s,n.binaryName),a=false;try{if(ve__default.mkdirSync(s,{recursive:!0}),a=!0,await nn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ve__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ve__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await nn(i,["--version"]),c=u.match(id);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ve__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=fe__default.join(Le__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await nn("curl",["-L","--fail","-o",n,r]);let o=ve__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ve__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{ve__default.unlinkSync(n);}catch{}}}};var Ae=x("moduleInstaller");function Nt(e){switch(e){case "npm":return new vs;case "homebrew":return new bs;case "curl":return new Es}}async function Xn(e,t,r){try{await b(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){Ae.warn(`Failed to emit install failed event: ${String(n)}`);}}async function sn(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"){Ae.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 Xn(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 Xn(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 Xn(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}let s=Nt(r),i=false;try{i=await s.isAvailable();}catch(l){Ae.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 Xn(e,t,l),{success:false,error:l,durationMs:Date.now()-n}}try{await b(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:t});}catch(l){Ae.warn(`Failed to emit install started event: ${String(l)}`);}let a;try{a=await s.install(e);}catch(l){let u=l instanceof Error?l.message:String(l);Ae.warn(`${r} install threw: ${u}`),a={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-n};}if(a.success){await or({alias:e.alias,name:e.name,installedVersion:a.version??null,installMethod:a.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await b(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(u){Ae.warn(`Failed to emit install completed event: ${String(u)}`);}let l=await Lh(e,t);return l?{...a,pendingInteractiveSetup:l}:a}return await Xn(e,t,a.error??{code:"UNKNOWN",message:"unknown error"}),a}async function Lh(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 Ae.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"});if(s.status!==0)return Ae.warn(`postInstall "${o.join(" ")}" exited with status ${s.status??"null"}`),s.stderr&&Ae.warn(s.stderr),null}return null}async function Ps(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Nt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await b(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ae,trigger:"command"});}catch(a){Ae.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);Ae.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await or({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await b(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){Ae.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await b(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Ae.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await b(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){Ae.warn(`Failed to emit update failed event: ${String(a)}`);}return i}function Rh(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 ud(e){let[t,r]=useState(()=>e.map(c=>({alias:c.module.alias,name:c.module.name,status:"pending"}))),[n,o]=useState(false),s=useCallback((c,d)=>{r(p=>p.map(f=>f.alias===c?{...f,...d}:f));},[]),i=useCallback(async()=>{for(let c of e){let d=Rh(c);if(!c.selectedStrategy){let p=d?`No package manager available. Install manually: ${d}`:"No package manager available for this platform";s(c.module.alias,{status:"failed",error:p,manualInstallHint:d||void 0});continue}s(c.module.alias,{status:"installing"});try{let p=await sn(c.module,"onboarding",c.selectedStrategy);p.success?s(c.module.alias,{status:"installed",pendingSetupCommand:p.pendingInteractiveSetup?.join(" ")}):s(c.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:d});}catch(p){s(c.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:d});}}o(true);},[e,s]),a=useMemo(()=>t.filter(c=>c.status==="installed").length,[t]),l=useMemo(()=>t.filter(c=>c.status==="failed").length,[t]),u=useMemo(()=>t.filter(c=>c.status==="skipped").length,[t]);return {modules:t,install:i,isComplete:n,installedCount:a,failedCount:l,skippedCount:u}}function Oh(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 gd(e,t){let[r,n]=useState(()=>Oh(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(p=>p.map(f=>f.module.alias!==d||f.module.required?f:{...f,checked:!f.checked}));},[]),u=useCallback((d,p)=>{n(f=>f.map(m=>m.module.alias===d?{...m,selectedStrategy:p}:m));},[]);useInput((d,p)=>{let f=i.current,m=a.current,g=p.upArrow||d==="[A",y=p.downArrow||d==="[B";if(g||y)g&&f>0?s(f-1):y&&f<m.length-1&&s(f+1);else if(d===" "){let I=m[f];I&&!I.module.required&&l(I.module.alias);}else if(p.tab){let I=m[f];if(I&&I.availableStrategies.length>1){let C=I.availableStrategies.indexOf(I.selectedStrategy??I.availableStrategies[0]),P=I.availableStrategies[(C+1)%I.availableStrategies.length];n(A=>A.map(M=>M.module.alias===I.module.alias?{...M,selectedStrategy:P}:M));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}function Nh(){return ee.filter(e=>e.platforms[process.platform]?.status==="supported")}function hd(e){let t=Nh();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var yd={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"}},Bh={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},ee=Jt()?[yd,Bh]:[yd];var Sd=null;function wd(){return Sd}async function Ts(){let t=Pr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=ee.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await xd(n);(o||s)&&await or({...r,installedVersion:o,installMethod:s});}}async function xd(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 Nt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function an(e){let t=await Promise.all(e.map(r=>Fh(r)));return Sd=t,t}async function Fh(e){let t=jh(e.versionCommand),r=e.platforms[process.platform],n=r?.status==="supported"?r.strategies:[],s=(await Promise.all(n.map(async i=>{try{return await Nt(i.type).isAvailable()?i.type:null}catch{return null}}))).filter(i=>i!==null);if(t&&!et(e.alias)){let{installedVersion:i,installMethod:a}=await xd(e);await or({alias:e.alias,name:e.name,installedVersion:i,installMethod:a,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:s}}function jh(e){if(e.length===0)return false;try{return spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe"}).status===0}catch{return false}}function Vh({module:e}){let t=h(e.name);return e.status==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ru,{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 '",h(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 ",h(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",h(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function Hh({confirmedItems:e}){let t=S(m=>m.setScreen),r=S(m=>m.setFocus),{modules:n,install:o,isComplete:s,installedCount:i,failedCount:a,skippedCount:l}=ud(e),u=useRef(false),c=useRef(false);useEffect(()=>{u.current||(u.current=true,o());},[o]);let d=useCallback(()=>{rn().catch(()=>{}),r("list");let m=se().some(g=>g.name===ie);t(m?"main":"claudeMdSuggestion");},[r,t]);useEffect(()=>{if(s&&a===0&&!c.current){c.current=true;let m=setTimeout(d,1500);return ()=>clearTimeout(m)}},[s,a,d]),useInput((m,g)=>{g.return&&d();},{isActive:s});let p=s,f=[];return i>0&&f.push(jsxs(Text,{color:"green",children:[i," installed"]},"i")),a>0&&f.push(jsxs(Text,{color:"red",children:[a," failed"]},"f")),l>0&&f.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(m=>jsx(Vh,{module:m},m.alias))}),p&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:f.reduce((m,g,y)=>(y>0&&m.push(jsx(Text,{children:" | "},`sep-${y}`)),m.push(g),m),[])}),jsx(Box,{paddingX:1,children:a>0?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Jh({probeResults:e,onConfirm:t}){let r=S(f=>f.focus),n=S(f=>f.actionMenuOpen),o=S(f=>f.setActionMenuOpen),s=S(f=>f.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=gd(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(f=>{(f==="Install"||f==="Skip")&&t(l),u();},[l,t,u]);useInput((f,m)=>{m.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],p=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((f,m)=>{let g=m===a,y=h(f.module.name);return f.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",y," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},f.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",f.checked?" [\u2713] ":" [ ] ",y]}),f.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",f.selectedStrategy??""]}),f.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",f.availableStrategies.indexOf(f.selectedStrategy??f.availableStrategies[0])+1,"/",f.availableStrategies.length," \u2194)"]})]}),f.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:h(f.module.description)})})]},f.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(ze,{itemName:p,actions:d,onAction:c,onClose:u})]})}function bd(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),i=S(c=>c.setFocus),a=S(c=>c.setScreen),l=useCallback(c=>{if(hd(c)){rn().catch(()=>{}),i("list");let p=se().some(f=>f.name===ie);a(p?"main":"claudeMdSuggestion");}else n(c),t("selection");},[i,a]);useEffect(()=>{let c=wd();if(c){l(c);return}an(ee).then(l).catch(()=>{n([]),t("selection");});},[l]);let u=useCallback(c=>{s(c),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(Jh,{probeResults:r,onConfirm:u}),e==="installation"&&jsx(Hh,{confirmedItems:o})]})}var Xh=x("ClaudeMdSuggestion"),qh=[`Install ${ie}`,"Skip for now"],Yh=["Retry","Skip for now"];function Td(){let e=S(p=>p.setScreen),t=S(p=>p.setFocus),r=_(p=>p.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{b(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,b(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Ee(ie),o("installed");}catch(p){if(p instanceof Ne){o("installed");return}Xh.warn(`Failed to install ${ie}: ${p instanceof Error?p.message:p}`),o("error");}},[]),d=n==="error"?Yh:qh;return useInput((p,f)=>{if(f.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){f.upArrow&&s>0?i(s-1):f.downArrow&&s<d.length-1?i(s+1):f.return&&(s===0?(i(0),c()):u());return}n==="installed"&&f.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Nr,{}),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(Pd,{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(ru,{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(Pd,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Pd({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 tS=promisify(execFile),Cs="@ciandt-flow/cli";async function Cd(){let e=ae;if(qi.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 ks(e){try{return await tS(Ot(),["install","-g",e.packageName],{timeout:6e4,shell:!0}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function kd(e){let r=et(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 Ad(e,t){let r=et(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Nt(r.installMethod).update(e,t.currentVersion??"");return o.success?{success:true,newVersion:o.version}:{success:false,error:o.error?.message}}function $d(e){let r=et(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Md(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ee.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([Cd(),an(ee),Promise.all(ee.map(l=>kd(l)))]);if(Ts(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await ks(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=ee.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await Ad(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:$d(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await rn(),t(l=>({...l,outcome:"done"}));}catch{await rn(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function aS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ru,{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 lS({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 Ld(){let{outcome:e,items:t}=Md(),r=S(o=>o.setScreen),n=S(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(aS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(lS,{outcome:e})})]})}var pS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Rd=10;function _d(){let[e,t]=useState(Gs());useEffect(()=>Va(()=>{t([...Gs()]);}),[]);let r=e.slice(-Rd);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Rd,") \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:pS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var yS=x("app"),hS={auth:xl,starterKitSetup:Qu,moduleSetup:bd,claudeMdSuggestion:Td,verify:Ld,main:ju};function Nd(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Tn(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Bd(){b(v.CLI_SESSION_STARTED,{cli_version:ae,os:process.platform,node_version:process.version,duration_ms:Tt(),interface:"tui"}).catch(()=>{});}async function Fd(){let e=await ne();if(e&&hl()&&await Vt()){let{clientSecret:n,...o}=e;Ge.getState().setCredentials(o),Bd(),Tn(e);return}if(!e){Nd();return}try{await Ht();}catch(n){yS.debug(`Token validation failed: ${String(n)}`),Nd();return}Bd();let{clientSecret:t,...r}=e;Ge.getState().setCredentials(r),Tn(e);}function jd(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=hS[r],{pendingExit:o}=pl(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(_d,{}),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 va(e,t={}){let r=To({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Co(r),await Pt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var ut=x("auth");function Vd(){De.clearFallbackFile(),xo();}var SS=3,Kd=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
- `;function br(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===`
118
+ `;function Tr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
119
119
  `){l(),process.stdout.write(`
120
- `),r(i);return}if(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 Ch(){let e=dr();return process.stdout.write(`
121
- `+M.yellow(" \u26A0 ")+`${f(e)} contains invalid JSON.
122
- `),(await br(M.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function gd(e,t){try{await ta(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 Ch())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await ta(e,{allowOverwriteMalformed:true});}}async function yd(){for(let e=1;e<=pd;e++)try{return await Co()}catch{if(e===pd)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function hd(){let e=await yd();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
123
- `+M.cyan(" ? ")+`Starter Kit:
124
- `),e.forEach((t,r)=>{process.stdout.write(` ${M.cyan(`${r+1})`)} ${f(t.name)}
120
+ `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function wS(){let e=mr();return process.stdout.write(`
121
+ `+R.yellow(" \u26A0 ")+`${h(e)} contains invalid JSON.
122
+ `),(await Tr(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Jd(e,t){try{await va(e);return}catch(r){if(!(r instanceof fr))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${mr()} and retry.`);if(!await wS())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await va(e,{allowOverwriteMalformed:true});}}async function Gd(){for(let e=1;e<=Kd;e++)try{return await Fo()}catch{if(e===Kd)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Wd(){let e=await Gd();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
123
+ `+R.cyan(" ? ")+`Starter Kit:
124
+ `),e.forEach((t,r)=>{process.stdout.write(` ${R.cyan(`${r+1})`)} ${h(t.name)}
125
125
  `);}),process.stdout.write(`
126
- `);;){let t=(await br(M.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(M.yellow(` \u26A0 Invalid selection. Please try again.
127
- `));}}async function Sd(e){if(e.plugins.length===0)return process.stdout.write(M.dim(`
128
- Starter kit '${f(e.name)}' has no plugins to install.
126
+ `);;){let t=(await Tr(R.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(R.yellow(` \u26A0 Invalid selection. Please try again.
127
+ `));}}async function zd(e){if(e.plugins.length===0)return process.stdout.write(R.dim(`
128
+ Starter kit '${h(e.name)}' has no plugins to install.
129
129
  `)),true;process.stdout.write(`
130
- Installing ${e.plugins.length} plugins from '${f(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(M.dim(` [${s}/${n}] Installing ${f(o)}...`));let i=false;for(let a=1;a<=Eh;a++)try{await ve(o),t++,i=!0;break}catch(l){if(l instanceof Re){t++,i=true;break}}i?process.stdout.write(M.green(` done
132
- `)):(r++,process.stdout.write(M.red(` failed
133
- `)));}return r===0?process.stdout.write(M.green(` \u2713 Starter kit '${f(e.name)}' selected. ${t}/${n} plugins installed successfully.
134
- `)):process.stdout.write(M.yellow(` \u26A0 Starter kit '${f(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
135
- `)),r===0}async function wd(){process.stdout.write(`
136
- `),process.stdout.write(M.bold(` Personalize your Claude Code
137
- `)),process.stdout.write(M.dim(` This plugin helps Claude understand your preferences and work style.
130
+ Installing ${e.plugins.length} plugins from '${h(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(R.dim(` [${s}/${n}] Installing ${h(o)}...`));let i=false;for(let a=1;a<=SS;a++)try{await Ee(o),t++,i=!0;break}catch(l){if(l instanceof Ne){t++,i=true;break}}i?process.stdout.write(R.green(` done
132
+ `)):(r++,process.stdout.write(R.red(` failed
133
+ `)));}return r===0?process.stdout.write(R.green(` \u2713 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed successfully.
134
+ `)):process.stdout.write(R.yellow(` \u26A0 Starter kit '${h(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
135
+ `)),r===0}async function Xd(){process.stdout.write(`
136
+ `),process.stdout.write(R.bold(` Personalize your Claude Code
137
+ `)),process.stdout.write(R.dim(` This plugin helps Claude understand your preferences and work style.
138
138
 
139
- `));let e=(await br(M.cyan(" ? ")+`Install ${ne}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){E(P.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(M.dim(`
139
+ `));let e=(await Tr(R.cyan(" ? ")+`Install ${ie}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){b(v.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(R.dim(`
140
140
  You can always install it later from the catalog.
141
- `));return}E(P.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(M.dim(` Installing ${ne}...`));try{await ve(ne),process.stdout.write(M.green(` done
142
- `));}catch(t){if(t instanceof Re)process.stdout.write(M.green(` already installed
143
- `));else {at.warn(`Failed to install ${ne}: ${t instanceof Error?t.message:t}`),process.stdout.write(M.red(` failed
144
- `)),process.stdout.write(M.dim(` You can install it later from the catalog.
141
+ `));return}b(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(R.dim(` Installing ${ie}...`));try{await Ee(ie),process.stdout.write(R.green(` done
142
+ `));}catch(t){if(t instanceof Ne)process.stdout.write(R.green(` already installed
143
+ `));else {ut.warn(`Failed to install ${ie}: ${t instanceof Error?t.message:t}`),process.stdout.write(R.red(` failed
144
+ `)),process.stdout.write(R.dim(` You can install it later from the catalog.
145
145
  `));return}}process.stdout.write(`
146
146
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
147
- `),process.stdout.write(M.cyan.bold(` /${ne}
147
+ `),process.stdout.write(R.cyan.bold(` /${ie}
148
148
  `)),process.stdout.write(` Claude will guide you through the rest.
149
- `);}async function Th(e){md(),process.stdout.write(`
150
- `+fd+`
151
- `),at.debug(`[${e.tenant}] Authenticating tenant`);try{await lr(e);}catch(t){let r=f(t instanceof Error?t.message:"unknown error");return at.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(M.red(` \u2717 Authentication failed: ${r}
152
- `)),1}try{let t;if(e.starterKit){let r=await yd(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(M.red(` \u2717 Starter kit '${f(e.starterKit)}' not found.
149
+ `);}async function xS(e){Vd(),process.stdout.write(`
150
+ `+Hd+`
151
+ `),ut.debug(`[${e.tenant}] Authenticating tenant`);try{await ur(e);}catch(t){let r=h(t instanceof Error?t.message:"unknown error");return ut.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(R.red(` \u2717 Authentication failed: ${r}
152
+ `)),1}try{let t;if(e.starterKit){let r=await Gd(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(R.red(` \u2717 Starter kit '${h(e.starterKit)}' not found.
153
153
  `)),process.stderr.write(` Available starter kits:
154
- `);for(let o of r)process.stderr.write(` - ${f(o.slug)} (${f(o.name)})
155
- `);return 1}t=n;}else t=await hd();return await gd({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug},!1),await Sd(t),await wd(),at.info(`[${e.tenant}] Authentication successful`),process.stdout.write(M.green(`
156
- \u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${dr()}.
154
+ `);for(let o of r)process.stderr.write(` - ${h(o.slug)} (${h(o.name)})
155
+ `);return 1}t=n;}else t=await Wd();return await Jd({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug},!1),await zd(t),await Xd(),ut.info(`[${e.tenant}] Authentication successful`),process.stdout.write(R.green(`
156
+ \u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${mr()}.
157
157
 
158
- `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=f(t instanceof Error?t.message:"unknown error");return at.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(M.red(` \u2717 Starter kit setup failed: ${r}
159
- `)),1}}async function kh(){md(),at.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
160
- `),process.stdout.write(fd+`
161
- `);let e=(await br(M.cyan(" ? ")+"Client ID: ")).trim(),t=(await br(M.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await br(M.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return at.error("[auth] Validation failed: all fields are required"),process.stderr.write(M.red(` \u2717 All fields are required
162
- `)),1;at.debug(`[${r}] Authenticating tenant`);try{await lr({clientId:e,clientSecret:t,tenant:r});}catch(o){let s=f(o instanceof Error?o.message:"unknown error");return at.error(`[${r}] Authentication failed: ${s}`),process.stderr.write(M.red(` \u2717 Authentication failed: ${s}
163
- `)),1}let n=await hd();return await gd({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug},!0),await Sd(n),await wd(),at.info(`[${r}] Authentication successful`),process.stdout.write(M.green(`
164
- \u2713 Setup complete. Tenant: ${r}. JWT written to ${dr()}.
158
+ `)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=h(t instanceof Error?t.message:"unknown error");return ut.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(R.red(` \u2717 Starter kit setup failed: ${r}
159
+ `)),1}}async function IS(){Vd(),ut.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
160
+ `),process.stdout.write(Hd+`
161
+ `);let e=(await Tr(R.cyan(" ? ")+"Client ID: ")).trim(),t=(await Tr(R.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await Tr(R.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return ut.error("[auth] Validation failed: all fields are required"),process.stderr.write(R.red(` \u2717 All fields are required
162
+ `)),1;ut.debug(`[${r}] Authenticating tenant`);try{await ur({clientId:e,clientSecret:t,tenant:r});}catch(o){let s=h(o instanceof Error?o.message:"unknown error");return ut.error(`[${r}] Authentication failed: ${s}`),process.stderr.write(R.red(` \u2717 Authentication failed: ${s}
163
+ `)),1}let n=await Wd();return await Jd({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug},!0),await zd(n),await Xd(),ut.info(`[${r}] Authentication successful`),process.stdout.write(R.green(`
164
+ \u2713 Setup complete. Tenant: ${r}. JWT written to ${mr()}.
165
165
 
166
- `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=f(e instanceof Error?e.message:"unknown error");return at.error(`[auth] Unexpected error: ${t}`),process.stderr.write(M.red(` \u2717 Unexpected error: ${t}
167
- `)),1}}async function ra(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return Th({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await kh()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
168
- `),130;throw t}}async function Ah(){try{return process.stdout.write(`
169
- `),(await br(M.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(M.yellow(` \u26A0 Logout cancelled
166
+ `)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=h(e instanceof Error?e.message:"unknown error");return ut.error(`[auth] Unexpected error: ${t}`),process.stderr.write(R.red(` \u2717 Unexpected error: ${t}
167
+ `)),1}}async function ba(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return xS({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await IS()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
168
+ `),130;throw t}}async function vS(){try{return process.stdout.write(`
169
+ `),(await Tr(R.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(R.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 xd(e){if(!await te())return process.stdout.write(M.yellow(` \u26A0 You are not authenticated
172
- `)),0;if(!e){let t=await Ah();if(t!==null)return t}try{return await Ma(),process.stdout.write(M.green(` \u2713 Credentials removed successfully
173
- `)),0}catch{return process.stderr.write(M.red(` \u2717 Error removing credentials
174
- `)),1}}async function Id(){let e=await te();return e?await Ft()?(process.stdout.write(`
175
- `+M.bold(` Authenticated
176
- `)),process.stdout.write(M.dim(" Tenant: ")+f(e.tenant)+`
177
- `),process.stdout.write(M.dim(" Client ID: ")+f(e.clientId)+`
178
- `),process.stdout.write(M.dim(" Starter Kit: ")+f(e.starterKit??"not set")+`
179
- `),process.stdout.write(M.dim(" Config: ")+f(await $a())+`
171
+ `),130;throw e}}async function qd(e){if(!await ne())return process.stdout.write(R.yellow(` \u26A0 You are not authenticated
172
+ `)),0;if(!e){let t=await vS();if(t!==null)return t}try{return await Ya(),process.stdout.write(R.green(` \u2713 Credentials removed successfully
173
+ `)),0}catch{return process.stderr.write(R.red(` \u2717 Error removing credentials
174
+ `)),1}}async function Yd(){let e=await ne();return e?await Vt()?(process.stdout.write(`
175
+ `+R.bold(` Authenticated
176
+ `)),process.stdout.write(R.dim(" Tenant: ")+h(e.tenant)+`
177
+ `),process.stdout.write(R.dim(" Client ID: ")+h(e.clientId)+`
178
+ `),process.stdout.write(R.dim(" Starter Kit: ")+h(e.starterKit??"not set")+`
179
+ `),process.stdout.write(R.dim(" Config: ")+h(await Za())+`
180
180
  `),process.stdout.write(`
181
- `),0):(process.stdout.write(M.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(M.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function Mh(e){let t=re(),r;try{r=await Ht();}catch{r=[];}let n=new Set(t.map(o=>o.name));return E(P.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?($r(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Mr(["","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 $h(e){let t=re(),r=await Ht(),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&&Pe(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return E(P.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(C("All plugins are up to date."),0):e.json?($r(o),0):(Mr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
181
+ `),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function bS(e){let t=se(),r;try{r=await zt();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(v.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(_r(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Rr(["","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 ES(e){let t=se(),r=await zt(),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&&Te(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return b(v.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(T("All plugins are up to date."),0):e.json?(_r(o),0):(Rr(["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 Lh(e){let t=re();if(E(P.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return C("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return $r(t),0;let r=[];try{r=await Ht();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=$n.indexOf(s.scope??"user"),l=$n.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return Mr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"plugin",l=i?.origin??Li(s.marketplace);return [s.name??"",s.version??"n/a",Cr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",Ot(s.installedAt??"")]})),process.stdout.write(`
183
+ `),0)}async function PS(e){let t=se();if(b(v.CLI_CATALOG_VIEWED,{interface:H().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return T("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return _r(t),0;let r=[];try{r=await zt();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=Jn.indexOf(s.scope??"user"),l=Jn.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return Rr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??Zi(s.marketplace);return [s.name??"",s.version??"n/a",Ar[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",Ft(s.installedAt??"")]})),process.stdout.write(`
184
184
  ${t.length} plugin(s) installed.
185
- `),0}async function vd(e){if(!await he())return 1;try{return e.available?await Mh(e):e.outdated?await $h(e):await Lh(e)}catch(t){return T(t instanceof Error?t.message:"Failed to list plugins."),1}}var se=x("manage");function ps(e,t){return t?re().find(r=>r.name===e&&r.scope===t):re().find(r=>r.name===e)}function Rh(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,C(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=na({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function _h(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=f(e),a=f(Fr(e,r.scope));if(!await Wt(`${t}Install external plugin "${i}"?
185
+ `),0}async function Zd(e){if(!await ge())return 1;try{return e.available?await bS(e):e.outdated?await ES(e):await PS(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}var le=x("manage");function $s(e,t){return t?se().find(r=>r.name===e&&r.scope===t):se().find(r=>r.name===e)}function TS(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,T(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Ea({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function CS(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=h(e),a=h(Kr(e,r.scope));if(!await gt(`${t}Install external plugin "${i}"?
186
186
  This will run: ${a}
187
- [y/N] `))return se.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=na({text:`${t}Installing ${e}...`}).start());}let s=o?Rh(t,o):void 0;try{let i=await qc(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ke({status:"error",plugin:e,message:a}):T(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Me({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):ie(`${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?Ke({status:"error",plugin:e,message:a}):T(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function Dh(e,t,r){let n=r.silent?void 0:na({text:`${t}Installing ${e}...`}).start();if(Nr(e))return _h(e,t,r,n);try{let o=await ve(e,r);return n?.stop(),r.silent?Me({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):ie(`${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 Re)return r.silent?Me({status:"already_installed",plugin:e,message:o.message}):C(`${t}${o.message}`),{name:e,success:true};let s=q(o);return r.silent?Ke({status:"error",plugin:e,message:s}):T(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function Oh(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;C(`
188
- Installation summary: ${t} succeeded, ${r} failed`);}async function ms(e,t={}){if(!await he())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await Dh(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?Me({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}:{}}))}):Oh(r)),r.some(n=>!n.success)?1:0}async function bd(e,t){if(!await he())return 1;if(se.debug(`[${e}] Looking up installed plugin`),!t.force){let r=ps(e,t.scope);if(!r)return se.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;let n=f(r.name),o=r.version?f(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await Wt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return se.debug(`[${e}] Uninstall cancelled by user`),C("Operation cancelled."),0}try{return se.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await ko(e,t.scope),se.info(`[${e}] Uninstalled successfully`),ie("Plugin removed successfully"),0}catch(r){return se.error(`[${e}] Failed to uninstall: ${q(r)}`),T(q(r)),1}}async function Pd(e,t={}){if(!await he())return 1;se.debug(`[${e}] Looking up installed plugin`);let r=ps(e,t.scope);if(!r)return se.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return se.debug(`[${e}] Already enabled, skipping`),C(`${r.name} is already enabled`),0;try{return se.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await bn(e,"enabled",t.scope),se.info(`[${e}] Enabled successfully`),ie(`${r.name} enabled successfully`),0}catch(n){return se.error(`[${e}] Failed to enable: ${q(n)}`),T(q(n)),1}}async function Ed(e,t={}){if(!await he())return 1;se.debug(`[${e}] Looking up installed plugin`);let r=ps(e,t.scope);if(!r)return se.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return se.debug(`[${e}] Already disabled, skipping`),C(`${r.name} is already disabled`),0;try{return se.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await bn(e,"disabled",t.scope),se.info(`[${e}] Disabled successfully`),ie(`${r.name} disabled successfully`),0}catch(n){return se.error(`[${e}] Failed to disable: ${q(n)}`),T(q(n)),1}}async function Cd(e,t,r){r.silent||C(`${t}Updating ${e}...`);try{let n=await Jo(e,r);return r.silent?Me({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):ie(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Kt)return r.silent?Me({status:"up_to_date",plugin:e,message:n.message}):C(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=q(n);return r.silent?Ke({status:"error",plugin:e,message:o}):T(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Nh(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;C(`
189
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function Uh(e,t,r){try{let n=await jr(e);Pe(t,n.version,r.force)?C(`Would update ${e}: v${t} \u2192 v${n.version}`):C(`${e} is already up to date (v${t})`);}catch(n){return T(q(n)),1}return 0}function Fh(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Bh(e,t,r){let n=t.get(e.name);return n?e.version&&Pe(e.version,n,r)?(C(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(C(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(C(`Skipping ${e.name}: not found in catalog`),false)}async function jh(e,t){try{let r=await Ht(),n=Fh(r),o=0;for(let s of e)Bh(s,n,t.force)&&o++;o===0&&C("All plugins are up to date");}catch(r){return T(q(r)),1}return 0}async function Kh(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Cd(e[n].name,o,t);r.push(s);}return t.silent?Me({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}:{}}))}):Nh(r),r.some(n=>!n.success)?1:0}async function Td(e,t={}){if(!await he())return 1;if(e){let o=ps(e,t.scope);return o?t.dryRun?Uh(e,o.version??"",t):(await Cd(e,"",t)).success?0:1:(t.silent?Ke({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):T(`Plugin "${e}" is not installed`),1)}let n=re().filter(o=>o.marketplace===ee);return n.length===0?(t.silent?Me({status:"empty",message:"No plugins installed"}):C("No plugins installed"),0):t.dryRun?jh(n,t):Kh(n,t)}var kd=x("marketplace");function Hh(e){return `claude plugin marketplace add ${e}`}async function Ad(e,t){if(!await he())return 1;let r;try{r=Po(e);}catch(s){let i=q(s);return t.silent?Ke({status:"error",source:e,message:i}):T(i),1}kd.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Hh(r);if(!t.force){let s=f(r),i=f(n);if(!await Wt(`Add marketplace "${s}"?
187
+ [y/N] `))return le.debug(`[${e}] Installation cancelled by user`),r.silent||T(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Ea({text:`${t}Installing ${e}...`}).start());}let s=o?TS(t,o):void 0;try{let i=await Eu(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Je({status:"error",plugin:e,message:a}):E(`${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}):re(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=Z(i);return r.silent?Je({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function kS(e,t,r){let n=r.silent?void 0:Ea({text:`${t}Installing ${e}...`}).start();if(Fr(e))return CS(e,t,r,n);try{let o=await Ee(e,r);return n?.stop(),r.silent?_e({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):re(`${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 Ne)return r.silent?_e({status:"already_installed",plugin:e,message:o.message}):T(`${t}${o.message}`),{name:e,success:true};let s=Z(o);return r.silent?Je({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function AS(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;T(`
188
+ Installation summary: ${t} succeeded, ${r} failed`);}async function Ms(e,t={}){if(!await ge())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await kS(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}:{}}))}):AS(r)),r.some(n=>!n.success)?1:0}async function Qd(e,t){if(!await ge())return 1;if(le.debug(`[${e}] Looking up installed plugin`),!t.force){let r=$s(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;let n=h(r.name),o=r.version?h(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await gt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return le.debug(`[${e}] Uninstall cancelled by user`),T("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`),re("Plugin removed successfully"),0}catch(r){return le.error(`[${e}] Failed to uninstall: ${Z(r)}`),E(Z(r)),1}}async function ep(e,t={}){if(!await ge())return 1;le.debug(`[${e}] Looking up installed plugin`);let r=$s(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return le.debug(`[${e}] Already enabled, skipping`),T(`${r.name} is already enabled`),0;try{return le.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Rn(e,"enabled",t.scope),le.info(`[${e}] Enabled successfully`),re(`${r.name} enabled successfully`),0}catch(n){return le.error(`[${e}] Failed to enable: ${Z(n)}`),E(Z(n)),1}}async function tp(e,t={}){if(!await ge())return 1;le.debug(`[${e}] Looking up installed plugin`);let r=$s(e,t.scope);if(!r)return le.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return le.debug(`[${e}] Already disabled, skipping`),T(`${r.name} is already disabled`),0;try{return le.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Rn(e,"disabled",t.scope),le.info(`[${e}] Disabled successfully`),re(`${r.name} disabled successfully`),0}catch(n){return le.error(`[${e}] Failed to disable: ${Z(n)}`),E(Z(n)),1}}async function rp(e,t,r){r.silent||T(`${t}Updating ${e}...`);try{let n=await as(e,r);return r.silent?_e({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):re(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Wt)return r.silent?_e({status:"up_to_date",plugin:e,message:n.message}):T(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=Z(n);return r.silent?Je({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function $S(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;T(`
189
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function MS(e,t,r){try{let n=await Hr(e);Te(t,n.version,r.force)?T(`Would update ${e}: v${t} \u2192 v${n.version}`):T(`${e} is already up to date (v${t})`);}catch(n){return E(Z(n)),1}return 0}function LS(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function RS(e,t,r){let n=t.get(e.name);return n?e.version&&Te(e.version,n,r)?(T(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(T(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(T(`Skipping ${e.name}: not found in catalog`),false)}async function _S(e,t){try{let r=await zt(),n=LS(r),o=0;for(let s of e)RS(s,n,t.force)&&o++;o===0&&T("All plugins are up to date");}catch(r){return E(Z(r)),1}return 0}async function DS(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await rp(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}:{}}))}):$S(r),r.some(n=>!n.success)?1:0}async function np(e,t={}){if(!await ge())return 1;if(e){let o=$s(e,t.scope);return o?t.dryRun?MS(e,o.version??"",t):(await rp(e,"",t)).success?0:1:(t.silent?Je({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=se().filter(o=>o.marketplace===te);return n.length===0?(t.silent?_e({status:"empty",message:"No plugins installed"}):T("No plugins installed"),0):t.dryRun?_S(n,t):DS(n,t)}var Yn=x("cli:bundle");function OS(e){let t=h(e.name??e.flowId),r=h(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function NS(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
190
+ Bundle: ${h(e)} (${t.length} artifacts)
191
+ `);for(let o of t)process.stdout.write(`${OS(o)}
192
+ `);process.stdout.write(`
193
+ ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
194
+
195
+ `);}async function op(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await ge())return 1;Yn.debug(`Fetching bundle "${e}"`);let r;try{r=await ps(e);}catch(a){return a instanceof en||a instanceof Hn?(E(a.message),1):(E(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(Yn.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),NS(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await gt(`Install ${o.length} artifact(s)? [Y/n] `))return Yn.debug("Installation cancelled by user"),0;Yn.debug(`Starting installation of ${o.length} artifact(s)`);let i=await ts(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let p=h(u.name??u.flowId),f=h(u.type??"unknown"),m=c?"\u2713":`\u2717 (${h(d??"failed")})`;a===1&&process.stdout.write(`
196
+ `),process.stdout.write(`[${a}/${l}] Installing ${p} (${f})... ${m}
197
+ `),a===l&&process.stdout.write(`
198
+ `);}});if(Yn.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&re(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${h(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>h(l.name??l.flowId)).join(", ");T(`${i.skipped} unavailable: ${a}`);}return 0}var sp=x("marketplace");function US(e){return `claude plugin marketplace add ${e}`}async function ip(e,t){if(!await ge())return 1;let r;try{r=Bo(e);}catch(s){let i=Z(s);return t.silent?Je({status:"error",source:e,message:i}):E(i),1}sp.debug(`[marketplace] Adding marketplace source: ${r}`);let n=US(r);if(!t.force){let s=h(r),i=h(n);if(!await gt(`Add marketplace "${s}"?
190
199
  This will run: ${i}
191
- [y/N] `))return kd.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:na({text:`Adding marketplace "${f(r)}"...`}).start();try{let s=await Se(n);return o?.stop(),s.exitCode!==0?(t.silent?Ke({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(T(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&C(`stdout: ${s.stdout}`)),1):(t.silent?Me({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(ie(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&C(s.stdout)),0)}catch(s){o?.stop();let i=q(s);return t.silent?Ke({status:"error",source:r,message:i}):T(`Failed to add marketplace "${r}": ${i}`),1}}async function zh(){return await te()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Xh(){let e=Date.now();try{await Ht();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 qh(){return await Ft()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Yh(){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 Md(){process.stdout.write(`
192
- `+M.bold(` FlowSetup CLI Diagnostics
200
+ [y/N] `))return sp.debug("[marketplace] Operation cancelled by user"),T("Operation cancelled."),0}let o=t.silent?void 0:Ea({text:`Adding marketplace "${h(r)}"...`}).start();try{let s=await xe(n);return o?.stop(),s.exitCode!==0?(t.silent?Je({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&T(`stdout: ${s.stdout}`)),1):(t.silent?_e({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(re(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&T(s.stdout)),0)}catch(s){o?.stop();let i=Z(s);return t.silent?Je({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}async function VS(){return await ne()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function HS(){let e=Date.now();try{await zt();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 JS(){return await Vt()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function GS(){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 ap(){process.stdout.write(`
201
+ `+R.bold(` FlowSetup CLI Diagnostics
193
202
 
194
- `));let e=[{name:"Credentials",fn:zh},{name:"Prompt Manager",fn:Xh},{name:"Valid Token",fn:qh},{name:"Claude Code",fn:Yh}],t=true;for(let r of e){let n=await r.fn(),o="",s=M.green;n.passed?o=M.green("[OK] "):(o=M.red("[FAIL]"),s=M.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${f(n.message)}`;process.stdout.write(i+`
203
+ `));let e=[{name:"Credentials",fn:VS},{name:"Prompt Manager",fn:HS},{name:"Valid Token",fn:JS},{name:"Claude Code",fn:GS}],t=true;for(let r of e){let n=await r.fn(),o="",s=R.green;n.passed?o=R.green("[OK] "):(o=R.red("[FAIL]"),s=R.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${h(n.message)}`;process.stdout.write(i+`
195
204
  `);}return process.stdout.write(`
196
- `),t?(process.stdout.write(M.green(` \u2713 All checks passed!
205
+ `),t?(process.stdout.write(R.green(` \u2713 All checks passed!
197
206
 
198
- `)),0):(process.stdout.write(M.red(` \u2717 Some checks failed \u2014 verify your configuration
207
+ `)),0):(process.stdout.write(R.red(` \u2717 Some checks failed \u2014 verify your configuration
199
208
 
200
- `)),1)}var eS=["github.com","www.github.com"],tS=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,rS=/^([^@]+)@(.+)$/;function nS(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function oa(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 oS(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=oa(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=oa(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(nS(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:")&&eS.includes(r.hostname))return oS(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(tS);if(s){let i=s[1],a=s[2],l=s[3],c,u=a.match(rS);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=oa(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 ia=new Set(["node_modules",".git","dist","build","__pycache__"]);function Qr(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function _d(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function cS(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function sa(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 Dd(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([sa(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!ia.has(a.name)).map(a=>Dd(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&&!cS(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await sa(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 sa(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 Dd(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 Od(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 Fd=1,gS={retries:5,minTimeout:50};async function Bd(e,t){mkdirSync(dirname(e),{recursive:true});let r=await wf.lock(e+".lock",{realpath:false,retries:gS});try{return await t()}finally{await r();}}function Nd(){return {version:Fd,skills:{}}}async function ws(e){let t=an(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Fd?Nd():n}catch{return Nd()}}function yS(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function jd(e,t){let r=an(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:yS(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
201
- `,"utf-8");}async function Kd(e,t,r){let n=an(r);await Bd(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 jd(o,r);});}async function Vd(e,t){let r=an(t);await Bd(r,async()=>{let n=await ws(t);e in n.skills&&(delete n.skills[e],await jd(n,t));});}var Hd=x("skillInstaller");async function bS(e,t,r,n){try{await E(P.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:H().interfaceType});}catch(o){Hd.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function PS(e,t){try{await E(P.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:H().interfaceType});}catch(r){Hd.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function ES(e,t){await cp(e,t,{recursive:true,dereference:true,filter:r=>!ia.has(basename(r))});}async function CS(e,t,r){let n=Qr(e.name),o=sr(t),s=join(o,n);if(!_d(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 ES(e.path,s);let a=gs(r)??r.url;return await Kd(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 Jd(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 Xt(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?Od(s,i):s,l=[],c=r.ref??"latest";for(let u of a){let d=Date.now(),m=await CS(u,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await bS(u.name,t.scope,c,p):await PS(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 qt(n).catch(()=>{});}}var $S=x("skills");async function LS(e){try{await E(P.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:H().interfaceType});}catch(t){$S.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function RS(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${f(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function _S(e){let t=fs(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return T("Invalid local path."),1;n=t.localPath;}else C(`Fetching skills from ${f(e)}...`),r=await Xt(t.url,t.ref),n=r;let o=await Ss(n,t.subpath);if(o.length===0)return C("No skills found in this source."),0;let i=gs(t)??f(e);C(`Found ${o.length} skill(s) in ${i}:
202
- `);for(let a of o){let l=f(a.name),c=f(a.description);process.stdout.write(` ${M.bold(l)} ${M.dim(c)}
209
+ `)),1)}var XS=["github.com","www.github.com"],qS=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,YS=/^([^@]+)@(.+)$/;function ZS(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Pa(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 QS(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=Pa(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Pa(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Ls(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(ZS(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:")&&XS.includes(r.hostname))return QS(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(qS);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(YS);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let p=l.replace(/^\//,"");p&&(d.subpath=Pa(p));}return d}}return {type:"git",url:t}}function Rs(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 lp(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 cn(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed-skill"}function dp(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function ow(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Ta(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Zn(e){try{let t=await readFile(e,"utf-8"),{data:r}=lp(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 pp(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Ta(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Ca.has(a.name)).map(a=>pp(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Os(e,t){let r=[],n=new Set;if(t&&!ow(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Ta(o)){let i=await Zn(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let u=join(i,l.name);if(await Ta(u)){let c=await Zn(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await pp(o);for(let a of i){let l=await Zn(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function mp(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 yp=1,uw={retries:5,minTimeout:50};async function hp(e,t){mkdirSync(dirname(e),{recursive:true});let r=await eg.lock(e+".lock",{realpath:false,retries:uw});try{return await t()}finally{await r();}}function fp(){return {version:yp,skills:{}}}async function Ns(e){let t=hn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<yp?fp():n}catch{return fp()}}function dw(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Sp(e,t){let r=hn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:dw(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
210
+ `,"utf-8");}async function wp(e,t,r){let n=hn(r);await hp(n,async()=>{let o=await Ns(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Sp(o,r);});}async function xp(e,t){let r=hn(t);await hp(r,async()=>{let n=await Ns(t);e in n.skills&&(delete n.skills[e],await Sp(n,t));});}var Ip=x("skillInstaller");async function Sw(e,t,r,n){try{await b(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:H().interfaceType});}catch(o){Ip.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function ww(e,t){try{await b(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:H().interfaceType});}catch(r){Ip.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function xw(e,t){await cp(e,t,{recursive:true,dereference:true,filter:r=>!Ca.has(basename(r))});}async function Iw(e,t,r){let n=cn(e.name),o=ar(t),s=join(o,n);if(!dp(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 xw(e.path,s);let a=Rs(r)??r.url;return await wp(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 vp(e,t){let r=Ls(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 Zt(r.url,r.ref),o=n;let s=await Os(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?mp(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),p=await Iw(c,t.scope,r);l.push(p);let f=Date.now()-d;p.success?await Sw(c.name,t.scope,u,f):await ww(c.name,new Error(p.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await Qt(n).catch(()=>{});}}var Tw=x("skills");async function Cw(e){try{await b(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:H().interfaceType});}catch(t){Tw.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function kw(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${h(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function Aw(e){let t=Ls(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else T(`Fetching skills from ${h(e)}...`),r=await Zt(t.url,t.ref),n=r;let o=await Os(n,t.subpath);if(o.length===0)return T("No skills found in this source."),0;let i=Rs(t)??h(e);T(`Found ${o.length} skill(s) in ${i}:
211
+ `);for(let a of o){let l=h(a.name),u=h(a.description);process.stdout.write(` ${R.bold(l)} ${R.dim(u)}
203
212
  `);}return process.stdout.write(`
204
- `),0}catch(n){return n instanceof zt?T(n.message):T(n instanceof Error?n.message:String(n)),1}finally{r&&await qt(r).catch(()=>{});}}function DS(e){for(let r of e.results){let n=f(r.skill);if(r.success){let o=relative(process.cwd(),r.path);ie(`${n} installed ${M.dim(`\u2192 ${o}/`)}`);}else T(`${n}: ${f(r.error??"unknown error")}`);}process.stdout.write(`
205
- `);let t=e.source;e.installed>0&&C(`Installed ${e.installed} of ${e.discovered} skill(s) from ${f(t)}`),e.failed>0&&T(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?C("No skills found in this source."):e.results.length===0&&e.discovered>0&&C(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Wd(e,t){if(t.list)return _S(e);let r=t.global?"global":"project";try{let n=await Jd(e,{scope:r,skillFilter:t.skill,yes:t.yes});return DS(n),n.failed>0?1:0}catch(n){return n instanceof zt?T(n.message):T(n instanceof Error?n.message:String(n)),1}}async function zd(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 Xd(e){let t=e.global?"global":"project",r=await zd(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[Qr(i.name)]?.source}));return $r(s),0}if(r.length===0)return C(`No skills installed (${t==="global"?"global":"project"} scope).`),0;C(`${t==="global"?"Global":"Project"} skills (${r.length}):
206
- `);for(let s of r){let i=n.skills[Qr(s.name)]?.source,a=f(s.name),l=f(s.description),c=l.length>80?l.slice(0,77)+"...":l,u=i?M.dim(` (${i})`):"";process.stdout.write(` ${M.bold(a)}${u}
207
- `),process.stdout.write(` ${M.dim(c)}
213
+ `),0}catch(n){return n instanceof Yt?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await Qt(r).catch(()=>{});}}function $w(e){for(let r of e.results){let n=h(r.skill);if(r.success){let o=relative(process.cwd(),r.path);re(`${n} installed ${R.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${h(r.error??"unknown error")}`);}process.stdout.write(`
214
+ `);let t=e.source;e.installed>0&&T(`Installed ${e.installed} of ${e.discovered} skill(s) from ${h(t)}`),e.failed>0&&E(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?T("No skills found in this source."):e.results.length===0&&e.discovered>0&&T(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Ep(e,t){if(t.list)return Aw(e);let r=t.global?"global":"project";try{let n=await vp(e,{scope:r,skillFilter:t.skill,yes:t.yes});return $w(n),n.failed>0?1:0}catch(n){return n instanceof Yt?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function Pp(e){let t=ar(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 Zn(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 Tp(e){let t=e.global?"global":"project",r=await Pp(t),n=await Ns(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[cn(i.name)]?.source}));return _r(s),0}if(r.length===0)return T(`No skills installed (${t==="global"?"global":"project"} scope).`),0;T(`${t==="global"?"Global":"Project"} skills (${r.length}):
215
+ `);for(let s of r){let i=n.skills[cn(s.name)]?.source,a=h(s.name),l=h(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?R.dim(` (${i})`):"";process.stdout.write(` ${R.bold(a)}${c}
216
+ `),process.stdout.write(` ${R.dim(u)}
208
217
 
209
- `);}return 0}async function qd(e,t){let r=t.global?"global":"project";if(!e){let i=await zd(r);if(i.length===0)return C("No skills installed."),0;C("Installed skills:");for(let a of i)process.stdout.write(` - ${f(a.name)}
218
+ `);}return 0}async function Cp(e,t){let r=t.global?"global":"project";if(!e){let i=await Pp(r);if(i.length===0)return T("No skills installed."),0;T("Installed skills:");for(let a of i)process.stdout.write(` - ${h(a.name)}
210
219
  `);return process.stdout.write(`
211
- `),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=Qr(e),o=sr(r),s=join(o,n);try{await stat(s);}catch{return T(`Skill "${f(e)}" is not installed.`),1}if(!t.force&&!await RS(`Remove skill "${f(n)}"?`))return C("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Vd(n,r),await LS(n),ie(`Skill "${f(n)}" removed.`),0}catch(i){return T(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var xs=x("transfer"),la=1;function OS(e){return e.marketplace&&e.marketplace!==ee?`${e.name}@${e.marketplace}`:e.name}function NS(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&C(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),C(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Qd(e){let t=de__default.resolve(e.output);try{let r=re(),n={version:la,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 xe__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),ie(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=q(r);return xs.error(`Export failed: ${n}`),T(`Failed to export plugins: ${n}`),1}}async function ep(e,t={}){if(!await he())return 1;let r;try{let a=xe__default.readFileSync(de__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return T(`Failed to read import file "${e}": ${q(a)}`),1}if(r.version!==la)return T(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${la}`),1;if(!Array.isArray(r.plugins))return T('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return C("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&&C(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(re().map(l=>l.name));NS(n,a);}if(t.dryRun)return C("Dry-run mode: no plugins were installed"),0;if(n.length===0){C(`
212
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)T(` ${a.name}: ${a.error}`);return o.length>0?1:0}C(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=OS(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"});}C(`
213
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)T(` ${a.name}: ${a.error}`);return o.length>0?1:0}function N(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var FS=x("moduleProxy");function BS(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=wi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(f(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function tp(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await E(P.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{FS.warn(`Failed to emit proxy executed event: ${String(s)}`);}),N(o);}async function np(e,t){let r=Z.find(o=>o.alias===e);if(!r){T(`Unknown module alias: '${e}'`),N(1);return}if(!await St(r.binaryName)){T(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await E(P.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),N(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await _t(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){T(`No supported installation method available for '${e}' on this platform.`),N(1);return}if(await BS("Would you like to install it now? [Y/n] ")){await E(P.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await qr(r,"inline",s);if(!a.success){T(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),N(1);return}await tp(r,t);}else C(`To install manually, run: flow modules install ${e}`),await E(P.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),N(1);return}await tp(r,t);}var HS=promisify(execFile);async function JS(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await HS(Rt(),["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/${oe}`,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 GS(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Pe(t,r)?"outdated":"installed"}async function ca(){let e=await Promise.all(Z.map(async t=>{let[r,n]=await Promise.all([St(t.binaryName),JS(t)]),s=Ye(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=GS(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Mr(["Name","Alias","Version","Status","Platform"],e),0}async function ip(e){let t=Z.find(i=>i.alias===e);if(!t)return T(`Unknown module alias: '${e}'`),1;let[r]=await Yr([t]);if(r.alreadyInstalled){let i=Ye(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return C(`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"?T(`Module ${t.name} is not supported on ${process.platform}.${a}`):T(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=na({text:`Installing ${t.name}...`}).start(),s;try{s=await qr(t,"on_demand",n);}finally{o.stop();}return s.success?(ie(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(T(s.error?.message??"Installation failed"),1)}async function op(e,t){let r=na({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 ap(e){if(e!==null){let n=Z.find(i=>i.alias===e);if(!n)return T(`Unknown module alias: '${e}'`),1;let o=Ye(n.alias);return o?.installMethod?await op(n,o.installedVersion??"unknown")==="error"?1:0:(T(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=vr().filter(n=>n.installMethod!==null);if(t.length===0)return C("No installed modules to update."),0;let r=0;for(let n of t){let o=Z.find(i=>i.alias===n.alias);if(!o)continue;await op(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function lp(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${oe}`,"-V, --version","Display the CLI version").addHelpText("after",`
220
+ `),T("Specify a skill name to remove: flow skills remove <name>"),1}let n=cn(e),o=ar(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${h(e)}" is not installed.`),1}if(!t.force&&!await kw(`Remove skill "${h(n)}"?`))return T("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await xp(n,r),await Cw(n),re(`Skill "${h(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var Bs=x("transfer"),Aa=1;function Mw(e){return e.marketplace&&e.marketplace!==te?`${e.name}@${e.marketplace}`:e.name}function Lw(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&T(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),T(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function $p(e){let t=fe__default.resolve(e.output);try{let r=se(),n={version:Aa,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return ve__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),re(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=Z(r);return Bs.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function Mp(e,t={}){if(!await ge())return 1;let r;try{let a=ve__default.readFileSync(fe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${Z(a)}`),1}if(r.version!==Aa)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Aa}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return T("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;Bs.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Bs.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&T(`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));Lw(n,a);}if(t.dryRun)return T("Dry-run mode: no plugins were installed"),0;if(n.length===0){T(`
221
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}T(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=Mw(a);Bs.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await Ms([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}T(`
222
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function B(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var _w=x("moduleProxy");function Dw(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Bi.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(h(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Lp(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await b(v.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{_w.warn(`Failed to emit proxy executed event: ${String(s)}`);}),B(o);}async function _p(e,t){let r=ee.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),B(1);return}if(!await xt(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await b(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),B(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Nt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),B(1);return}if(await Dw("Would you like to install it now? [Y/n] ")){await b(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await sn(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),B(1);return}await Lp(r,t);}else T(`To install manually, run: flow modules install ${e}`),await b(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),B(1);return}await Lp(r,t);}var Uw=promisify(execFile);async function Fw(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await Uw(Ot(),["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 jw(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Te(t,r)?"outdated":"installed"}async function $a(){let e=await Promise.all(ee.map(async t=>{let[r,n]=await Promise.all([xt(t.binaryName),Fw(t)]),s=et(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=jw(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Rr(["Name","Alias","Version","Status","Platform"],e),0}async function Np(e){let t=ee.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await an([t]);if(r.alreadyInstalled){let i=et(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return T(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Ea({text:`Installing ${t.name}...`}).start(),s;try{s=await sn(t,"on_demand",n);}finally{o.stop();}return s.success?(re(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function Dp(e,t){let r=Ea({text:`Updating ${e.name}...`}).start(),n;try{n=await Ps(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 Bp(e){if(e!==null){let n=ee.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=et(n.alias);return o?.installMethod?await Dp(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Pr().filter(n=>n.installMethod!==null);if(t.length===0)return T("No installed modules to update."),0;let r=0;for(let n of t){let o=ee.find(i=>i.alias===n.alias);if(!o)continue;await Dp(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function Up(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
223
  Without arguments, opens the interactive interface (TUI).
215
224
  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
225
  Examples:
217
- $ flow setup init`).action(async()=>{let c=await ra();N(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",`
226
+ $ flow setup init`).action(async()=>{let c=await ba();B(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
227
  Examples:
219
228
  $ flow plugin list
220
229
  $ flow plugin list --available
221
230
  $ flow plugin list --outdated
222
- $ flow plugin list --json`).action(async c=>{let u=await vd(c);N(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",`
231
+ $ flow plugin list --json`).action(async c=>{let d=await Zd(c);B(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
223
232
  Examples:
224
233
  $ flow plugin install flow-adr-writer
225
234
  $ flow plugin install flow-adr-writer --scope project
@@ -227,11 +236,11 @@ Examples:
227
236
  $ flow plugin install flow-adr-writer --force
228
237
  $ flow plugin install flow-adr-writer --silent
229
238
  $ flow plugin install superpowers@claude-plugins-official
230
- $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(c,u)=>{let d=c.filter(p=>p.trim());if(d.length===0){T("No valid plugin names provided"),N(1);return}je("cli",{verbose:u.verbose,silent:u.silent});let m=await ms(d,u);N(m);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
239
+ $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(c,d)=>{let p=c.filter(m=>m.trim());if(p.length===0){E("No valid plugin names provided"),B(1);return}Re("cli",{verbose:d.verbose,silent:d.silent});let f=await Ms(p,d);B(f);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
231
240
  Examples:
232
241
  $ flow plugin uninstall flow-adr-writer
233
242
  $ flow plugin uninstall flow-adr-writer --scope project
234
- $ flow plugin uninstall startup-pack-ai --force`).action(async(c,u)=>{let d=await bd(c,u);N(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",`
243
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let p=await Qd(c,d);B(p);}),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
244
  Examples:
236
245
  $ flow plugin update flow-adr-writer
237
246
  $ flow plugin update flow-adr-writer --scope project
@@ -240,70 +249,74 @@ Examples:
240
249
  $ flow plugin update flow-adr-writer --verbose
241
250
  $ flow plugin update flow-adr-writer --silent
242
251
  $ flow plugin update
243
- $ flow plugin update --dry-run`).action(async(c,u)=>{je("cli",{verbose:u.verbose,silent:u.silent});let d=await Td(c??null,u);N(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",`
252
+ $ flow plugin update --dry-run`).action(async(c,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let p=await np(c??null,d);B(p);}),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
253
  Examples:
245
254
  $ flow plugin enable flow-adr-writer
246
- $ flow plugin enable flow-adr-writer --scope project`).action(async(c,u)=>{je("cli");let d=await Pd(c,u);N(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",`
255
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Re("cli");let p=await ep(c,d);B(p);}),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
256
  Examples:
248
257
  $ flow plugin disable flow-adr-writer
249
- $ flow plugin disable flow-adr-writer --scope project`).action(async(c,u)=>{je("cli");let d=await Ed(c,u);N(d);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
258
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Re("cli");let p=await tp(c,d);B(p);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
250
259
  Examples:
251
260
  $ flow plugin export
252
- $ flow plugin export --output my-plugins.json`).action(async c=>{let u=await Qd(c);N(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",`
261
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await $p(c);B(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
253
262
  Examples:
254
263
  $ flow plugin import flow-plugins.json
255
264
  $ flow plugin import flow-plugins.json --scope user
256
265
  $ flow plugin import flow-plugins.json --force
257
266
  $ flow plugin import flow-plugins.json --dry-run
258
- $ flow plugin import flow-plugins.json --diff`).action(async(c,u)=>{let d=await ep(c,u);N(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",`
267
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let p=await Mp(c,d);B(p);});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
268
  Examples:
260
269
  $ flow plugin marketplace add anthropics/claude-code
261
270
  $ flow plugin marketplace add https://github.com/owner/repo
262
271
  $ flow plugin marketplace add anthropics/claude-code --force
263
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,u)=>{je("cli",{verbose:u.verbose,silent:u.silent});let d=await Ad(c,u);N(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",`
272
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let p=await ip(c,d);B(p);}),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
273
  Examples:
265
274
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
266
275
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
267
276
  $ 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)=>{je("cli",{verbose:d.verbose,silent:d.silent});let m=await tu(c,u,d);N(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",`
277
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,p)=>{Re("cli",{verbose:p.verbose,silent:p.silent});let f=await Au(c,d,p);B(f);}),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
278
  Examples:
270
279
  $ flow mcp remove notion
271
280
  $ flow mcp remove notion --scope project
272
- $ flow mcp remove playwright-mcp --force`).action(async(c,u)=>{je("cli",{verbose:u.verbose,silent:u.silent});let d=await ru(c,u);N(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",`
281
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let p=await $u(c,d);B(p);}),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
282
  Examples:
274
283
  $ flow auth login
275
284
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
276
285
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
277
- $ flow auth login --verbose`).action(async c=>{je("cli",{verbose:c.verbose});let u=await ra(c);N(u);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
286
+ $ flow auth login --verbose`).action(async c=>{Re("cli",{verbose:c.verbose});let d=await ba(c);B(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
278
287
  Examples:
279
288
  $ flow auth logout
280
- $ flow auth logout --force`).action(async c=>{let u=await xd(c.force);N(u);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
289
+ $ flow auth logout --force`).action(async c=>{let d=await qd(c.force);B(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
281
290
  Examples:
282
- $ flow auth status`).action(async()=>{let c=await Id();N(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
291
+ $ flow auth status`).action(async()=>{let c=await Yd();B(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
292
  Examples:
284
293
  $ flow skills add vercel-labs/agent-skills
285
294
  $ flow skills add owner/repo -g
286
295
  $ flow skills add owner/repo --skill pr-review commit
287
296
  $ flow skills add ./local/skills -y
288
- $ flow skills add owner/repo --list`).action(async(c,u)=>{let d=await Wd(c,u);N(d);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
297
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let p=await Ep(c,d);B(p);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
289
298
  Examples:
290
299
  $ flow skills list
291
300
  $ flow skills list -g
292
- $ flow skills list --json`).action(async c=>{let u=await Xd(c);N(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",`
301
+ $ flow skills list --json`).action(async c=>{let d=await Tp(c);B(d);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
293
302
  Examples:
294
303
  $ flow skills remove pr-review
295
- $ flow skills remove pr-review -g --force`).action(async(c,u)=>{let d=await qd(c,u);N(d);}),t.addCommand(a),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
304
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let p=await Cp(c,d);B(p);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
305
+ Examples:
306
+ $ flow bundle install "My React Kit"
307
+ $ flow bundle install "Squad Setup Bundle"
308
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Re("cli",{verbose:d.verbose});let p=await op(c);B(p);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
296
309
  Examples:
297
- $ flow health`).action(async()=>{let c=await Md();N(c);});let l=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");l.action(async()=>{let c=await ca();N(c);}),l.command("list").description("List available and installed modules").addHelpText("after",`
310
+ $ flow health`).action(async()=>{let c=await ap();B(c);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await $a();B(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
298
311
  Examples:
299
- $ flow modules list`).action(async()=>{let c=await ca();N(c);}),l.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
312
+ $ flow modules list`).action(async()=>{let c=await $a();B(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
300
313
  Examples:
301
314
  $ flow modules install metrics
302
- $ flow modules install dashboard`).action(async c=>{let u=await ip(c);N(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",`
315
+ $ flow modules install dashboard`).action(async c=>{let d=await Np(c);B(d);}),u.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
303
316
  Examples:
304
317
  $ flow modules update
305
- $ flow modules update metrics`).action(async c=>{let u=await ap(c??null);N(u);}),t.addCommand(l);for(let c of Z)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await np(c.alias,u);});return t.hook("preAction",()=>{ls();}),t}function XS(){return de__default.join(Ae__default.homedir(),".claude","settings.json")}function up(){let e=XS();try{if(!xe__default.existsSync(e))return !0;let r=JSON.parse(xe__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var tw=x("updateChecker"),rw=promisify(execFile),nw=1440*60*1e3,dp=3e4;function ow(){let e=process.env.FLOW_HOME??de__default.join(Ae__default.homedir(),".flow");return de__default.join(e,"update.lock")}async function pp(e){try{let{stdout:t}=await rw(Rt(),["view",e,"version"],{timeout:dp,shell:!0});return String(t).trim()||null}catch{return null}}async function sw(e){let t=new AbortController,r=setTimeout(()=>t.abort(),dp);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 iw(e){return e.versionCheck.type==="npm-registry"?pp(e.versionCheck.package):sw(e.versionCheck.repo)}async function aw(){let e=await pp("@ciandt-flow/cli");return e&&Pe(oe,e)?(us({currentVersion:oe,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function lw(){let e=vr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=Z.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<nw)return;let s=await iw(r);try{await tr({...t,lastChecked:new Date().toISOString()});}catch(i){tw.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Pe(t.installedVersion,s)&&as(r,"background").catch(()=>{});}));}async function da(){let e=up();if(e===false)return;let t=ow();xe__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=null;try{r=await wf.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await aw().catch(()=>null);n&&process.stdout.write(`
318
+ $ flow modules update metrics`).action(async c=>{let d=await Bp(c??null);B(d);}),t.addCommand(u);for(let c of ee)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await _p(c.alias,d);});return t.hook("preAction",()=>{Ts();}),t}function Hw(){return fe__default.join(Le__default.homedir(),".claude","settings.json")}function jp(){let e=Hw();try{if(!ve__default.existsSync(e))return !0;let r=JSON.parse(ve__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var qw=x("updateChecker"),Yw=promisify(execFile),Zw=1440*60*1e3,Kp=3e4;function Qw(){let e=process.env.FLOW_HOME??fe__default.join(Le__default.homedir(),".flow");return fe__default.join(e,"update.lock")}async function Vp(e){try{let{stdout:t}=await Yw(Ot(),["view",e,"version"],{timeout:Kp,shell:!0});return String(t).trim()||null}catch{return null}}async function ex(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Kp);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 tx(e){return e.versionCheck.type==="npm-registry"?Vp(e.versionCheck.package):ex(e.versionCheck.repo)}async function rx(){let e=await Vp("@ciandt-flow/cli");return e&&Te(ae,e)?(ks({currentVersion:ae,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function nx(){let e=Pr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=ee.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<Zw)return;let s=await tx(r);try{await or({...t,lastChecked:new Date().toISOString()});}catch(i){qw.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Te(t.installedVersion,s)&&Ps(r,"background").catch(()=>{});}));}async function La(){let e=jp();if(e===false)return;let t=Qw();ve__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=null;try{r=await eg.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await rx().catch(()=>null);n&&process.stdout.write(`
306
319
  \u26A0 @ciandt-flow/cli v${n} installing in background.
307
320
  Restart flow to apply the update.
308
321
 
309
- `);}await lw().catch(()=>{});}finally{await r().catch(()=>{});}}var uw=x("cli"),pa=lp(async()=>{je("tui"),Ba("tui"),ja(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=y.getState();pn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=y.getState();pn("sigterm",t,r).finally(()=>process.exit(143));}),await da().catch(()=>{}),await Jl().catch(t=>{uw.error(`Failed to init catalog registry: ${String(t)}`);}),await ud();let{waitUntilExit:e}=render(jsx(dd,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});pa.hook("preAction",async(e,t)=>{t!==pa&&await da().catch(()=>{});});pa.parse();
322
+ `);}await nx().catch(()=>{});}finally{await r().catch(()=>{});}}var sx=x("cli"),Ra=Up(async()=>{Re("tui"),al("tui"),ll(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();vn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();vn("sigterm",t,r).finally(()=>process.exit(143));}),await La().catch(()=>{}),await dc().catch(t=>{sx.error(`Failed to init catalog registry: ${String(t)}`);}),await Fd();let{waitUntilExit:e}=render(jsx(jd,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Ra.hook("preAction",async(e,t)=>{t!==Ra&&await La().catch(()=>{});});Ra.parse();