@ciandt-flow/cli 2.14.1-beta.75 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +72 -72
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import*as En from'crypto';import {randomUUID,createHash}from'crypto';import*as Se from'os';import Se__default,{tmpdir,homedir,cpus}from'os';import*as W from'path';import W__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ue from'fs';import ue__default,{readFileSync,mkdirSync,existsSync,writeFileSync,rmSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import C from'chalk';import*as Yl from'readline';import {createInterface}from'readline';import Ya from'conf';import fp,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import gS,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Cw from'jsonwebtoken';import Bw from'proper-lockfile';import lS from'ink-big-text';import Im from'ink-spinner';import*as Ht from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import yb from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import cc from'semver';import ca from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Sy=Object.defineProperty;var G=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var mu=(e,t)=>{for(var r in t)Sy(e,r,{get:t[r],enumerable:true});};var wr,Ue,Ea,Sr,So,Sn,br,Pa,fu,Ta,Xe,he,st,Zt,bs,bn,xn,In,vn,F=G(()=>{"use strict";wr="FLOW",Ue="flow-skills",Ea="flow-cli",Sr=[Ue,"flow-harness"],So="internal",Sn="external",br={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"},rule:{label:"Rule",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},Pa=new Set(Object.keys(br)),fu={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ta=new Set(["internal","external"]),Xe={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"}},he="flow-claude-md-setup",st=5,Zt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,bs="https://flow.ciandt.com",bn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,xn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",In=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,vn="Must be a valid email address (e.g. name@example.com)";});var xs,xy,gu,bo,Ca=G(()=>{"use strict";xs="aes-256-gcm",xy=16,gu=16,bo=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=En.randomBytes(xy),n=En.createCipheriv(xs,this.key,r,{authTagLength:gu}),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:xs}}decrypt(t){if(t.algorithm!==xs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=En.createDecipheriv(xs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:gu});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function ka(e){return e.replace(Py,"").replace(Ty,"").replace(Cy,"").replace(Iy,"Bearer ***").replace(vy,"***").replace(Ey,"***").replace(/\r\n|\r|\n/g,"\\n")}var Iy,vy,Ey,Py,Ty,Cy,Aa=G(()=>{"use strict";Iy=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,vy=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Ey=/[A-Za-z0-9+/]{40,}={0,2}/g,Py=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Ty=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Cy=/\x1b/g;});function vs(e){return e||Ue}function hu(e,t,r){return _a(vs(r),e,t)}function Ra(e,t){return W.join(Se.homedir(),Qt,"plugins","marketplaces",vs(t),"plugins","native",e)}function xo(e){return W.join(Se.homedir(),Qt,"plugins","marketplaces",vs(e),".claude-plugin","marketplace.json")}function Wr(){return W.join(Se.homedir(),Qt,"plugins","known_marketplaces.json")}function $a(e){return W.join(Se.homedir(),Qt,"plugins","marketplaces",vs(e))}function yu(){return W.join(Se.homedir(),Is,"cache","install.lock")}function wu(){return W.join(Se.homedir(),Is,"logs","flowsetup.log")}function _a(e,t,r){return W.join(Se.homedir(),Qt,"plugins","cache",e,t,r)}function zr(e){let t=e==="global"?Se.homedir():process.cwd();return W.join(t,".claude","skills")}function Io(e){let t=e==="global"?Se.homedir():process.cwd();return W.join(t,".claude","skills-lock.json")}function Es(e="user"){return e==="project"?W.join(process.cwd(),".opencode","plugins"):W.join(Se.homedir(),".config","opencode","plugins")}function Su(){return W.join(Se.homedir(),Is,"flow-catalogs.json")}function bu(){let e=process.env.FLOW_HOME??W.join(Se.homedir(),Is);return W.join(e,"config.json")}function Ps(e="user"){return e==="project"||e==="local"?W.join(process.cwd(),Qt,"agents"):W.join(Se.homedir(),Qt,"agents")}function Ma(e="user"){return e==="project"||e==="local"?W.join(process.cwd(),Qt,"rules"):W.join(Se.homedir(),Qt,"rules")}function xu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","skills"):W.join(Se.homedir(),".copilot","skills")}function Iu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","agents"):W.join(Se.homedir(),".copilot","agents")}function vu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","hooks"):W.join(Se.homedir(),".copilot","hooks")}function Eu(e="user"){return e==="project"?W.join(process.cwd(),".cursor","plugins"):W.join(Se.homedir(),".cursor","plugins")}var Qt,Is,$e=G(()=>{"use strict";F();Qt=".claude",Is=".flow";});var ky,Ay,Ts,Pu=G(()=>{"use strict";$e();ky=5*1024*1024,Ay=3,Ts=class{filePath;constructor(){this.filePath=wu(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{ue.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=W.dirname(this.filePath);ue.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ue.statSync(this.filePath).size>ky){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ue.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=W.dirname(this.filePath),r=W.basename(this.filePath,".log"),n=ue.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Ay))ue.unlinkSync(W.join(t,o));}catch{}}};});var Cs,Tu=G(()=>{"use strict";Cs=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 ks,Cu=G(()=>{"use strict";ks=class{write(t){process.stdout.write(t.message+`
5
- `);}};});function Da(){return As}function ku(e){return La.add(e),()=>{La.delete(e);}}var As,La,Rs,Oa=G(()=>{"use strict";As=[],La=new Set;Rs=class{write(t){As.push(t),As.length>100&&As.shift();for(let r of La)r();}};});function Ry(){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 Be(e,t){if(e==="tui"){let r=Ry();qr={context:e,transports:[new Rs,new Ts],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?qr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?qr={context:e,transports:[new Cs("cli")],minLevel:"debug",debugModules:null}:qr={context:e,transports:[new ks],minLevel:"info",debugModules:null};}function Au(){return qr.transports}function Ru(e,t){let{debugModules:r,minLevel:n}=qr;return qr.context==="tui"&&r&&r!=="all"?r.has(t)?Pn[e]>=Pn.debug:Pn[e]>=Pn.warn:Pn[e]>=Pn[n]}var Pn,qr,Na=G(()=>{"use strict";Pu();Tu();Cu();Oa();Pn={debug:0,info:1,warn:2,error:3},qr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function $s(e,t,r){if(!Ru(e,t))return;let n={level:e,module:t,message:ka(r),timestamp:new Date};for(let o of Au())o.write(n);}function b(e){let t=$u.get(e);if(t)return t;let r={debug:n=>$s("debug",e,n),info:n=>$s("info",e,n),warn:n=>$s("warn",e,n),error:n=>$s("error",e,n)};return $u.set(e,r),r}var $u,_u=G(()=>{"use strict";Aa();Na();$u=new Map;});var R=G(()=>{"use strict";_u();Na();Aa();});function $y(e){return typeof e=="object"&&e!==null&&Ba in e&&e[Ba]===true}function Fa(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Ba]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Ua.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if($y(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Ua.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Ua.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Ua,Ba,ja=G(()=>{"use strict";R();Ua=b("encryption"),Ba="__encrypted__";});var Ka,Ly,wt,Tn,Ha=G(()=>{"use strict";R();Ka=promisify(execFile),Ly=promisify(exec),wt=b("encryption:macos-keyvault"),Tn=class{static async isAvailable(){try{let{stdout:t}=await Ly("command -v security");return wt.debug(`security binary found at: ${t.trim()}`),!0}catch{return wt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{wt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ka("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return wt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return wt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{wt.debug(`Storing secret: service=${t}, account=${r}`),await Ka("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),wt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw wt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return wt.debug(`Deleting secret: service=${t}, account=${r}`),await Ka("security",["delete-generic-password","-a",r,"-s",t]),wt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return wt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g,"")}function q(e){process.stdout.write(C.green(` \u2713 ${y(e)}
2
+ import*as En from'crypto';import {randomUUID,createHash}from'crypto';import*as Se from'os';import Se__default,{tmpdir,homedir,cpus}from'os';import*as W from'path';import W__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ue from'fs';import ue__default,{readFileSync,mkdirSync,existsSync,writeFileSync,rmSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import C from'chalk';import*as Zl from'readline';import {createInterface}from'readline';import Za from'conf';import gp,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import gS,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Cw from'jsonwebtoken';import Bw from'proper-lockfile';import lS from'ink-big-text';import Im from'ink-spinner';import*as Ht from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import yb from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import uc from'semver';import ua from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Sy=Object.defineProperty;var G=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var fu=(e,t)=>{for(var r in t)Sy(e,r,{get:t[r],enumerable:true});};var wr,Ue,Pa,Sr,So,Sn,br,Ta,gu,Ca,Xe,he,st,Qt,bs,bn,xn,In,vn,F=G(()=>{"use strict";wr="FLOW",Ue="flow-skills",Pa="flow-cli",Sr=[Ue,"flow-harness"],So="internal",Sn="external",br={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"},rule:{label:"Rule",color:"blue"},plugin:{label:"Plugin",color:"magenta"}},Ta=new Set(Object.keys(br)),gu={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ca=new Set(["internal","external"]),Xe={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"}},he="flow-claude-md-setup",st=5,Qt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,bs="https://flow.ciandt.com",bn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,xn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",In=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,vn="Must be a valid email address (e.g. name@example.com)";});var xs,xy,hu,bo,ka=G(()=>{"use strict";xs="aes-256-gcm",xy=16,hu=16,bo=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=En.randomBytes(xy),n=En.createCipheriv(xs,this.key,r,{authTagLength:hu}),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:xs}}decrypt(t){if(t.algorithm!==xs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=En.createDecipheriv(xs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:hu});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Aa(e){return e.replace(Py,"").replace(Ty,"").replace(Cy,"").replace(Iy,"Bearer ***").replace(vy,"***").replace(Ey,"***").replace(/\r\n|\r|\n/g,"\\n")}var Iy,vy,Ey,Py,Ty,Cy,Ra=G(()=>{"use strict";Iy=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,vy=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Ey=/[A-Za-z0-9+/]{40,}={0,2}/g,Py=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Ty=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Cy=/\x1b/g;});function vs(e){return e||Ue}function yu(e,t,r){return Ma(vs(r),e,t)}function $a(e,t){return W.join(Se.homedir(),er,"plugins","marketplaces",vs(t),"plugins","native",e)}function xo(e){return W.join(Se.homedir(),er,"plugins","marketplaces",vs(e),".claude-plugin","marketplace.json")}function Wr(){return W.join(Se.homedir(),er,"plugins","known_marketplaces.json")}function _a(e){return W.join(Se.homedir(),er,"plugins","marketplaces",vs(e))}function wu(){return W.join(Se.homedir(),Is,"cache","install.lock")}function Su(){return W.join(Se.homedir(),Is,"logs","flowsetup.log")}function Ma(e,t,r){return W.join(Se.homedir(),er,"plugins","cache",e,t,r)}function zr(e){let t=e==="global"?Se.homedir():process.cwd();return W.join(t,".claude","skills")}function Io(e){let t=e==="global"?Se.homedir():process.cwd();return W.join(t,".claude","skills-lock.json")}function Es(e="user"){return e==="project"?W.join(process.cwd(),".opencode","plugins"):W.join(Se.homedir(),".config","opencode","plugins")}function bu(){return W.join(Se.homedir(),Is,"flow-catalogs.json")}function xu(){let e=process.env.FLOW_HOME??W.join(Se.homedir(),Is);return W.join(e,"config.json")}function Ps(e="user"){return e==="project"||e==="local"?W.join(process.cwd(),er,"agents"):W.join(Se.homedir(),er,"agents")}function La(e="user"){return e==="project"||e==="local"?W.join(process.cwd(),er,"rules"):W.join(Se.homedir(),er,"rules")}function Iu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","skills"):W.join(Se.homedir(),".copilot","skills")}function vu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","agents"):W.join(Se.homedir(),".copilot","agents")}function Eu(e="user"){if(e==="local")throw new Error('Copilot does not support scope "local"');return e==="project"?W.join(process.cwd(),".github","hooks"):W.join(Se.homedir(),".copilot","hooks")}function Pu(e="user"){return e==="project"?W.join(process.cwd(),".cursor","plugins"):W.join(Se.homedir(),".cursor","plugins")}var er,Is,$e=G(()=>{"use strict";F();er=".claude",Is=".flow";});var ky,Ay,Ts,Tu=G(()=>{"use strict";$e();ky=5*1024*1024,Ay=3,Ts=class{filePath;constructor(){this.filePath=Su(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{ue.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=W.dirname(this.filePath);ue.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ue.statSync(this.filePath).size>ky){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ue.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=W.dirname(this.filePath),r=W.basename(this.filePath,".log"),n=ue.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Ay))ue.unlinkSync(W.join(t,o));}catch{}}};});var Cs,Cu=G(()=>{"use strict";Cs=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 ks,ku=G(()=>{"use strict";ks=class{write(t){process.stdout.write(t.message+`
5
+ `);}};});function Oa(){return As}function Au(e){return Da.add(e),()=>{Da.delete(e);}}var As,Da,Rs,Na=G(()=>{"use strict";As=[],Da=new Set;Rs=class{write(t){As.push(t),As.length>100&&As.shift();for(let r of Da)r();}};});function Ry(){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 Be(e,t){if(e==="tui"){let r=Ry();qr={context:e,transports:[new Rs,new Ts],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?qr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?qr={context:e,transports:[new Cs("cli")],minLevel:"debug",debugModules:null}:qr={context:e,transports:[new ks],minLevel:"info",debugModules:null};}function Ru(){return qr.transports}function $u(e,t){let{debugModules:r,minLevel:n}=qr;return qr.context==="tui"&&r&&r!=="all"?r.has(t)?Pn[e]>=Pn.debug:Pn[e]>=Pn.warn:Pn[e]>=Pn[n]}var Pn,qr,Ua=G(()=>{"use strict";Tu();Cu();ku();Na();Pn={debug:0,info:1,warn:2,error:3},qr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function $s(e,t,r){if(!$u(e,t))return;let n={level:e,module:t,message:Aa(r),timestamp:new Date};for(let o of Ru())o.write(n);}function b(e){let t=_u.get(e);if(t)return t;let r={debug:n=>$s("debug",e,n),info:n=>$s("info",e,n),warn:n=>$s("warn",e,n),error:n=>$s("error",e,n)};return _u.set(e,r),r}var _u,Mu=G(()=>{"use strict";Ra();Ua();_u=new Map;});var R=G(()=>{"use strict";Mu();Ua();Ra();});function $y(e){return typeof e=="object"&&e!==null&&Fa in e&&e[Fa]===true}function ja(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Fa]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Ba.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if($y(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Ba.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Ba.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Ba,Fa,Ka=G(()=>{"use strict";R();Ba=b("encryption"),Fa="__encrypted__";});var Ha,Ly,wt,Tn,Va=G(()=>{"use strict";R();Ha=promisify(execFile),Ly=promisify(exec),wt=b("encryption:macos-keyvault"),Tn=class{static async isAvailable(){try{let{stdout:t}=await Ly("command -v security");return wt.debug(`security binary found at: ${t.trim()}`),!0}catch{return wt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{wt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ha("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return wt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return wt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{wt.debug(`Storing secret: service=${t}, account=${r}`),await Ha("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),wt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw wt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return wt.debug(`Deleting secret: service=${t}, account=${r}`),await Ha("security",["delete-generic-password","-a",r,"-s",t]),wt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return wt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g,"")}function q(e){process.stdout.write(C.green(` \u2713 ${y(e)}
6
6
  `));}function v(e){process.stderr.write(C.red(` \u2717 ${y(e)}
7
7
  `));}function I(e){process.stdout.write(C.cyan(` \u2139 ${y(e)}
8
8
  `));}function xr(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
@@ -13,16 +13,16 @@ import*as En from'crypto';import {randomUUID,createHash}from'crypto';import*as S
13
13
  `);}function Ir(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
14
  `);}function oe(e){process.stdout.write(JSON.stringify(e)+`
15
15
  `);}function _e(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function te(e){return e instanceof Error?e.message:String(e)}function Lt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=G(()=>{"use strict";});async function By(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 Fy(e){let t=Yl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Va,Ga,Uy,ie,vr,Ja=G(()=>{"use strict";R();N();Va=promisify(execFile),Ga=promisify(exec),Uy=[{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"}],ie=b("encryption:linux-keyvault");vr=class e{static async isAvailable(){try{let{stdout:t}=await Ga("command -v secret-tool");ie.debug(`secret-tool found at: ${t.trim()}`);}catch{return ie.debug("secret-tool binary not found in PATH"),!1}try{return await Va("secret-tool",["lookup","service","__flow_connectivity_check__"]),ie.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(ie.debug(`Secret Service D-Bus not available: ${n}`),!1):(ie.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of Uy)try{return await Ga(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;ie.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 ie.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await Fy(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return ie.info(`Running: ${t.command}`),await By("Installing secret-tool...",()=>Ga(t.command)),e.isAvailable()}catch{return ie.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{ie.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Va("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return ie.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ie.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){ie.debug(`Storing secret: service=${t}, account=${r}`),ie.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),ie.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),ie.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?(ie.debug("secret-tool store succeeded"),o()):(ie.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=>{ie.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return ie.debug(`Deleting secret: service=${t}, account=${r}`),await Va("secret-tool",["clear","service",t,"account",r]),ie.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return ie.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function za(e,t){return `${e}:${t}`}function Eo(e){return e.replace(/'/g,"''")}function _s(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Wy(e){return `Add-Type -TypeDefinition @'
17
- ${Xa}
16
+ `);}function te(e){return e instanceof Error?e.message:String(e)}function Lt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=G(()=>{"use strict";});async function By(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 Fy(e){let t=Zl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Ga,Ja,Uy,ie,vr,Wa=G(()=>{"use strict";R();N();Ga=promisify(execFile),Ja=promisify(exec),Uy=[{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"}],ie=b("encryption:linux-keyvault");vr=class e{static async isAvailable(){try{let{stdout:t}=await Ja("command -v secret-tool");ie.debug(`secret-tool found at: ${t.trim()}`);}catch{return ie.debug("secret-tool binary not found in PATH"),!1}try{return await Ga("secret-tool",["lookup","service","__flow_connectivity_check__"]),ie.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(ie.debug(`Secret Service D-Bus not available: ${n}`),!1):(ie.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of Uy)try{return await Ja(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;ie.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 ie.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await Fy(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return ie.info(`Running: ${t.command}`),await By("Installing secret-tool...",()=>Ja(t.command)),e.isAvailable()}catch{return ie.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{ie.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ga("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return ie.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ie.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){ie.debug(`Storing secret: service=${t}, account=${r}`),ie.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),ie.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),ie.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?(ie.debug("secret-tool store succeeded"),o()):(ie.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=>{ie.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return ie.debug(`Deleting secret: service=${t}, account=${r}`),await Ga("secret-tool",["clear","service",t,"account",r]),ie.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return ie.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Xa(e,t){return `${e}:${t}`}function Eo(e){return e.replace(/'/g,"''")}function _s(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Wy(e){return `Add-Type -TypeDefinition @'
17
+ ${qa}
18
18
  '@
19
19
  [FlowCredManager]::Read('${Eo(e)}')`}function zy(e,t,r){return `Add-Type -TypeDefinition @'
20
- ${Xa}
20
+ ${qa}
21
21
  '@
22
22
  [FlowCredManager]::Write('${Eo(e)}', '${Eo(t)}', '${Eo(r)}')`}function Xy(e){return `Add-Type -TypeDefinition @'
23
- ${Xa}
23
+ ${qa}
24
24
  '@
25
- [FlowCredManager]::Delete('${Eo(e)}')`}async function Ms(e){return Hy("powershell.exe",e)}var Hy,St,Wa,Vy,Gy,Jy,Xa,Cn,qa=G(()=>{"use strict";R();Hy=promisify(execFile),St=b("encryption:windows-keyvault"),Wa=1,Vy=1,Gy=2,Jy=3;Xa=`
25
+ [FlowCredManager]::Delete('${Eo(e)}')`}async function Ms(e){return Hy("powershell.exe",e)}var Hy,St,za,Vy,Gy,Jy,qa,Cn,Ya=G(()=>{"use strict";R();Hy=promisify(execFile),St=b("encryption:windows-keyvault"),za=1,Vy=1,Gy=2,Jy=3;qa=`
26
26
  using System;
27
27
  using System.Runtime.InteropServices;
28
28
  using System.Text;
@@ -58,7 +58,7 @@ public class FlowCredManager {
58
58
 
59
59
  public static string Read(string target) {
60
60
  IntPtr credPtr;
61
- if (!CredRead(target, ${Wa}, 0, out credPtr)) return "";
61
+ if (!CredRead(target, ${za}, 0, out credPtr)) return "";
62
62
  try {
63
63
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
64
64
  if (cred.CredentialBlobSize <= 0) return "";
@@ -80,7 +80,7 @@ public class FlowCredManager {
80
80
  try {
81
81
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
82
82
  var cred = new CREDENTIAL();
83
- cred.Type = ${Wa};
83
+ cred.Type = ${za};
84
84
  cred.TargetName = targetPtr;
85
85
  cred.CredentialBlobSize = bytes.Length;
86
86
  cred.CredentialBlob = blobPtr;
@@ -98,54 +98,54 @@ public class FlowCredManager {
98
98
  }
99
99
 
100
100
  public static bool Delete(string target) {
101
- return CredDelete(target, ${Wa}, 0);
101
+ return CredDelete(target, ${za}, 0);
102
102
  }
103
103
  }
104
104
  `;Cn=class{static async isAvailable(){try{let{stdout:t}=await Ms(_s('Write-Output "ok"')),r=t.trim()==="ok";return St.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
- `)[0]:"unknown error";return St.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=za(t,r);St.debug(`Looking up secret: target=${n}`);let o=Wy(n),{stdout:s}=await Ms(_s(o)),i=s.trim();return St.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
- `)[0]:"unknown error";return St.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=za(t,r);St.debug(`Storing secret: target=${o}`);let s=zy(o,n,r),{stdout:i}=await Ms(_s(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];St.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 St.error(i),new Error(i,{cause:o})}}async deleteSecret(t,r){try{let n=za(t,r);St.debug(`Deleting secret: target=${n}`);let o=Xy(n),{stdout:s}=await Ms(_s(o)),i=s.trim()==="True";return St.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
- `)[0]:"unknown error";return St.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Qy(){let e=`${Se.hostname()}${Se.userInfo().username}`;return En.scryptSync(e,Yy,qy)}function ew(){let e=Qy(),t=new bo(e),r=Fa(t);return new Ya({projectName:Za,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function Ls(){return Ds||(Ds=ew()),Ds}var qy,Yy,Za,Zy,Ds,qe,Po=G(()=>{"use strict";Ca();ja();qy=32,Yy="flow-plugins-cli-fallback",Za="flow-plugins-cli-fallback",Zy={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};Ds=null;qe=class{warned=!1;async getSecret(t,r){return Ls().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Zy[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
105
+ `)[0]:"unknown error";return St.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=Xa(t,r);St.debug(`Looking up secret: target=${n}`);let o=Wy(n),{stdout:s}=await Ms(_s(o)),i=s.trim();return St.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
+ `)[0]:"unknown error";return St.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Xa(t,r);St.debug(`Storing secret: target=${o}`);let s=zy(o,n,r),{stdout:i}=await Ms(_s(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];St.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 St.error(i),new Error(i,{cause:o})}}async deleteSecret(t,r){try{let n=Xa(t,r);St.debug(`Deleting secret: target=${n}`);let o=Xy(n),{stdout:s}=await Ms(_s(o)),i=s.trim()==="True";return St.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
+ `)[0]:"unknown error";return St.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Qy(){let e=`${Se.hostname()}${Se.userInfo().username}`;return En.scryptSync(e,Yy,qy)}function ew(){let e=Qy(),t=new bo(e),r=ja(t);return new Za({projectName:Qa,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function Ls(){return Ds||(Ds=ew()),Ds}var qy,Yy,Qa,Zy,Ds,qe,Po=G(()=>{"use strict";ka();Ka();qy=32,Yy="flow-plugins-cli-fallback",Qa="flow-plugins-cli-fallback",Zy={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};Ds=null;qe=class{warned=!1;async getSecret(t,r){return Ls().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Zy[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
109
109
  using a machine-derived key. For stronger security, ${o}.
110
- `),this.warned=!0;}Ls().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ls(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return Ls().path}static hasExistingData(){try{let t=new Ya({projectName:Za});return ue.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Ya({projectName:Za});ue.rmSync(t.path,{force:!0});}catch{}Ds=null;}};});async function Qa(){if(qe.hasExistingData())return new qe;switch(process.platform){case "darwin":return await Tn.isAvailable()?new Tn:new qe;case "linux":return await vr.isAvailable()?new vr:await vr.ensureInstalled()?new vr:new qe;case "win32":return await Cn.isAvailable()?new Cn:new qe;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Nu=G(()=>{"use strict";Ha();Ja();qa();Po();});var Uu=G(()=>{"use strict";Ca();ja();Nu();Ha();Ja();qa();Po();});async function Er(){return Us||(Us=Qa()),Us}function Bs(){Us=null;}async function re(){let t=await(await Er()).getSecret(er,el);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pr(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Bu.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Er()).setSecret(er,el,JSON.stringify(e));}async function Fu(){let e=await Er();await e.deleteSecret(er,el),await e.deleteSecret(er,tl),await e.deleteSecret(er,rl);}async function ju(){return (await Er()).getStoragePath()}async function Ku(e){await(await Er()).setSecret(er,tl,JSON.stringify(e));}async function Fs(){let t=await(await Er()).getSecret(er,tl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function js(e){await(await Er()).setSecret(er,rl,JSON.stringify(e));}async function kn(){let t=await(await Er()).getSecret(er,rl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Tr(){let e=await Fs();return e?new Date(e.expiresAt)>new Date:false}function Dt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Bu.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Bu,er,el,tl,rl,Us,Ce=G(()=>{"use strict";Uu();R();Bu=b("config:credentials"),er="flow-plugins-cli",el="credentials",tl="token-cache",rl="user-info",Us=null;});function An(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ks=G(()=>{"use strict";});function tw(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 nl(e){if(Hu.some(r=>r.test(e)))return true;let t=tw(e);return !!(t&&Hu.some(r=>r.test(t)))}function rw(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ot(e,t){let r=rw(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&nl(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Hu,Yr=G(()=>{"use strict";Hu=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function sw(e){if(!Zt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function iw(e){if(e instanceof HTTPError){let t=e.response.status;ol.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Vu[r]?new Error(Vu[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?(ol.debug(`Non-HTTP error during authentication: ${e.message}`),e):(ol.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Zr(e){let t=Ot("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");sw(e.tenant);let r;try{r=await fp.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await iw(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Pr(e),await Ku({accessToken:r.access_token,expiresAt:n});let o=An(r.access_token);await js({sub:o.sub,name:o.name,email:o.email});}var ol,Vu,Hs=G(()=>{"use strict";Ce();Ks();Yr();R();F();ol=b("api:auth");Vu={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 Nt(){if(await Tr()){let n=await Fs();if(n)return n.accessToken}Gu.debug("Token expired or missing, re-authenticating...");let t=await re();if(!t)throw new Error("Not authenticated. Run: flow auth login");qe.clearFallbackFile(),Bs(),await Zr(t);let r=await Fs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Gu.debug("Token refreshed successfully"),r.accessToken}var Gu,Rn=G(()=>{"use strict";Ce();Hs();Po();R();Gu=b("lib:tokenProvider");});function Kt(){return fp.create({prefix:Ot("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Nt();e.headers.set("Authorization",`Bearer ${t}`);let r=await re();r?.tenant&&Zt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Fo=G(()=>{"use strict";Yr();Ce();Rn();F();});function ip(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Bn(e,t,r){let n=Kt(),o=ip({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function ap(e,t={}){let r=Kt(),n=ip(t);return n?r.head(e,n):r.head(e)}async function Fn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Tl=G(()=>{"use strict";Fo();});function jo(e){if(!e||!rb.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function jn(e){return nb.test(e)}function Kn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function kl(e){if(!ob.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 Hn(e,t){let r=Kn(e);kl(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function yi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!sb.test(t)&&!ib.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var rb,nb,ob,sb,ib,Nr=G(()=>{"use strict";rb=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;nb=/^[^@]+@[^@]+$/;ob=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;sb=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,ib=/^https:\/\/[\w./:@?&=+#%-]+$/;});var up={};mu(up,{FlowApiAdapter:()=>Vn});var ab,Vn,Al=G(()=>{"use strict";Fo();Tl();R();Nr();ab=b("catalog.flow-api"),Vn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Bn("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await Fn(t);if(r)throw new Error(r,{cause:t});if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login",{cause:t}):new Error(`Failed to fetch plugin catalog: HTTP ${n}`,{cause:t})}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog",{cause:t}):new Error(`Failed to fetch plugin catalog: ${t.message}`,{cause:t}):t}}async fetchManifest(t){jo(t);try{return await Bn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Fn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await Kt().head("v1/plugins/catalog"),ab.debug("ping ok"),!0}catch{return !1}}};});function cb(){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 pp(){return dp??=cb(),dp}var dp,mp=G(()=>{"use strict";});var hp={};mu(hp,{GitRepoAdapter:()=>Gn});function gp(e,t){if(!ub.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var ub,Gn,Rl=G(()=>{"use strict";mp();Yr();ub=/^[a-zA-Z0-9_.-]+$/;Gn=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(nl(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return gp(a,"owner"),gp(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 fp.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 fp.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 pp();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});F();var S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Pa),origins:new Set(Ta)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Pa)},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(Ta)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ce();Rn();Ks();F();Yr();R();var Vs=b("api:metrics");function Ju(){return Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Wu(e,t,r){return fp.post(e,{json:t,headers:r})}async function lw(e){let t=await kn();if(t)return t;let r=An(e),n={sub:r.sub,name:r.name,email:r.email};return await js(n),n}async function P(e,t){let r=await Nt(),n=await lw(r),o=await re();if(!Zt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ea,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Wu(Ju(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Vs.debug(`Metrics event sent: ${e}`);}catch(i){throw Vs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function zu(e,t,r){try{let n=r&&Zt.test(r)?r:"unknown",o={action:e,booster:Ea,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Wu(Ju(),o,{FlowTenant:n}),Vs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Vs.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var E={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_PLUGIN_PRUNE_COMPLETED:"CLI_PLUGIN_PRUNE_COMPLETED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var cw={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},bt={...cw};function Xu(e){let t=Date.now();bt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Qr(e){bt.currentStep=e,bt.stepStart=Date.now();}function ee(){return {...bt}}function Cr(){return bt.sessionStart===0?0:Date.now()-bt.sessionStart}function en(){return bt.stepStart===0?0:Date.now()-bt.stepStart}function qu(){bt.tuiSessionStart=Date.now();}function Yu(){return bt.tuiSessionStart===0?0:Date.now()-bt.tuiSessionStart}R();var uw=3e3,dw=b("abandonment");async function Gs(e){let{currentStep:t,sessionStart:r}=ee();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Cr()};try{await Promise.race([P(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),uw))]);}catch(o){dw.warn(`Abandonment event failed: ${String(o)}`);}}function Zu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var pw=3e3,mw=b("session-end");async function Co(e,t,r){let n=Yu(),s=[P(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Gs(e));try{await Zu(Promise.all(s).then(()=>{}),pw);}catch(i){mw.warn(`Session end event failed: ${String(i)}`);}}var yw=2e3;function ed(){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),Co("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},yw);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var xw=16;function td({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(xw)}),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]})})]})}F();function rd({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();In.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:vn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function nd({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}F();function od(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[wr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var at=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})}));Hs();F();function nn(){return W__default.join(Se__default.homedir(),".claude","settings.json")}function id(e){return `${(e&&e.trim().length>0?e.trim():bs).replace(/\/+$/,"")}/flow-litellm/`}function Lo(){let e=nn();if(!ue__default.existsSync(e))return {status:"missing"};let t=ue__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Ws(e){let t=nn();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ue__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,t);}function ad(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function dl(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function ld(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var kw=3600,on=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Do(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function Aw(e){return Cw.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:kw})}function zs(e,t={}){let r=Lo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new on;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?dl(r.settings):null,s=r.status==="ok"?ld(r.settings):null,i=t.jwtOverride??Aw(e),a=id(e.customUrl),l=ad(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Xs(e){Ws(e.merged);}function cd(){let e=Lo();return e.status!=="ok"?false:dl(e.settings)!==null}Ce();$e();function Rw(){let e=bu();if(!ue__default.existsSync(e))return {};try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return {}}}var pl=null;function $w(){return pl===null&&(pl=Rw()),pl}function Rr(){let e=$w().ENABLE_EXPERIMENTAL_BETAS;if(e!==void 0)return !!e;let t=process.env.ENABLE_EXPERIMENTAL_BETAS;return t===void 0?false:t!=="0"&&t!=="false"&&t!==""}F();function Dw(){return me.filter(e=>e.platforms[process.platform]?.status==="supported")}function dd(e){let t=Dw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var qs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=W__default.join(Se__default.homedir(),".claude","settings.json"),r=ue__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??bs),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},Ow={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},me=Rr()?[qs,Ow]:[qs];Ce();R();var Fw=b("moduleState");function Zs(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"modules.json")}var jw={retries:5,minTimeout:50};async function pd(e,t){ue__default.mkdirSync(W__default.dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:jw});try{return await t()}finally{await r();}}function md(){let e=Zs();if(!ue__default.existsSync(e))return [];try{let t=JSON.parse(ue__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Fw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ue__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ue__default.rmSync(e,{force:true}),[]}}function sn(){return md()}function fd(e){let t=Zs();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ue__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,t);}function lt(e){return sn().find(t=>t.alias===e)??null}async function xt(e){let t=Zs();await pd(t,async()=>{let r=md(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,fd(r);});}async function an(){let e=Zs();ue__default.existsSync(e)||await pd(e,async()=>{ue__default.existsSync(e)||fd([]);});}var Vw=promisify(execFile);function $r(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Bt(e){let t=process.platform==="win32"?"where":"which";try{return await Vw(t,[e]),!0}catch{return false}}function tr(){return process.platform==="win32"?"npm.cmd":"npm"}var gd=promisify(execFile),_n=class{type="npm";async isAvailable(){return Bt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=$r(t,"npm");if(!r)return null;try{let{stdout:n}=await gd(tr(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=$r(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 gd(tr(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var Qs=promisify(execFile),Xw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ei=class{type="homebrew";async isAvailable(){return Bt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=$r(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=$r(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Qs("brew",["tap",o.tap]),await Qs("brew",["trust",o.tap])),await Qs("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 Qs("brew",["list","--versions",t]),n=r.trim().match(Xw);return n?n[2]:null}catch{return null}}};var Mn=promisify(execFile),yd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function wd(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"bin")}var ti=class{type="curl";async isAvailable(){return Bt("curl")}async install(t){let r=Date.now(),n=$r(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=W__default.join(wd(),W__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Mn(n,["--version"]),s=o.match(yd);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=W__default.join(Se__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Mn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ue__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ue__default.chmodSync(s,448),await Mn("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{ue__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=wd(),i=W__default.join(s,W__default.basename(n.binaryName)),a=false;try{if(ue__default.mkdirSync(s,{recursive:!0}),a=!0,await Mn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ue__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ue__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Mn(i,["--version"]),c=u.match(yd);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ue__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=W__default.join(Se__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Mn("curl",["-L","--fail","-o",n,r]);let o=ue__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ue__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{ue__default.unlinkSync(n);}catch{}}}};R();var Sd="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Sd=e.version);}catch{}var ye=Sd;var Me=b("moduleInstaller");function jt(e){switch(e){case "npm":return new _n;case "homebrew":return new ei;case "curl":return new ti}}async function Oo(e,t,r){try{await P(E.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){Me.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Mr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Me.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=jt(r),u=false;try{u=await l.isAvailable();}catch(d){Me.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await P(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ye,trigger:t});}catch(d){Me.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Me.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await xt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(E.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Me.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await rS(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Oo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function rS(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await re(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Me.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Me.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Me.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Me.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function ri(e,t){let r=Date.now(),n=lt(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=jt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ye,trigger:"command"});}catch(a){Me.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);Me.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await xt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(E.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){Me.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(E.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Me.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(E.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){Me.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var ni=b("flowAiObsSetup");async function oi(e,t){try{if(!await new _n().isAvailable().catch(()=>!1))return ni.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Mr(qs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ni.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ni.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ni.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function bd(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 nS=b("useAuthSetup");function xd(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),g=useRef(0),h=useRef(false),{setCredentials:w,setJustAuthenticated:x}=at(),_=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},L=()=>{P(E.CLI_SESSION_STARTED,{cli_version:ye,os:process.platform,node_version:process.version,duration_ms:Cr(),interface:"tui"}).catch(()=>{});},T=async H=>{h.current=true;let Z={...r.current,customUrl:n.current??void 0};try{H&&Xs(H),await Pr(Z);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),h.current=false;return}let{clientSecret:A,...j}=Z;w(j),x(true),L(),await oi(n.current,o.current).catch(J=>nS.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),si({starterKit:j.starterKit});},$=async()=>T(),O=async H=>T(H),U=H=>{try{let Z={...r.current,customUrl:n.current??void 0};return zs(Z,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(Z){return Z instanceof on?(m("malformedConfirm"),null):(l(Z instanceof Error?Z.message:"Failed to read settings.json"),m("fields"),null)}},se=()=>{let H=U(true);H&&(f(H),O(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let Z;try{Z=Do(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Z,m("customUrl");},V=H=>{n.current=H,m("email");},ne=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Dt(H),c(true),l(null),g.current+=1;try{await Zr(r.current);let Z=U(!1);Z&&(f(Z),m("preview"));}catch(Z){let A=Z instanceof Error?Z.message:"Authentication failed";l(A),zu(E.CLI_AUTH_FAILED,{error_code:bd(Z),attempt:g.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:h,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:ne,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:se}}F();N();function Id(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:g}=xd(),[h,w]=useState("confirm"),[x,_]=useState(""),L=useRef(""),[T,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),L.current="",_(""),$(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?f():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?g():U.escape&&u();return}if(o==="customUrl"){if(h==="confirm")O==="y"||O==="Y"?w("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)L.current="",_(""),w("confirm");else if(U.return){let se=L.current.trim();se.length>0&&bn.test(se)?($(false),d(se)):se.length>0&&$(true);}else U.backspace||U.delete?(L.current=L.current.slice(0,-1),_(L.current)):O&&!U.ctrl&&!U.meta&&(L.current=L.current+O,_(L.current),$(false));return}o!=="email"&&U.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:x}),jsx(Text,{color:"cyan",children:"\u2588"})]}),T&&jsx(Text,{color:"red",children:xn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(rd,{onConfirm:m})]}):o==="preview"&&s?jsx(nd,{plan:s}):o==="malformedConfirm"?jsx(od,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:jsx(Box,{marginBottom:1,children:jsx(td,{label:"JWT",value:e,onChange:O=>{a(O),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Dn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(lS,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ye]})})]})}var Td=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ae=Rr()?Td:Td.slice(0,3);function cS(e){return ae.findIndex(t=>t.id===e)}function gl(e,t,r){let n=cS(r.activeTab);if(t.rightArrow||t.tab){let o=ae[(n+1)%ae.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ae[(n-1+ae.length)%ae.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ae[n]?.focus??"list"}]:[]}var Ad={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Rd({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ae.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Ad[r]} (${e})`:Ad[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ye=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function _d(){let e=S(i=>i.focus),t=Ye(i=>i.query),r=Ye(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..."})]})}F();var Md=Object.keys(br).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...br[e]})),Ld=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...fu[e]}));function Dd(){let e=S(n=>n.catalogFilters),t=Md.every(n=>e.types.has(n.type)),r=Ld.every(n=>e.origins.has(n.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",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"]})]}),Md.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"]})]}),Ld.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)})]})}F();function Od({type:e}){let{label:t,color:r}=br[e];return jsx(Text,{color:r,children:t})}F();function Bd({origin:e}){return e===So?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ai=gS.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(Od,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Bd,{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 ",Lt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function On({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Kd({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(On,{message:t});let n=Math.max(0,r-Math.floor(st/2)),o=Math.min(e.length,n+st);o===e.length&&(n=Math.max(0,o-st));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(ai,{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 Gd({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}F();function Wd({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(On,{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(st/2)),u=Math.min(n.length,l+st);u===n.length&&(l=Math.max(0,u-st));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Gd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ai,{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 vS={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ES({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(_d,{}),jsx(Dd,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:vS[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Wd,{groups:n,emptyMessage:r}):jsx(Kd,{items:e,emptyMessage:r})]})}function zd({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(ES,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var CS={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 li(){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:[CS[e],t?" | Ctrl+D: debug log":""]})})}N();function Xd({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ci({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Dr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Qd=20;function Un(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Qd),s="\u2588".repeat(o)+"\u2591".repeat(Qd-o),i=`${Dr(e)} / ${Dr(t)}`;return {bar:s,percent:n,label:i}}function ui({received:e,total:t}){let{bar:r,percent:n,label:o}=Un(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function di({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 ct({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))})]})}F();var Pl=Object.entries(Xe),np=[...Pl.map(([,e])=>e.actionLabel),"Cancel"],op=Object.fromEntries(Pl.map(([,e])=>[e.actionLabel,e.description]));function sp(e){let t=Pl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var KS=b("provider.registry"),HS=3e4,mi=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()+HS}),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"&&KS.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 VS={user:"global",project:"project",local:"local"};function fi(e){return e?VS[e]:"global"}var Ze=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},Or=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};Fo();Tl();R();var WS=b("catalog.registry"),gi=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);WS.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()]}};$e();var tb={retries:5,minTimeout:50};async function Cl(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:tb});try{return await t()}finally{await r();}}var hi=class{filePath;constructor(t){this.filePath=t??Su();}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 Cl(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 Cl(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Cl(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));});}};Al();var le=new gi,nr=new hi,db=["flow-harness"];function pb(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?db:e.split(",").map(t=>t.trim()).filter(Boolean)}le.register(new Vn);for(let e of pb())le.register(new Vn(e));var yp=false;async function wp(){if(yp)return;yp=true;let e=await nr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Rl(),hp));for(let r of e)le.register(new t(r.id,r.name,r.source));}Nr();function Sp(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let t=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(t)))}R();var fb=b("api:actions"),bp=2;async function or(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Al(),up));return new t(e).fetchItems()}return le.fetchAll()}async function xp(){return le.fetchAllWithErrors()}async function Jn(e,t){jo(e);try{return await Bn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Fn(r);throw n?new Error(n,{cause:r}):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`,{cause:r}):r.message.includes("timeout")?new Error("Download timed out after 30s",{cause:r}):new Error(`Failed to fetch plugin manifest: ${r.message}`,{cause:r}):r}}async function gb(e,t){try{let n=(await ap(`v1/plugins/${e}/archive`,{source:t,timeoutMs:3e4})).headers.get("x-archive-size"),o=n?Number(n):NaN;return Number.isFinite(o)&&o>0?o:void 0}catch(r){fb.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function Ip(e,t,r){jo(e);try{let n=await gb(e,r),o=Sp(n),s=await Bn(`v1/plugins/${e}/archive`,r,o),i=s.headers.get("x-archive-size"),a=i?Number(i):NaN,l=Number.isFinite(a)&&a>0?a:0,u=l>0,c=s.body;if(!c)throw new Error("Failed to download plugin: response has no body");let d=c.getReader(),m=[],p=0;for(;;){let{done:f,value:g}=await d.read();if(f)break;if(p+=g.byteLength,u&&p>l*bp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*bp}`);m.push(g),u&&t?.(p,l);}return Buffer.concat(m)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await Fn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function wi(){try{let{profiles:e}=await Kt().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",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}$e();$e();async function vp(e,t){let r=W.resolve(t);await Ht.mkdir(r,{recursive:true});let n=W.join(W.dirname(r),`${randomUUID()}.zip`);try{await Ht.writeFile(n,e);let o=await yb.Open.file(n),s=W.normalize(r+W.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=W.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(W.resolve(W.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ht.unlink(n);}catch{}}}async function $l(e){await Ht.rm(e,{recursive:true,force:true});}async function sr(){let e=yu();await Ht.mkdir(W.dirname(e),{recursive:true});try{await Ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Bw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}$e();F();R();var xb=b("marketplace-registry");function Ib(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||Ue,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Pp(e){let t=xo(e);if(!ue__default.existsSync(t))return null;try{return JSON.parse(ue__default.readFileSync(t,"utf-8"))}catch{return null}}function vb(e){let t=Pp(e);if(t)return t;let r=Ib(e),n=xo(e);return ue__default.mkdirSync(W__default.dirname(n),{recursive:true}),Ll(r,e),r}function Ll(e,t){let r=xo(t),n=`${r}.${randomUUID()}.tmp`;ue__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(n,r);}function Eb(e){let t=e||Ue,r=Wr(),n={};try{ue__default.existsSync(r)&&(n=JSON.parse(ue__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:$a(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;ue__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(o,r);}async function _l(e,t){let r=$a(e),n=W__default.relative(r,xo(e));try{let o=simpleGit({baseDir:r,timeout:{block:1e4}});if((await o.status()).files.length===0)return;await o.add([n,"plugins/native/"]),await o.commit(t);}catch(o){xb.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function Tp(e,t,r){Le(e.name),Eb(r);let n=Ra(e.name,r);ue__default.mkdirSync(W__default.dirname(n),{recursive:true});try{ue__default.lstatSync(n),ue__default.rmSync(n,{recursive:!0,force:!0});}catch{}ue__default.cpSync(t,n,{recursive:true,dereference:true});let o=vb(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Ll(o,r)),await _l(r,`chore: register ${e.name}@${e.version}`);}async function Cp(e,t){Le(e);let r=Ra(e,t);try{ue__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=Pp(t);if(!n){await _l(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Ll(n,t),await _l(t,`chore: unregister ${e}`);}N();R();var Tb=b("mcpConfigReader"),Cb=500,kb=512;function Ab(){return W__default.join(Se__default.homedir(),".claude.json")}function Rb(){return W__default.join(process.cwd(),".mcp.json")}function Ap(e){if(!ue__default.existsSync(e))return null;try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return Tb.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dl(e){if(!Ko(e))return {};let t=e.mcpServers;return Ko(t)?t:{}}function Ol(e,t){return Object.keys(e).slice(0,Cb).map(n=>({name:y(n.slice(0,kb)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function $p(){let e=[],t=Ab(),r=Ap(t);if(Ko(r)){let a=r,l=Dl(a);e.push(...Ol(l,"user"));let u=process.cwd();if(Ko(a.projects)){let c=a.projects[u];if(Ko(c)){let d=Dl(c);e.push(...Ol(d,"local"));}}}let n=Rb(),o=Ap(n),s=Dl(o);e.push(...Ol(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}R();F();function Ho(e,t){let r=join(e,".gitignore");if(!existsSync(r)){writeFileSync(r,`${t}
110
+ `),this.warned=!0;}Ls().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ls(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return Ls().path}static hasExistingData(){try{let t=new Za({projectName:Qa});return ue.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Za({projectName:Qa});ue.rmSync(t.path,{force:!0});}catch{}Ds=null;}};});async function el(){if(qe.hasExistingData())return new qe;switch(process.platform){case "darwin":return await Tn.isAvailable()?new Tn:new qe;case "linux":return await vr.isAvailable()?new vr:await vr.ensureInstalled()?new vr:new qe;case "win32":return await Cn.isAvailable()?new Cn:new qe;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Uu=G(()=>{"use strict";Va();Wa();Ya();Po();});var Bu=G(()=>{"use strict";ka();Ka();Uu();Va();Wa();Ya();Po();});async function Er(){return Us||(Us=el()),Us}function Bs(){Us=null;}async function re(){let t=await(await Er()).getSecret(tr,tl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pr(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw Fu.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Er()).setSecret(tr,tl,JSON.stringify(e));}async function ju(){let e=await Er();await e.deleteSecret(tr,tl),await e.deleteSecret(tr,rl),await e.deleteSecret(tr,nl);}async function Ku(){return (await Er()).getStoragePath()}async function Hu(e){await(await Er()).setSecret(tr,rl,JSON.stringify(e));}async function Fs(){let t=await(await Er()).getSecret(tr,rl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function js(e){await(await Er()).setSecret(tr,nl,JSON.stringify(e));}async function kn(){let t=await(await Er()).getSecret(tr,nl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Tr(){let e=await Fs();return e?new Date(e.expiresAt)>new Date:false}function Dt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Fu.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Fu,tr,tl,rl,nl,Us,Ce=G(()=>{"use strict";Bu();R();Fu=b("config:credentials"),tr="flow-plugins-cli",tl="credentials",rl="token-cache",nl="user-info",Us=null;});function An(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ks=G(()=>{"use strict";});function tw(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 ol(e){if(Vu.some(r=>r.test(e)))return true;let t=tw(e);return !!(t&&Vu.some(r=>r.test(t)))}function rw(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ot(e,t){let r=rw(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&ol(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Vu,Yr=G(()=>{"use strict";Vu=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function sw(e){if(!Qt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function iw(e){if(e instanceof HTTPError){let t=e.response.status;sl.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Gu[r]?new Error(Gu[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?(sl.debug(`Non-HTTP error during authentication: ${e.message}`),e):(sl.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Zr(e){let t=Ot("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");sw(e.tenant);let r;try{r=await gp.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await iw(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Pr(e),await Hu({accessToken:r.access_token,expiresAt:n});let o=An(r.access_token);await js({sub:o.sub,name:o.name,email:o.email});}var sl,Gu,Hs=G(()=>{"use strict";Ce();Ks();Yr();R();F();sl=b("api:auth");Gu={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 Nt(){if(await Tr()){let n=await Fs();if(n)return n.accessToken}Ju.debug("Token expired or missing, re-authenticating...");let t=await re();if(!t)throw new Error("Not authenticated. Run: flow auth login");qe.clearFallbackFile(),Bs(),await Zr(t);let r=await Fs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Ju.debug("Token refreshed successfully"),r.accessToken}var Ju,Rn=G(()=>{"use strict";Ce();Hs();Po();R();Ju=b("lib:tokenProvider");});function Kt(){return gp.create({prefix:Ot("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Nt();e.headers.set("Authorization",`Bearer ${t}`);let r=await re();r?.tenant&&Qt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Fo=G(()=>{"use strict";Yr();Ce();Rn();F();});function ap(e){if(!(e.source===void 0&&e.timeoutMs===void 0))return {...e.source!==void 0&&{searchParams:{source:e.source}},...e.timeoutMs!==void 0&&{timeout:e.timeoutMs}}}function Bn(e,t,r){let n=Kt(),o=ap({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function lp(e,t={}){let r=Kt(),n=ap(t);return n?r.head(e,n):r.head(e)}async function Fn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Cl=G(()=>{"use strict";Fo();});function jo(e){if(!e||!rb.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function jn(e){return nb.test(e)}function Kn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Al(e){if(!ob.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 Hn(e,t){let r=Kn(e);Al(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function yi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!sb.test(t)&&!ib.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var rb,nb,ob,sb,ib,Nr=G(()=>{"use strict";rb=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;nb=/^[^@]+@[^@]+$/;ob=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;sb=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,ib=/^https:\/\/[\w./:@?&=+#%-]+$/;});var dp={};fu(dp,{FlowApiAdapter:()=>Vn});var ab,Vn,Rl=G(()=>{"use strict";Fo();Cl();R();Nr();ab=b("catalog.flow-api"),Vn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Bn("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await Fn(t);if(r)throw new Error(r,{cause:t});if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login",{cause:t}):new Error(`Failed to fetch plugin catalog: HTTP ${n}`,{cause:t})}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog",{cause:t}):new Error(`Failed to fetch plugin catalog: ${t.message}`,{cause:t}):t}}async fetchManifest(t){jo(t);try{return await Bn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Fn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await Kt().head("v1/plugins/catalog"),ab.debug("ping ok"),!0}catch{return !1}}};});function cb(){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 mp(){return pp??=cb(),pp}var pp,fp=G(()=>{"use strict";});var yp={};fu(yp,{GitRepoAdapter:()=>Gn});function hp(e,t){if(!ub.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var ub,Gn,$l=G(()=>{"use strict";fp();Yr();ub=/^[a-zA-Z0-9_.-]+$/;Gn=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(ol(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return hp(a,"owner"),hp(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 gp.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 gp.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 mp();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});F();var S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Ta),origins:new Set(Ca)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Ta)},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(Ca)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ce();Rn();Ks();F();Yr();R();var Vs=b("api:metrics");function Wu(){return Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function zu(e,t,r){return gp.post(e,{json:t,headers:r})}async function lw(e){let t=await kn();if(t)return t;let r=An(e),n={sub:r.sub,name:r.name,email:r.email};return await js(n),n}async function P(e,t){let r=await Nt(),n=await lw(r),o=await re();if(!Qt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Pa,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await zu(Wu(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Vs.debug(`Metrics event sent: ${e}`);}catch(i){throw Vs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Xu(e,t,r){try{let n=r&&Qt.test(r)?r:"unknown",o={action:e,booster:Pa,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await zu(Wu(),o,{FlowTenant:n}),Vs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Vs.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var E={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_PLUGIN_PRUNE_COMPLETED:"CLI_PLUGIN_PRUNE_COMPLETED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var cw={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},bt={...cw};function qu(e){let t=Date.now();bt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Qr(e){bt.currentStep=e,bt.stepStart=Date.now();}function ee(){return {...bt}}function Cr(){return bt.sessionStart===0?0:Date.now()-bt.sessionStart}function en(){return bt.stepStart===0?0:Date.now()-bt.stepStart}function Yu(){bt.tuiSessionStart=Date.now();}function Zu(){return bt.tuiSessionStart===0?0:Date.now()-bt.tuiSessionStart}R();var uw=3e3,dw=b("abandonment");async function Gs(e){let{currentStep:t,sessionStart:r}=ee();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Cr()};try{await Promise.race([P(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),uw))]);}catch(o){dw.warn(`Abandonment event failed: ${String(o)}`);}}function Qu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var pw=3e3,mw=b("session-end");async function Co(e,t,r){let n=Zu(),s=[P(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Gs(e));try{await Qu(Promise.all(s).then(()=>{}),pw);}catch(i){mw.warn(`Session end event failed: ${String(i)}`);}}var yw=2e3;function td(){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),Co("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},yw);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var xw=16;function rd({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(xw)}),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]})})]})}F();function nd({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();In.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:vn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function od({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}F();function sd(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[wr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var at=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})}));Hs();F();function nn(){return W__default.join(Se__default.homedir(),".claude","settings.json")}function ad(e){return `${(e&&e.trim().length>0?e.trim():bs).replace(/\/+$/,"")}/flow-litellm/`}function Lo(){let e=nn();if(!ue__default.existsSync(e))return {status:"missing"};let t=ue__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Ws(e){let t=nn();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ue__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,t);}function ld(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function pl(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function cd(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var kw=3600,on=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Do(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function Aw(e){return Cw.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:kw})}function zs(e,t={}){let r=Lo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new on;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?pl(r.settings):null,s=r.status==="ok"?cd(r.settings):null,i=t.jwtOverride??Aw(e),a=ad(e.customUrl),l=ld(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Xs(e){Ws(e.merged);}function ud(){let e=Lo();return e.status!=="ok"?false:pl(e.settings)!==null}Ce();$e();function Rw(){let e=xu();if(!ue__default.existsSync(e))return {};try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return {}}}var ml=null;function $w(){return ml===null&&(ml=Rw()),ml}function Rr(){let e=$w().ENABLE_EXPERIMENTAL_BETAS;if(e!==void 0)return !!e;let t=process.env.ENABLE_EXPERIMENTAL_BETAS;return t===void 0?false:t!=="0"&&t!=="false"&&t!==""}F();function Dw(){return me.filter(e=>e.platforms[process.platform]?.status==="supported")}function pd(e){let t=Dw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var qs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=W__default.join(Se__default.homedir(),".claude","settings.json"),r=ue__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??bs),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},Ow={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},me=Rr()?[qs,Ow]:[qs];Ce();R();var Fw=b("moduleState");function Zs(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"modules.json")}var jw={retries:5,minTimeout:50};async function md(e,t){ue__default.mkdirSync(W__default.dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:jw});try{return await t()}finally{await r();}}function fd(){let e=Zs();if(!ue__default.existsSync(e))return [];try{let t=JSON.parse(ue__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Fw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ue__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ue__default.rmSync(e,{force:true}),[]}}function sn(){return fd()}function gd(e){let t=Zs();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ue__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,t);}function lt(e){return sn().find(t=>t.alias===e)??null}async function xt(e){let t=Zs();await md(t,async()=>{let r=fd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,gd(r);});}async function an(){let e=Zs();ue__default.existsSync(e)||await md(e,async()=>{ue__default.existsSync(e)||gd([]);});}var Vw=promisify(execFile);function $r(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Bt(e){let t=process.platform==="win32"?"where":"which";try{return await Vw(t,[e]),!0}catch{return false}}function rr(){return process.platform==="win32"?"npm.cmd":"npm"}var hd=promisify(execFile),_n=class{type="npm";async isAvailable(){return Bt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=$r(t,"npm");if(!r)return null;try{let{stdout:n}=await hd(rr(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=$r(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 hd(rr(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var Qs=promisify(execFile),Xw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ei=class{type="homebrew";async isAvailable(){return Bt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=$r(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=$r(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Qs("brew",["tap",o.tap]),await Qs("brew",["trust",o.tap])),await Qs("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 Qs("brew",["list","--versions",t]),n=r.trim().match(Xw);return n?n[2]:null}catch{return null}}};var Mn=promisify(execFile),wd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Sd(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"bin")}var ti=class{type="curl";async isAvailable(){return Bt("curl")}async install(t){let r=Date.now(),n=$r(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=W__default.join(Sd(),W__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Mn(n,["--version"]),s=o.match(wd);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=W__default.join(Se__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Mn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ue__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ue__default.chmodSync(s,448),await Mn("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{ue__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=Sd(),i=W__default.join(s,W__default.basename(n.binaryName)),a=false;try{if(ue__default.mkdirSync(s,{recursive:!0}),a=!0,await Mn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ue__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ue__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Mn(i,["--version"]),c=u.match(wd);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ue__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=W__default.join(Se__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Mn("curl",["-L","--fail","-o",n,r]);let o=ue__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ue__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{ue__default.unlinkSync(n);}catch{}}}};R();var bd="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(bd=e.version);}catch{}var ye=bd;var Me=b("moduleInstaller");function jt(e){switch(e){case "npm":return new _n;case "homebrew":return new ei;case "curl":return new ti}}async function Oo(e,t,r){try{await P(E.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){Me.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Mr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Me.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=jt(r),u=false;try{u=await l.isAvailable();}catch(d){Me.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Oo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await P(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ye,trigger:t});}catch(d){Me.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Me.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await xt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(E.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Me.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await rS(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Oo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function rS(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await re(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Me.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Me.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Me.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Me.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function ri(e,t){let r=Date.now(),n=lt(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=jt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ye,trigger:"command"});}catch(a){Me.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);Me.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await xt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(E.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){Me.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(E.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Me.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(E.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){Me.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var ni=b("flowAiObsSetup");async function oi(e,t){try{if(!await new _n().isAvailable().catch(()=>!1))return ni.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Mr(qs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ni.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ni.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ni.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function xd(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 nS=b("useAuthSetup");function Id(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),g=useRef(0),h=useRef(false),{setCredentials:w,setJustAuthenticated:x}=at(),_=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},L=()=>{P(E.CLI_SESSION_STARTED,{cli_version:ye,os:process.platform,node_version:process.version,duration_ms:Cr(),interface:"tui"}).catch(()=>{});},T=async H=>{h.current=true;let Z={...r.current,customUrl:n.current??void 0};try{H&&Xs(H),await Pr(Z);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),h.current=false;return}let{clientSecret:A,...j}=Z;w(j),x(true),L(),await oi(n.current,o.current).catch(J=>nS.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),si({starterKit:j.starterKit});},$=async()=>T(),O=async H=>T(H),U=H=>{try{let Z={...r.current,customUrl:n.current??void 0};return zs(Z,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(Z){return Z instanceof on?(m("malformedConfirm"),null):(l(Z instanceof Error?Z.message:"Failed to read settings.json"),m("fields"),null)}},se=()=>{let H=U(true);H&&(f(H),O(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let Z;try{Z=Do(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Z,m("customUrl");},V=H=>{n.current=H,m("email");},ne=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Dt(H),c(true),l(null),g.current+=1;try{await Zr(r.current);let Z=U(!1);Z&&(f(Z),m("preview"));}catch(Z){let A=Z instanceof Error?Z.message:"Authentication failed";l(A),Xu(E.CLI_AUTH_FAILED,{error_code:xd(Z),attempt:g.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:h,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:ne,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:se}}F();N();function vd(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:g}=Id(),[h,w]=useState("confirm"),[x,_]=useState(""),L=useRef(""),[T,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),L.current="",_(""),$(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?f():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?g():U.escape&&u();return}if(o==="customUrl"){if(h==="confirm")O==="y"||O==="Y"?w("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)L.current="",_(""),w("confirm");else if(U.return){let se=L.current.trim();se.length>0&&bn.test(se)?($(false),d(se)):se.length>0&&$(true);}else U.backspace||U.delete?(L.current=L.current.slice(0,-1),_(L.current)):O&&!U.ctrl&&!U.meta&&(L.current=L.current+O,_(L.current),$(false));return}o!=="email"&&U.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:x}),jsx(Text,{color:"cyan",children:"\u2588"})]}),T&&jsx(Text,{color:"red",children:xn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(nd,{onConfirm:m})]}):o==="preview"&&s?jsx(od,{plan:s}):o==="malformedConfirm"?jsx(sd,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[wr," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:jsx(Box,{marginBottom:1,children:jsx(rd,{label:"JWT",value:e,onChange:O=>{a(O),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Dn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(lS,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ye]})})]})}var Cd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ae=Rr()?Cd:Cd.slice(0,3);function cS(e){return ae.findIndex(t=>t.id===e)}function hl(e,t,r){let n=cS(r.activeTab);if(t.rightArrow||t.tab){let o=ae[(n+1)%ae.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ae[(n-1+ae.length)%ae.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ae[n]?.focus??"list"}]:[]}var Rd={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function $d({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ae.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Rd[r]} (${e})`:Rd[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ye=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Md(){let e=S(i=>i.focus),t=Ye(i=>i.query),r=Ye(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..."})]})}F();var Ld=Object.keys(br).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...br[e]})),Dd=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...gu[e]}));function Od(){let e=S(n=>n.catalogFilters),t=Ld.every(n=>e.types.has(n.type)),r=Dd.every(n=>e.origins.has(n.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",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"]})]}),Ld.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"]})]}),Dd.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)})]})}F();function Nd({type:e}){let{label:t,color:r}=br[e];return jsx(Text,{color:r,children:t})}F();function Fd({origin:e}){return e===So?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ai=gS.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(Nd,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Fd,{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 ",Lt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function On({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Hd({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(On,{message:t});let n=Math.max(0,r-Math.floor(st/2)),o=Math.min(e.length,n+st);o===e.length&&(n=Math.max(0,o-st));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(ai,{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 Jd({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}F();function zd({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(On,{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(st/2)),u=Math.min(n.length,l+st);u===n.length&&(l=Math.max(0,u-st));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Jd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ai,{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 vS={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ES({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Md,{}),jsx(Od,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:vS[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(zd,{groups:n,emptyMessage:r}):jsx(Hd,{items:e,emptyMessage:r})]})}function Xd({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(ES,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var CS={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 li(){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:[CS[e],t?" | Ctrl+D: debug log":""]})})}N();function qd({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ci({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Dr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var ep=20;function Un(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*ep),s="\u2588".repeat(o)+"\u2591".repeat(ep-o),i=`${Dr(e)} / ${Dr(t)}`;return {bar:s,percent:n,label:i}}function ui({received:e,total:t}){let{bar:r,percent:n,label:o}=Un(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function di({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 ct({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))})]})}F();var Tl=Object.entries(Xe),op=[...Tl.map(([,e])=>e.actionLabel),"Cancel"],sp=Object.fromEntries(Tl.map(([,e])=>[e.actionLabel,e.description]));function ip(e){let t=Tl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var KS=b("provider.registry"),HS=3e4,mi=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()+HS}),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"&&KS.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 VS={user:"global",project:"project",local:"local"};function fi(e){return e?VS[e]:"global"}var Ze=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},Or=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};Fo();Cl();R();var WS=b("catalog.registry"),gi=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);WS.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()]}};$e();var tb={retries:5,minTimeout:50};async function kl(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:tb});try{return await t()}finally{await r();}}var hi=class{filePath;constructor(t){this.filePath=t??bu();}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 kl(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 kl(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await kl(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));});}};Rl();var le=new gi,or=new hi,db=["flow-harness"];function pb(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?db:e.split(",").map(t=>t.trim()).filter(Boolean)}le.register(new Vn);for(let e of pb())le.register(new Vn(e));var wp=false;async function Sp(){if(wp)return;wp=true;let e=await or.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>($l(),yp));for(let r of e)le.register(new t(r.id,r.name,r.source));}Nr();function bp(e){if(e===void 0||!Number.isFinite(e)||e<=0)return 3e4;let t=e/131072*1e3;return Math.min(6e5,Math.max(3e4,Math.ceil(t)))}R();var fb=b("api:actions"),xp=2;async function sr(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Rl(),dp));return new t(e).fetchItems()}return le.fetchAll()}async function Ip(){return le.fetchAllWithErrors()}async function Jn(e,t){jo(e);try{return await Bn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Fn(r);throw n?new Error(n,{cause:r}):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`,{cause:r}):r.message.includes("timeout")?new Error("Download timed out after 30s",{cause:r}):new Error(`Failed to fetch plugin manifest: ${r.message}`,{cause:r}):r}}async function gb(e,t){try{let n=(await lp(`v1/plugins/${e}/archive`,{source:t,timeoutMs:3e4})).headers.get("x-archive-size"),o=n?Number(n):NaN;return Number.isFinite(o)&&o>0?o:void 0}catch(r){fb.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function vp(e,t,r){jo(e);try{let n=await gb(e,r),o=bp(n),s=await Bn(`v1/plugins/${e}/archive`,r,o),i=s.headers.get("x-archive-size"),a=i?Number(i):NaN,l=Number.isFinite(a)&&a>0?a:0,u=l>0,c=s.body;if(!c)throw new Error("Failed to download plugin: response has no body");let d=c.getReader(),m=[],p=0;for(;;){let{done:f,value:g}=await d.read();if(f)break;if(p+=g.byteLength,u&&p>l*xp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*xp}`);m.push(g),u&&t?.(p,l);}return Buffer.concat(m)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await Fn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function wi(){try{let{profiles:e}=await Kt().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",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}$e();$e();async function Ep(e,t){let r=W.resolve(t);await Ht.mkdir(r,{recursive:true});let n=W.join(W.dirname(r),`${randomUUID()}.zip`);try{await Ht.writeFile(n,e);let o=await yb.Open.file(n),s=W.normalize(r+W.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=W.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(W.resolve(W.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ht.unlink(n);}catch{}}}async function _l(e){await Ht.rm(e,{recursive:true,force:true});}async function ir(){let e=wu();await Ht.mkdir(W.dirname(e),{recursive:true});try{await Ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Bw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}$e();F();R();var xb=b("marketplace-registry");function Ib(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||Ue,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Tp(e){let t=xo(e);if(!ue__default.existsSync(t))return null;try{return JSON.parse(ue__default.readFileSync(t,"utf-8"))}catch{return null}}function vb(e){let t=Tp(e);if(t)return t;let r=Ib(e),n=xo(e);return ue__default.mkdirSync(W__default.dirname(n),{recursive:true}),Dl(r,e),r}function Dl(e,t){let r=xo(t),n=`${r}.${randomUUID()}.tmp`;ue__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(n,r);}function Eb(e){let t=e||Ue,r=Wr(),n={};try{ue__default.existsSync(r)&&(n=JSON.parse(ue__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:_a(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;ue__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(o,r);}async function Ml(e,t){let r=_a(e),n=W__default.relative(r,xo(e));try{let o=simpleGit({baseDir:r,timeout:{block:1e4}});if((await o.status()).files.length===0)return;await o.add([n,"plugins/native/"]),await o.commit(t);}catch(o){xb.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function Cp(e,t,r){Le(e.name),Eb(r);let n=$a(e.name,r);ue__default.mkdirSync(W__default.dirname(n),{recursive:true});try{ue__default.lstatSync(n),ue__default.rmSync(n,{recursive:!0,force:!0});}catch{}ue__default.cpSync(t,n,{recursive:true,dereference:true});let o=vb(r);o.plugins.some(i=>i.name===e.name)||(o.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Dl(o,r)),await Ml(r,`chore: register ${e.name}@${e.version}`);}async function kp(e,t){Le(e);let r=$a(e,t);try{ue__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=Tp(t);if(!n){await Ml(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Dl(n,t),await Ml(t,`chore: unregister ${e}`);}N();R();var Tb=b("mcpConfigReader"),Cb=500,kb=512;function Ab(){return W__default.join(Se__default.homedir(),".claude.json")}function Rb(){return W__default.join(process.cwd(),".mcp.json")}function Rp(e){if(!ue__default.existsSync(e))return null;try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return Tb.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ko(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ol(e){if(!Ko(e))return {};let t=e.mcpServers;return Ko(t)?t:{}}function Nl(e,t){return Object.keys(e).slice(0,Cb).map(n=>({name:y(n.slice(0,kb)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function _p(){let e=[],t=Ab(),r=Rp(t);if(Ko(r)){let a=r,l=Ol(a);e.push(...Nl(l,"user"));let u=process.cwd();if(Ko(a.projects)){let c=a.projects[u];if(Ko(c)){let d=Ol(c);e.push(...Nl(d,"local"));}}}let n=Rb(),o=Rp(n),s=Ol(o);e.push(...Nl(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}R();F();function Ho(e,t){let r=join(e,".gitignore");if(!existsSync(r)){writeFileSync(r,`${t}
111
111
  `,"utf8");return}let n=readFileSync(r,"utf8");n.split(`
112
112
  `).some(s=>s.trim()===t)||appendFileSync(r,`${n.endsWith(`
113
113
  `)?"":`
114
114
  `}${t}
115
- `,"utf8");}function Wn(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Wn(r)]))}function zn(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(Wn(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Wn(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=zn(s,o):r[n]=o;}return r}function Nl(e,t,r){let n={...e};for(let[o,s]of Object.entries(t)){let i=n[o];if(Array.isArray(s)&&Array.isArray(i)){let a=new Set(s.map(d=>JSON.stringify(Wn(d)))),l=r[o],u=new Set(Array.isArray(l)?l.map(d=>JSON.stringify(Wn(d))):[]),c=i.filter(d=>{let m=JSON.stringify(Wn(d));return !a.has(m)||u.has(m)});c.length>0?n[o]=c:delete n[o];}else if(s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)){let a=r[o],l=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:{},u=Nl(i,s,l);Object.keys(u).length>0?n[o]=u:delete n[o];}else i===s&&r[o]!==s&&delete n[o];}return n}R();var Si=b("bundleContent"),Ob="${CLAUDE_PLUGIN_ROOT}";function Nb(e,t){return t.split(Ob).join(e)}function Ub(e){let t=Se__default.homedir();return e===t||e.startsWith(`${t}/`)?`$HOME${e.slice(t.length)}`:e}function Bb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.type==="command"&&typeof e.command=="string"}function Lp(e,t){return typeof t=="string"?Nb(e,t):Array.isArray(t)?t.map(r=>Lp(e,r)):t}function Ul(e,t,r){if(Array.isArray(r))return r.map(n=>Ul(e,t,n));if(Bb(r)){let n="args"in r?e:t;return Object.fromEntries(Object.entries(r).map(([o,s])=>[o,Lp(n,s)]))}return r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,Ul(e,t,o)])):r}function Bl(e){let t=W__default.join(e,"hooks","hooks.json");if(!ue__default.existsSync(t))return null;let r;try{r=JSON.parse(ue__default.readFileSync(t,"utf-8"));}catch(o){return Si.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(o)}`),null}let n=r.hooks;return !n||typeof n!="object"||Array.isArray(n)?null:n}function Fl(e,t,r){let n=t==="user"?e:Ub(e);return Ul(e,n,r)}function jl(e){return e.hooks!==null&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{}}function Fb(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function jb(e,t){if(t==="user")return;let r=Se__default.homedir(),n=W__default.dirname(e);if(!(n===r||n.startsWith(`${r}${W__default.sep}`)))return;let s=mn(t),i=jl(s),a=0,l={};for(let[c,d]of Object.entries(i)){if(!Fb(d)){l[c]=d;continue}let m=d.map(p=>{if(!Array.isArray(p.hooks))return p;let f=p.hooks.filter(g=>{if(g===null||typeof g!="object"||Array.isArray(g))return true;let{command:h,args:w}=g,x=typeof h=="string"&&h.includes(n)||Array.isArray(w)&&w.some(_=>typeof _=="string"&&_.includes(n));return x&&a++,!x});return {...p,hooks:f}}).filter(p=>!Array.isArray(p.hooks)||p.hooks.length>0);m.length>0&&(l[c]=m);}if(a===0)return;Xn({...s,hooks:l},t);let u=t==="project"?".claude/settings.json":".claude/settings.local.json";Si.info(`Removed ${a} stale hook command(s) an older CLI version wrote as a literal, machine-specific path in ${u} \u2014 the portable ($HOME) form is registered right after this.`);}function Kb(e,t){let r=Bl(e);if(!r)return;jb(e,t);let n=Fl(e,t,r),o=mn(t),s=zn(jl(o),n);Xn({...o,hooks:s},t),Si.debug(`Registered hooks from ${W__default.join(e,"hooks","hooks.json")}, pointing at ${e} (scope: ${t})`);}function Hb(e,t,r){let n=Bl(e);if(!n)return;let o=Fl(e,t,n),s=r.filter(l=>l.scope===t).reduce((l,u)=>{let c=Bl(u.installPath);return c?zn(l,Fl(u.installPath,t,c)):l},{}),i=mn(t),a=Nl(jl(i),o,s);Xn({...i,hooks:a},t),Si.debug(`Removed hooks from ${W__default.join(e,"hooks","hooks.json")} (scope: ${t})`);}function bi(e,t){Kb(e,t);}function Dp(e,t,r){Hb(e,t,r);}var Ke=b("storage");async function Gb(e,t,r){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:ee().interfaceType});}catch(n){Ke.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Jb(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:ee().interfaceType}).catch(o=>Ke.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Gl(){return W__default.join(Se__default.homedir(),".claude","plugins","installed_plugins.json")}function Np(){return W__default.join(Se__default.homedir(),".claude","plugins")}function Hl(e){let t;try{t=ue__default.realpathSync(e);}catch{t=W__default.resolve(e);}let r=W__default.resolve(Np()),n=W__default.resolve(W__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+W__default.sep),s=t.startsWith(n+W__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Up(e="user"){return e==="local"?W__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?W__default.join(process.cwd(),".claude","settings.json"):W__default.join(Se__default.homedir(),".claude","settings.json")}function Te(){let e=Gl();if(!ue__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Jl(){let e=Gl();try{let t=await ue__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Wb(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Bp(e,t){try{ue__default.mkdirSync(W__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ue__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,e);}catch(r){throw Wb(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function ut(e){Bp(Gl(),e);}function fn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function zb(e,t){let r=W__default.join(e,".claude-plugin"),n=W__default.join(r,"plugin.json");if(ue__default.existsSync(n))try{return JSON.parse(ue__default.readFileSync(n,"utf-8"))}catch{return null}let o=W__default.join(r,"marketplace.json");if(ue__default.existsSync(o))try{let s=JSON.parse(ue__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function mn(e="user"){let t=Up(e);if(!ue__default.existsSync(t))return {};try{return JSON.parse(ue__default.readFileSync(t,"utf-8"))}catch{return {}}}function Xn(e,t="user"){Bp(Up(t),e),t==="local"&&Ho(process.cwd(),".claude/settings.local.json");}function Xb(e,t){let{name:r,marketplace:n}=fn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>fn(i).name===r)[0],!o)throw Ke.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function qb(e,t){let{name:r,marketplace:n}=fn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>fn(i).name===r)[0],o?{key:o,name:r}:null}function Kl(e="user"){return mn(e).enabledPlugins??{}}function Op(e,t="user"){let r=mn(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Xn(r,t);}function Go(e,t,r="user"){let n=mn(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Xn(n,r);}function Yb(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function Wl(e,t,r){return t?t==="user"?e.find(n=>n.scope==="user"):e.find(n=>n.scope===t&&n.projectPath===r)??e.find(n=>n.scope===t):e.find(n=>n.projectPath===r)??e.find(n=>n.scope==="user")}function Zb(e,t,r){let n=[];for(let[o,s]of Object.entries(e))for(let i of s)o===t&&i===r||n.push({installPath:i.installPath,scope:i.scope});return n}function fe(){let e=Te(),t=Kl(),r=Kl("project"),n=Kl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=fn(u),p=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Yb(p).map(g=>{let h=zb(g.installPath,d),x=(o[g.scope]??t)[u];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,projectPath:g.projectPath,description:h?.description,author:h?.author,status:x===false?"disabled":"enabled"}})}),i=$p(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Qb(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Jo(e,t){Ke.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=Te(),o=qb(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],l=t??"user",u=Wl(a,l,process.cwd());if(!u)throw new Error(t?`Plugin '${i}' is not installed in ${t} scope`:`Plugin '${i}' is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`);Ke.debug(`[${i}] Resolved key: ${s}, scope: ${l}`);let c=W__default.dirname(u.installPath),d=a.filter(p=>p!==u);if(Dp(u.installPath,l,Zb(n.plugins,s,u)),d.some(p=>W__default.dirname(p.installPath)===c)?Ke.debug(`[${i}] Directory still used by another scope, keeping: ${c}`):(Hl(u.installPath),Hl(c),Ke.debug(`[${i}] Removing directory: ${c}`),ue__default.rmSync(c,{recursive:!0,force:!0})),d.length===0){let{[s]:p,...f}=n.plugins;ut({...n,plugins:f}),Op(s,l),await Cp(i,Qb(s));}else n.plugins[s]=d,ut(n),Op(s,l);await Gb(i,u.origin??"internal",u.type??"skill"),Ke.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Wo(e,t,r){Ke.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=Te(),{key:s,name:i}=Xb(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";Ke.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Go(s,t==="enabled",l),Jb(i,t,u),Ke.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var ex=/^\d+$/;function tx(e){let t=W__default.join(e,".in_use"),r;try{r=ue__default.readdirSync(t);}catch{return false}for(let n of r){if(!ex.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var rx=20;function Fp(e,t=0){if(t>rx)return 0;let r=0,n;try{n=ue__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=W__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=Fp(s,t+1);else if(o.isFile())try{r+=ue__default.statSync(s).size;}catch{}}}return r}function nx(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=fn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.projectPath&&!ue__default.existsSync(l.projectPath)||l.version&&a.add(l.version);r.set(s,a);}return r}function jp(){let e=Te(),t=[];for(let r of Sr){let n=nx(e,r),o=W__default.join(Np(),"cache",r),s;try{s=ue__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=W__default.join(o,a),u=n.get(a)??new Set,c;try{c=ue__default.readdirSync(l,{withFileTypes:!0});}catch{continue}for(let d of c){if(!d.isDirectory())continue;let m=d.name;if(u.has(m))continue;let p=W__default.join(l,m);tx(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:Fp(p)});}}}return t}async function Kp(e){let t=await sr(),r=[],n=[];try{for(let s of e)try{Hl(s.path),ue__default.rmSync(s.path,{recursive:!0,force:!0}),r.push(s),Ke.debug(`[${s.pluginName}@${s.version}] Pruned ${s.path}`);}catch(i){n.push({candidate:s,error:i instanceof Error?i.message:String(i)}),Ke.warn(`[${s.pluginName}@${s.version}] Prune failed: ${String(i)}`);}}finally{await t();}let o=r.reduce((s,i)=>s+i.sizeBytes,0);return await P(E.CLI_PLUGIN_PRUNE_COMPLETED,{removed_count:r.length,failed_count:n.length,freed_bytes:o,interface:ee().interfaceType}).catch(s=>Ke.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}function Hp(){let e=Te(),t=[];for(let[r,n]of Object.entries(e.plugins)){let{name:o,marketplace:s}=fn(r);for(let i of n)i.projectPath&&!ue__default.existsSync(i.projectPath)&&t.push({key:r,pluginName:o,marketplace:s,scope:i.scope,projectPath:i.projectPath});}return t}function Vp(e){if(e.length===0)return;let t=new Set(e.map(n=>`${n.key}::${n.projectPath}`)),r=Te();for(let[n,o]of Object.entries(r.plugins)){let s=o.filter(i=>!i.projectPath||!t.has(`${n}::${i.projectPath}`));s.length===0?delete r.plugins[n]:r.plugins[n]=s;}ut(r);}F();R();var ox=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,sx=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Le(e){if(!ox.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function ix(e){if(!sx.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 Ur=b("installer");function ax(e,t,r,n){let o=`${e}@${n||Ue}`,i=Te().plugins[o],a=i?.find(l=>r==="user"?l.scope==="user":l.scope===r&&l.projectPath===process.cwd());if(a&&!t)throw new Ze(e,a.version??"unknown");return {pluginKey:o,alreadyInstalled:i}}async function lx(e,t,r){r&&await $l(t);try{Ur.debug(`[${t}] Extracting archive...`),await vp(e,t);}catch(n){throw await $l(t),n}}function cx(e,t,r,n,o,s="claude-code",i){let a=Te(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>!(c.scope===n&&c.projectPath===l.projectPath)),l],ut(a),Go(e,true,n);}async function ux(e,t,r,n,o,s){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:ee().interfaceType});}catch(i){Ur.warn(`Failed to send install metrics: ${String(i)}`);}}async function dx(e,t,r,n){try{await P(E.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:ee().interfaceType});}catch(o){Ur.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function He(e,t={}){let r=Date.now(),n=null;try{Ur.debug(`[${e}] Acquiring lock...`),n=await sr();let o=t.scope??"user",{pluginKey:s,alreadyInstalled:i}=ax(e,t.force,o,t.source),{source:a}=t;Ur.debug(`[${e}] Fetching manifest...`);let l=await Jn(e,a);Le(l.name),ix(l.version),Ur.debug(`[${e}] Downloading archive...`);let u=await Ip(e,t.onDownloadProgress,a),c=t.type??"skill",d=hu(l.name,l.version,t.source);await lx(u,d,!!i&&!!t.force),await bi(d,o),cx(s,d,l.version,o,"internal",t.providerId,c),await Tp(l,d,t.source);let m=Date.now()-r;Ur.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:l.name,version:l.version,path:d,duration_ms:m};return t.skipMetrics||await ux(l.name,l.version,m,fi(o),"internal",c),p}catch(o){throw await dx(e,o,"internal",t.type??"skill"),Ur.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Ce();Rn();R();N();var px="\x1B[A",mx="\x1B[B";function Gp(e,t,r){let n=t?C.cyan("\u276F"):" ",o=r?C.cyan("[x]"):"[ ]",s=t?C.cyan(e.label):e.label;return ` ${n} ${o} ${s}`}function fx(e,t,r){return e.map((n,o)=>Gp(n,o===t,r.has(o))).join(`
116
- `)}async function Xl(e,t){if(t.length===0)throw new Error("multiSelectPrompt requires at least one option");return new Promise((r,n)=>{let o=0,s=new Set;process.stdout.write(`${y(e)} (space to toggle, enter to confirm)
115
+ `,"utf8");}function Wn(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,Wn(r)]))}function zn(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(Wn(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Wn(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=zn(s,o):r[n]=o;}return r}function Ul(e,t,r){let n={...e};for(let[o,s]of Object.entries(t)){let i=n[o];if(Array.isArray(s)&&Array.isArray(i)){let a=new Set(s.map(d=>JSON.stringify(Wn(d)))),l=r[o],u=new Set(Array.isArray(l)?l.map(d=>JSON.stringify(Wn(d))):[]),c=i.filter(d=>{let m=JSON.stringify(Wn(d));return !a.has(m)||u.has(m)});c.length>0?n[o]=c:delete n[o];}else if(s!==null&&typeof s=="object"&&!Array.isArray(s)&&i!==null&&typeof i=="object"&&!Array.isArray(i)){let a=r[o],l=a!==null&&typeof a=="object"&&!Array.isArray(a)?a:{},u=Ul(i,s,l);Object.keys(u).length>0?n[o]=u:delete n[o];}else i===s&&r[o]!==s&&delete n[o];}return n}R();var Si=b("bundleContent"),Ob="${CLAUDE_PLUGIN_ROOT}";function Nb(e,t){return t.split(Ob).join(e)}function Ub(e){let t=Se__default.homedir();return e===t||e.startsWith(`${t}/`)?`$HOME${e.slice(t.length)}`:e}function Bb(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.type==="command"&&typeof e.command=="string"}function Dp(e,t){return typeof t=="string"?Nb(e,t):Array.isArray(t)?t.map(r=>Dp(e,r)):t}function Bl(e,t,r){if(Array.isArray(r))return r.map(n=>Bl(e,t,n));if(Bb(r)){let n="args"in r?e:t;return Object.fromEntries(Object.entries(r).map(([o,s])=>[o,Dp(n,s)]))}return r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,o])=>[n,Bl(e,t,o)])):r}function Fl(e){let t=W__default.join(e,"hooks","hooks.json");if(!ue__default.existsSync(t))return null;let r;try{r=JSON.parse(ue__default.readFileSync(t,"utf-8"));}catch(o){return Si.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(o)}`),null}let n=r.hooks;return !n||typeof n!="object"||Array.isArray(n)?null:n}function jl(e,t,r){let n=t==="user"?e:Ub(e);return Bl(e,n,r)}function Kl(e){return e.hooks!==null&&typeof e.hooks=="object"&&!Array.isArray(e.hooks)?e.hooks:{}}function Fb(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function jb(e,t){if(t==="user")return;let r=Se__default.homedir(),n=W__default.dirname(e);if(!(n===r||n.startsWith(`${r}${W__default.sep}`)))return;let s=mn(t),i=Kl(s),a=0,l={};for(let[c,d]of Object.entries(i)){if(!Fb(d)){l[c]=d;continue}let m=d.map(p=>{if(!Array.isArray(p.hooks))return p;let f=p.hooks.filter(g=>{if(g===null||typeof g!="object"||Array.isArray(g))return true;let{command:h,args:w}=g,x=typeof h=="string"&&h.includes(n)||Array.isArray(w)&&w.some(_=>typeof _=="string"&&_.includes(n));return x&&a++,!x});return {...p,hooks:f}}).filter(p=>!Array.isArray(p.hooks)||p.hooks.length>0);m.length>0&&(l[c]=m);}if(a===0)return;Xn({...s,hooks:l},t);let u=t==="project"?".claude/settings.json":".claude/settings.local.json";Si.info(`Removed ${a} stale hook command(s) an older CLI version wrote as a literal, machine-specific path in ${u} \u2014 the portable ($HOME) form is registered right after this.`);}function Kb(e,t){let r=Fl(e);if(!r)return;jb(e,t);let n=jl(e,t,r),o=mn(t),s=zn(Kl(o),n);Xn({...o,hooks:s},t),Si.debug(`Registered hooks from ${W__default.join(e,"hooks","hooks.json")}, pointing at ${e} (scope: ${t})`);}function Hb(e,t,r){let n=Fl(e);if(!n)return;let o=jl(e,t,n),s=r.filter(l=>l.scope===t).reduce((l,u)=>{let c=Fl(u.installPath);return c?zn(l,jl(u.installPath,t,c)):l},{}),i=mn(t),a=Ul(Kl(i),o,s);Xn({...i,hooks:a},t),Si.debug(`Removed hooks from ${W__default.join(e,"hooks","hooks.json")} (scope: ${t})`);}function bi(e,t){Kb(e,t);}function xi(e,t,r){Hb(e,t,r);}var Ke=b("storage");async function Gb(e,t,r){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:ee().interfaceType});}catch(n){Ke.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Jb(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:ee().interfaceType}).catch(o=>Ke.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Jl(){return W__default.join(Se__default.homedir(),".claude","plugins","installed_plugins.json")}function Np(){return W__default.join(Se__default.homedir(),".claude","plugins")}function Vl(e){let t;try{t=ue__default.realpathSync(e);}catch{t=W__default.resolve(e);}let r=W__default.resolve(Np()),n=W__default.resolve(W__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+W__default.sep),s=t.startsWith(n+W__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Up(e="user"){return e==="local"?W__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?W__default.join(process.cwd(),".claude","settings.json"):W__default.join(Se__default.homedir(),".claude","settings.json")}function xe(){let e=Jl();if(!ue__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ue__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Wl(){let e=Jl();try{let t=await ue__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Wb(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Bp(e,t){try{ue__default.mkdirSync(W__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ue__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(r,e);}catch(r){throw Wb(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function ut(e){Bp(Jl(),e);}function fn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function zb(e,t){let r=W__default.join(e,".claude-plugin"),n=W__default.join(r,"plugin.json");if(ue__default.existsSync(n))try{return JSON.parse(ue__default.readFileSync(n,"utf-8"))}catch{return null}let o=W__default.join(r,"marketplace.json");if(ue__default.existsSync(o))try{let s=JSON.parse(ue__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function mn(e="user"){let t=Up(e);if(!ue__default.existsSync(t))return {};try{return JSON.parse(ue__default.readFileSync(t,"utf-8"))}catch{return {}}}function Xn(e,t="user"){Bp(Up(t),e),t==="local"&&Ho(process.cwd(),".claude/settings.local.json");}function Xb(e,t){let{name:r,marketplace:n}=fn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>fn(i).name===r)[0],!o)throw Ke.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function qb(e,t){let{name:r,marketplace:n}=fn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>fn(i).name===r)[0],o?{key:o,name:r}:null}function Hl(e="user"){return mn(e).enabledPlugins??{}}function Op(e,t="user"){let r=mn(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Xn(r,t);}function Go(e,t,r="user"){let n=mn(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Xn(n,r);}function Yb(e){let t=new Map;for(let r of e){let n=r.projectPath?`${r.scope}:${r.projectPath}`:r.scope,o=t.get(n);(!o||r.installedAt>o.installedAt)&&t.set(n,r);}return [...t.values()]}function zl(e,t,r){return t?t==="user"?e.find(n=>n.scope==="user"):e.find(n=>n.scope===t&&n.projectPath===r)??e.find(n=>n.scope===t):e.find(n=>n.projectPath===r)??e.find(n=>n.scope==="user")}function Zb(e,t,r){let n=[];for(let[o,s]of Object.entries(e))for(let i of s)o===t&&i===r||n.push({installPath:i.installPath,scope:i.scope});return n}function fe(){let e=xe(),t=Hl(),r=Hl("project"),n=Hl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=fn(u),p=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Yb(p).map(g=>{let h=zb(g.installPath,d),x=(o[g.scope]??t)[u];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,projectPath:g.projectPath,description:h?.description,author:h?.author,status:x===false?"disabled":"enabled"}})}),i=_p(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Qb(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Jo(e,t){Ke.debug(`[${e}] Acquiring lock to uninstall`);let r=await ir();try{let n=xe(),o=qb(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],l=t??"user",u=zl(a,l,process.cwd());if(!u)throw new Error(t?`Plugin '${i}' is not installed in ${t} scope`:`Plugin '${i}' is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`);Ke.debug(`[${i}] Resolved key: ${s}, scope: ${l}`);let c=W__default.dirname(u.installPath),d=a.filter(p=>p!==u);if(xi(u.installPath,l,Zb(n.plugins,s,u)),d.some(p=>W__default.dirname(p.installPath)===c)?Ke.debug(`[${i}] Directory still used by another scope, keeping: ${c}`):(Vl(u.installPath),Vl(c),Ke.debug(`[${i}] Removing directory: ${c}`),ue__default.rmSync(c,{recursive:!0,force:!0})),d.length===0){let{[s]:p,...f}=n.plugins;ut({...n,plugins:f}),Op(s,l),await kp(i,Qb(s));}else n.plugins[s]=d,ut(n),Op(s,l);await Gb(i,u.origin??"internal",u.type??"skill"),Ke.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Wo(e,t,r){Ke.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await ir();try{let o=xe(),{key:s,name:i}=Xb(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";Ke.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Go(s,t==="enabled",l),Jb(i,t,u),Ke.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var ex=/^\d+$/;function tx(e){let t=W__default.join(e,".in_use"),r;try{r=ue__default.readdirSync(t);}catch{return false}for(let n of r){if(!ex.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var rx=20;function Fp(e,t=0){if(t>rx)return 0;let r=0,n;try{n=ue__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=W__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=Fp(s,t+1);else if(o.isFile())try{r+=ue__default.statSync(s).size;}catch{}}}return r}function nx(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=fn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.projectPath&&!ue__default.existsSync(l.projectPath)||l.version&&a.add(l.version);r.set(s,a);}return r}function jp(){let e=xe(),t=[];for(let r of Sr){let n=nx(e,r),o=W__default.join(Np(),"cache",r),s;try{s=ue__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=W__default.join(o,a),u=n.get(a)??new Set,c;try{c=ue__default.readdirSync(l,{withFileTypes:!0});}catch{continue}for(let d of c){if(!d.isDirectory())continue;let m=d.name;if(u.has(m))continue;let p=W__default.join(l,m);tx(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:Fp(p)});}}}return t}async function Kp(e){let t=await ir(),r=[],n=[];try{for(let s of e)try{Vl(s.path),ue__default.rmSync(s.path,{recursive:!0,force:!0}),r.push(s),Ke.debug(`[${s.pluginName}@${s.version}] Pruned ${s.path}`);}catch(i){n.push({candidate:s,error:i instanceof Error?i.message:String(i)}),Ke.warn(`[${s.pluginName}@${s.version}] Prune failed: ${String(i)}`);}}finally{await t();}let o=r.reduce((s,i)=>s+i.sizeBytes,0);return await P(E.CLI_PLUGIN_PRUNE_COMPLETED,{removed_count:r.length,failed_count:n.length,freed_bytes:o,interface:ee().interfaceType}).catch(s=>Ke.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}function Hp(){let e=xe(),t=[];for(let[r,n]of Object.entries(e.plugins)){let{name:o,marketplace:s}=fn(r);for(let i of n)i.projectPath&&!ue__default.existsSync(i.projectPath)&&t.push({key:r,pluginName:o,marketplace:s,scope:i.scope,projectPath:i.projectPath});}return t}function Vp(e){if(e.length===0)return;let t=new Set(e.map(n=>`${n.key}::${n.projectPath}`)),r=xe();for(let[n,o]of Object.entries(r.plugins)){let s=o.filter(i=>!i.projectPath||!t.has(`${n}::${i.projectPath}`));s.length===0?delete r.plugins[n]:r.plugins[n]=s;}ut(r);}F();R();var ox=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,sx=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function Le(e){if(!ox.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function ix(e){if(!sx.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 Ur=b("installer");function ax(e,t,r,n){let o=`${e}@${n||Ue}`,i=xe().plugins[o],a=i?.find(l=>r==="user"?l.scope==="user":l.scope===r&&l.projectPath===process.cwd());if(a&&!t)throw new Ze(e,a.version??"unknown");return {pluginKey:o,alreadyInstalled:i}}async function lx(e,t,r){r&&await _l(t);try{Ur.debug(`[${t}] Extracting archive...`),await Ep(e,t);}catch(n){throw await _l(t),n}}function cx(e,t,r,n,o,s="claude-code",i){let a=xe(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>!(c.scope===n&&c.projectPath===l.projectPath)),l],ut(a),Go(e,true,n);}async function ux(e,t,r,n,o,s){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:ee().interfaceType});}catch(i){Ur.warn(`Failed to send install metrics: ${String(i)}`);}}async function dx(e,t,r,n){try{await P(E.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:ee().interfaceType});}catch(o){Ur.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function He(e,t={}){let r=Date.now(),n=null;try{Ur.debug(`[${e}] Acquiring lock...`),n=await ir();let o=t.scope??"user",{pluginKey:s,alreadyInstalled:i}=ax(e,t.force,o,t.source),{source:a}=t;Ur.debug(`[${e}] Fetching manifest...`);let l=await Jn(e,a);Le(l.name),ix(l.version),Ur.debug(`[${e}] Downloading archive...`);let u=await vp(e,t.onDownloadProgress,a),c=t.type??"skill",d=yu(l.name,l.version,t.source);await lx(u,d,!!i&&!!t.force),await bi(d,o),cx(s,d,l.version,o,"internal",t.providerId,c),await Cp(l,d,t.source);let m=Date.now()-r;Ur.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:l.name,version:l.version,path:d,duration_ms:m};return t.skipMetrics||await ux(l.name,l.version,m,fi(o),"internal",c),p}catch(o){throw await dx(e,o,"internal",t.type??"skill"),Ur.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Ce();Rn();R();N();var px="\x1B[A",mx="\x1B[B";function Gp(e,t,r){let n=t?C.cyan("\u276F"):" ",o=r?C.cyan("[x]"):"[ ]",s=t?C.cyan(e.label):e.label;return ` ${n} ${o} ${s}`}function fx(e,t,r){return e.map((n,o)=>Gp(n,o===t,r.has(o))).join(`
116
+ `)}async function ql(e,t){if(t.length===0)throw new Error("multiSelectPrompt requires at least one option");return new Promise((r,n)=>{let o=0,s=new Set;process.stdout.write(`${y(e)} (space to toggle, enter to confirm)
117
117
  `),process.stdout.write(fx(t,o,s));let i="",a=d=>{if(i+=d,i===""){u(),n(new Error("SIGINT"));return}if(i==="\r"||i===`
118
118
  `){u(),process.stdout.write(`
119
119
  `),r(t.filter((m,p)=>s.has(p)).map(m=>m.value));return}if(i===" "){s.has(o)?s.delete(o):s.add(o),l(),i="";return}if(i===px){o=(o-1+t.length)%t.length,l(),i="";return}if(i===mx){o=(o+1)%t.length,l(),i="";return}i.startsWith("\x1B")&&i.length<3||(i="");};function l(){process.stdout.write(`\x1B[${t.length-1}A`);for(let d=0;d<t.length;d++)process.stdout.write(`\r\x1B[2K${Gp(t[d],d===o,s.has(d))}`),d<t.length-1&&process.stdout.write(`
120
- `);}function u(){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.exit(1);}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);})}var gx=b("commands:helpers");async function Y(){let e=await re();if(!e)return v("Not authenticated. Run: flow auth login"),false;e.customUrl&&Dt(e.customUrl);try{await Nt();}catch(t){return gx.debug(`Token validation failed: ${String(t)}`),v("Session expired. Run: flow auth login"),false}return true}async function X(e){let t=Yl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function qn(e){let t=Yl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var hx="\x1B[A",yx="\x1B[B";function Jp(e,t){let r=t?C.cyan("\u276F"):" ",n=t?C.cyan(e.label):e.label,o=e.description?C.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function wx(e,t){return e.map((r,n)=>Jp(r,n===t)).join(`
121
- `)}async function xi(e,t){if(t.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((r,n)=>{let o=0;process.stdout.write(`${y(e)}
120
+ `);}function u(){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.exit(1);}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);})}var gx=b("commands:helpers");async function Y(){let e=await re();if(!e)return v("Not authenticated. Run: flow auth login"),false;e.customUrl&&Dt(e.customUrl);try{await Nt();}catch(t){return gx.debug(`Token validation failed: ${String(t)}`),v("Session expired. Run: flow auth login"),false}return true}async function X(e){let t=Zl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function qn(e){let t=Zl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var hx="\x1B[A",yx="\x1B[B";function Jp(e,t){let r=t?C.cyan("\u276F"):" ",n=t?C.cyan(e.label):e.label,o=e.description?C.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function wx(e,t){return e.map((r,n)=>Jp(r,n===t)).join(`
121
+ `)}async function Ii(e,t){if(t.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((r,n)=>{let o=0;process.stdout.write(`${y(e)}
122
122
  `),process.stdout.write(wx(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
123
123
  `){l(),process.stdout.write(`
124
124
  `),r(t[o].value);return}if(s===hx){o=(o-1+t.length)%t.length,a(),s="";return}if(s===yx){o=(o+1)%t.length,a(),s="";return}s.startsWith("\x1B")&&s.length<3||(s="");};function a(){process.stdout.write(`\x1B[${t.length-1}A`);for(let c=0;c<t.length;c++)process.stdout.write(`\r\x1B[2K${Jp(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
125
- `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}Nr();var Zn=b("claudeProxy"),tc="claude ",Wp="flow ",Zl=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Yn=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";}},Sx=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,bx=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,xx={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Ix=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,vx=/^(flow|claude)\s+auth\s+login(\s|$)/,zp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Xp(e){return zp.test(e.trim())}function Ex(e){return zp.exec(e.trim())?.[2]??""}async function qp(e){let t=Ex(e);kl(t);let r=Date.now();Zn.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 rc(n)?new Ql:n}}function Px(e){Yp(e);let t=e.slice(tc.length);if(!Sx.test(t))throw new Yn(e)}var Ii=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Ql=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Yp(e){if(!e||!/^claude /.test(e))throw new Zl(e)}function Tx(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!bx.test(r))throw new Yn(`Unexpected flag: ${r}`);let n=xx[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Yn(`Flag ${r} requires a value`);if(!n.test(o))throw new Yn(`Unsafe value for flag ${r}`);t++;}}}async function De(e){Yp(e);let t=e.slice(tc.length).split(/\s+/).filter(Boolean);Tx(t);let r=Cx(t);Zn.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 Zn.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 rc(o)?new Ii:o}}function Cx(e){return e.length>=3?e[2]:e.join(" ")}function rc(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function kx(e){return e.startsWith(Wp)?tc+e.slice(Wp.length):e}function Ax(e){return Ix.test(e)||vx.test(e)}function Rx(e){let t=0;for(;t<e.length&&Ax(e[t]);)t++;return e.slice(t)}var $x=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function _x(e,t){return !t||e.includes("--scope")||!$x.test(e)?e:`${e} --scope ${t}`}async function zo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Rx(r).map(i=>kx(i)).map(i=>_x(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Px(i);Zn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await De(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await De(o[i]),s.exitCode!==0)return s;return s}async function vi(e,t,r){let n=Kn(e),o=t?.trim();if(!o&&(o=(await qn(`Plugin "${n}" could not be installed.
126
- 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=yi(o),r?.(),Zn.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"}`);Zn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw rc(s)?new Ii:s}}Nr();F();$e();R();var Nx=6e4,Br=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 Qe(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Nx},allowEnvironment:["GIT_TERMINAL_PROMPT","GIT_LFS_SKIP_SMUDGE"]}).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 Br("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Br(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Br(`Failed to clone ${e}: ${i}`,e,false,false)}}async function et(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 Vt(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 Bx(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Fx(e){return typeof e=="object"&&e!==null&&e.source==="url"}function jx(e){return typeof e=="object"&&e!==null&&e.source==="github"}function ir(e,t){let r=e.source;if(Bx(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(Fx(r))return {cloneUrl:r.url,subPath:"."};if(jx(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function dt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Pt=b("claude-code.adapter");function Hx(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=Wr();if(!ue__default.existsSync(s))return r;try{let i=JSON.parse(ue__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 im(e,t){let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=ir(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=Hx(e.catalogId,r?.source),i=t.scope??"user",a;o?a=_a(s,e.name,"external"):a=join(zr(i==="user"?"global":"project"),e.name);let l=null;try{Le(e.name),l=await Qe(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(ue__default.existsSync(a)&&ue__default.rmSync(a,{recursive:!0,force:!0}),ue__default.mkdirSync(dirname(a),{recursive:!0}),ue__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Jl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],ut(d),Go(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Pt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await et(l).catch(()=>{});}}async function nc(e,t,r,n){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:fi(n),version:"unknown",duration_ms:t,interface:ee().interfaceType});}catch(o){Pt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function rm(e,t,r){try{await P(E.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:ee().interfaceType});}catch(n){Pt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var nm={async install(e,t){if(e.origin===Sn&&!e.installCommand&&!jn(e.name))return im(e,t);if(e.origin===Sn&&e.installCommand){let r=e.type??"skill",n=await zo(e.installCommand,t.scope);return n.exitCode===0?(await nc(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await rm(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(jn(e.name)){let r=e.type??"skill",n=Hn(e.name,t.scope);Pt.debug(`[${e.name}] Attempting install: ${n}`);let o=await De(n);if(o.exitCode===0)return await nc(e.name,o.duration_ms,r,t.scope),{success:true};Pt.debug(`[${e.name}] First attempt failed, adding marketplace`),await vi(e.name,t.marketplaceSource,()=>{});let s=await De(n);return s.exitCode===0?(await nc(e.name,s.duration_ms,r,t.scope),{success:true}):(await rm(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 He(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Pt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Jo(e,t);},getInstallPath(e,t){return ""}};function om(e){return {async install(t,r){if(t.origin===Sn&&!t.installCommand&&!jn(t.name))return im(t,r);if(!t.installCommand)try{let o=await He(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Pt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Pt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await zo(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Te(),o=`${t}@${Ue}`;if(n.plugins[o]){await Jo(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function Vx(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ue__default.existsSync(t))continue;let r=ue__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ue__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Gx(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!ue__default.existsSync(t))continue;let r=ue__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ue__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function oc(e,t,r,n){let o=await Jl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],ut(o);}var Jx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ir(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Vx(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Ps(r);ue__default.mkdirSync(l,{recursive:!0});let u=dt(e.name);if(a.length===1)ue__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=dt(basename(d,".md"));ue__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await oc(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){let r=Ps(t),n=dt(e);if(ue__default.existsSync(r))for(let a of ue__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ue__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Te(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;ut({...s,plugins:l});}else ut({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Ps(t),`${dt(e)}.md`)}},Wx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ir(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Gx(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=Ma(r);ue__default.mkdirSync(l,{recursive:!0});for(let u of a)ue__default.copyFileSync(u,join(l,basename(u)));return await oc(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return Ma(t)}},zx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ir(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!ue__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ue__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Lo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=zn(m,u);return Ws({...d,hooks:p}),await oc(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Ei=class{id="claude-code";name="Claude Code";async isAvailable(){return Vt("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:nm,plugin:nm,skill:om("skill"),mcp:om("mcp"),agent:Jx,hook:zx,rule:Wx}};function Pi(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 ""}}}function eo(e){return {async install(t,r){try{Le(t.name);}catch{return {success:false,message:"Invalid plugin name."}}let n=t.catalogId?le.getAdapter(t.catalogId):void 0,o=ir(t,n?.source);if(!o)return {success:false,message:`Cannot install "${t.name}": unsupported source format.`};let s=null;try{s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=e(r.scope??"user"),l=join(a,t.name);return ue__default.existsSync(l)&&ue__default.rmSync(l,{recursive:!0,force:!0}),ue__default.mkdirSync(a,{recursive:!0}),ue__default.cpSync(i,l,{recursive:!0}),{success:!0,message:`Installed ${t.name}`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(t,r){Le(t);let n=join(e(r),t);ue__default.existsSync(n)&&ue__default.rmSync(n,{recursive:true,force:true});},getInstallPath(t,r){return join(e(r),t)}}}$e();var qx=new Set(["gh"]),Yx=Pi(qx,"use: gh copilot mcp remove <name>"),am=eo(e=>xu(e)),Zx=eo(e=>Iu(e)),Qx=eo(e=>vu(e)),Ci=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Vt("gh",["--version"])?Vt("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user","project"]}installers={mcp:Yx,skill:am,bundle:am,agent:Zx,hook:Qx}};$e();var eI=new Set(["opencode"]),tI=Pi(eI,"use: opencode config remove mcp <name>");function rI(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(`
127
- `)}function lm(){return {async install(e,t){try{Le(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=ir(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Qe(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Es(t.scope??"user"),a=join(s,".opencode","plugins");if(ue__default.existsSync(a)){let l=ue__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/"};ue__default.mkdirSync(i,{recursive:!0}),ue__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ue__default.existsSync(l)&&ue__default.rmSync(l,{recursive:!0,force:!0}),ue__default.mkdirSync(l,{recursive:!0}),ue__default.cpSync(s,l,{recursive:!0}),ue__default.mkdirSync(i,{recursive:!0}),ue__default.writeFileSync(join(i,`${e.name}.js`),rI(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 et(o).catch(()=>{});}},async uninstall(e,t){Le(e);let r=Es(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ue__default.existsSync(n)&&ue__default.rmSync(n,{force:true}),ue__default.existsSync(o)&&ue__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Es(t),`${e}.js`)}}}var ki=class{id="opencode";name="OpenCode";async isAvailable(){return Vt("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:tI,skill:lm(),bundle:lm()}};$e();var Ai=eo(e=>Eu(e)),Ri=class{id="cursor";name="Cursor";async isAvailable(){return await Vt("cursor-agent",["--version"])||await Vt("cursor",["--version"])?true:ue__default.existsSync(join(Se__default.homedir(),".cursor"))}getSupportedScopes(){return ["user","project"]}installers={skill:Ai,bundle:Ai,agent:Ai,hook:Ai}};var Tt=new mi;Tt.register(new Ei);Rr()&&(Tt.register(new Ci),Tt.register(new ki),Tt.register(new Ri));function cm({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(()=>{Tt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let w=l.find(x=>x.name===h);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let w=sp(h);w?r(w,c):s(false);},[r,c]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(w=>w.name),"Cancel"];return jsx(ct,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ct,{itemName:`${e} \u2014 Choose scope`,actions:np,descriptions:op,onAction:f,onClose:g},"scope"):jsx(ct,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function dm({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,g)=>{g.upArrow?a(h=>Math.max(0,h-1)):g.downArrow?a(h=>Math.min(d.length-1,h+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let g=y(f.name??f.flowId),h=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",f]})},f))})]}):jsx(ct,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Mi({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")}}N();function fm({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Mi({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(ct,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function ym({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Mi({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(ct,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var no=b("bundle:installer"),wm=/already exists/i;async function mI(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Xp(t)){let r=await qp(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(wm.test(n))return;throw new Error(n)}}else {let r=await zo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(wm.test(n))return;throw new Error(n)}}}async function fI(e,t){try{await P(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){no.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function gI(e,t,r){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){no.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Sm(e,t,r,n){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){no.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function hI(e,t,r,n,o){try{await P(E.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){no.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Oi(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await fI(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){no.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await Sm(i,g,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await mI(f),u++,await gI(i,g,h),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let x=w instanceof Error?w.message:String(w);no.error(`Failed to install artifact "${g}": ${x}`),l.push({name:g,type:h,reason:x}),await Sm(i,g,h,x),r?.({index:p+1,total:c,artifact:f,success:false,error:x});}}let d=Date.now()-a,m=l.length;return await hI(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function vm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Oi(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(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var xe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:fe()})}));N();function Em({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 ",Lt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function Pm({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Lt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((g,h)=>{let w=h===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:g.danger?"yellow":void 0,dimColor:!w,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 Tm(e){return e.adapter.removable!==false?4:2}F();N();function Cm({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Am({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 Rm({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(T=>r.has(`${T.name}@${o}`)),i=t.filter(T=>!r.has(`${T.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((T,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(O=>Math.max(0,O-1));return}$.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(Cm,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(st/2)),p=Math.min(a.length,m+st);p===a.length&&(m=Math.max(0,p-st));let f=a.slice(m,p),g=m,h=a.length-p,w=s.length>0&&m<s.length,x=p>s.length,_=f.filter(T=>r.has(`${T.name}@${o}`)),L=f.filter(T=>!r.has(`${T.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(T=>jsx(Am,{item:T,isSelected:a.indexOf(T)===l,isInstalled:true},T.name))]}),x&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(T=>jsx(Am,{item:T,isSelected:a.indexOf(T)===l,isInstalled:false},T.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Rl();var vI=/^https?:\/\/.+/;function EI(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function PI(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Lm(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,w=d.current;if(!vI.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let x=randomUUID(),_=new Gn(x,w,h);try{await _.fetchItems(),await nr.add({id:x,name:w,source:h}),le.register(new Gn(x,w,h)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(L){let T=EI(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":PI(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";t(T,"error"),o("add-url");}},[e,t,r]);return useInput((h,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!w.ctrl&&!w.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,w)=>{if(w.escape){o("add-name");return}if(w.return){g();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!w.ctrl&&!w.meta&&(m.current=m.current+h,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Dm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await nr.remove(o),le.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 Nm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=xe(A=>A.installedItems),[o,s]=useState(()=>le.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&g("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=le.listAdapters(),j=await nr.read(),J=new Map(j.map(Ne=>[Ne.id,Ne]));s(A.map(Ne=>({adapter:Ne,stored:J.get(Ne.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=h.current[i-1];if(!A)return;let j=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(J=>{j||p({items:J,loading:false,error:null});}).catch(J=>{j||p({items:[],loading:false,error:J instanceof Error?J.message:"Failed to load catalog"});}),()=>{j=true;}},[i]);let x=Lm(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),g("main");},[w]),{handleRemove:L}=Dm(_),T=useCallback(async A=>{g("removing"),await L(A);},[L]),$=useCallback(async A=>{try{let j=await A.adapter.fetchItems();if(p({items:j,loading:!1,error:null}),A.stored){let J=new Date().toISOString();await nr.updateField(A.stored.id,{lastUpdated:J}),w();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[w,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await nr.updateField(A.stored.id,{autoUpdate:!j}),w();},[w]),U=useCallback(()=>g("browse"),[]),se=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{$(j);},...J?[()=>{O(j);},()=>{T(j.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,T]),k=useCallback(()=>g("main"),[]),V=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),ne=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&T(A.adapter.id);},[o,i,T]);if(useInput((A,j)=>{if(j.upArrow){a(J=>Math.max(0,J-1));return}if(j.downArrow){a(J=>Math.min(o.length,J+1));return}(j.return||j.tab)&&(i===0?x.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&x.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,j)=>{if(j.escape||j.tab){u("list");return}if(j.upArrow){d(J=>Math.max(0,J-1));return}if(j.downArrow){let J=o[i-1],Ne=J?Tm(J)-1:0;d(Ss=>Math.min(Ss+1,Ne));return}j.return&&se(c);},{isActive:f==="main"&&x.phase==="idle"&&l==="detail"&&e==="marketplaces"}),x.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:x.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),x.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(x.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:x.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:x.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),x.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:x.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(x.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(Ne=>Ne.marketplace===A.adapter.name).map(Ne=>`${Ne.name}@${j}`));return jsx(Rm,{entry:A,items:m?.items??[],installedKeys:J,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let H=o[i-1]??null,Z=H?n.filter(A=>A.marketplace===H.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Em,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(Pm,{entry:H,detailData:m,installedCount:Z,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:V,onToggleAutoUpdate:ne,onRemove:K}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:H?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function Um(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=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o-1+ae.length)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o+1)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o+1)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]: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 Bm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Fm(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var RI=new Set(ae.filter(e=>e.focus!=="list").map(e=>e.focus));function os(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}=Ye.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 jm({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=Ye(g=>g.query),a=Ye(g=>g.setQuery),l=Ye(g=>g.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Ye.getState();h(g.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(gl(g,h,{activeTab:w}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(gl("",h,{activeTab:w}));},{isActive:RI.has(t)}),useInput((g,h)=>{let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(Um(g,h,{activeTab:w,selectedIndex:x},u.current));},{isActive:t==="list"}),useInput((g,h)=>{os(Bm(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let w=Fm(g,h,Ye.getState().query),x=w.queryUpdate;if(os(w.actions),x==="reset")l(),d("");else if(x!==null){let{query:_,cursorPosition:L,setCursorPosition:T}=Ye.getState();if("backspace"in x)L>0&&(a(_.slice(0,L-1)+_.slice(L)),T(L-1));else if("append"in x)a(_.slice(0,L)+x.append+_.slice(L)),T(L+x.append.length);else if("cursorMove"in x){let $=L+x.cursorMove;$>=0&&$<=_.length&&T($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:w}=S.getState();g===0?h(0):w>=g&&h(g-1);},[]),f=useCallback(g=>{if(!c)return u.current=g.length,g;let h=c.toLowerCase(),w=g.filter(x=>x.name.toLowerCase().includes(h)||x.description?.toLowerCase().includes(h));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Hm(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=at(a=>a.justAuthenticated),o=at(a=>a.credentials),s=at(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 Ge(e,t,r=false){return r?true:!cc.valid(e)||!cc.valid(t)?false:cc.gt(t,e)}F();R();var cr=b("updater");async function $I(e,t,r,n,o,s){try{await P(E.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:ee().interfaceType});}catch(i){cr.warn(`Failed to send update metrics: ${String(i)}`);}}function _I(e,t){let r=Te(),n=process.cwd();for(let o of Sr){let s=`${e}@${o}`,i=r.plugins[s];if(i&&i.length>0){let a=Wl(i,t,n);if(a)return {pluginKey:s,entry:a}}}return null}async function Fi(e,t={}){let r=Date.now(),n=null;try{cr.debug(`[${e}] Acquiring lock...`),n=await sr();let o=_I(e,t.scope);if(!o)throw cr.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{pluginKey:s,entry:i}=o,a=i.version,l=i.installPath,u=s.slice(s.lastIndexOf("@")+1);cr.debug(`[${e}] Fetching manifest...`);let d=(await Jn(e,t.source??u)).version;if(!a||!Ge(a,d,t.force))throw l&&await bi(l,i.scope),cr.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Or(e,a??"unknown");cr.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await He(e,{force:!0,skipMetrics:!0,source:t.source??u,scope:i.scope}),p=Date.now()-r;return await $I(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),cr.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){cr.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await sr();let p=Te(),f=p.plugins[s]?.find(g=>g.scope===i.scope&&g.projectPath===i.projectPath);throw f&&(f.version=a,f.installPath=l,ut(p),cr.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Nr();R();var ji=b("dispatcher");async function MI(e,t,r,n,o){let s=Kn(e);return ji.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await vi(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),ji.debug(`[${e}] Retrying install after marketplace add`),De(t)}async function Vm(e,t,r,n){let o=Hn(e,n),s=Kn(e);r?.onStatus?.(`Installing ${s}...`),ji.debug(`[${e}] Attempting install: ${o}`);let i=await De(o);if(i.exitCode===0)return i;ji.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return MI(e,o,a,t,r)}async function Gm(e,t,r){let n=e.type??"bundle",o=await Tt.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 Jm(){let e=xe(i=>i.installedItems),t=xe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Gm(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=fe().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Tt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Wo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Fi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var Hi=b("mcp");function ss(e,t){e.silent?_e({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):v(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function zm(e,t){e.silent?oe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(q(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function LI(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 uc(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 Xm(e,t,r){if(!await Y())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return ss(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Hi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=LI(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await X(`Install external MCP "${s}"?
125
+ `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}Nr();var Zn=b("claudeProxy"),rc="claude ",Wp="flow ",Ql=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Yn=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";}},Sx=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,bx=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,xx={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Ix=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,vx=/^(flow|claude)\s+auth\s+login(\s|$)/,zp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Xp(e){return zp.test(e.trim())}function Ex(e){return zp.exec(e.trim())?.[2]??""}async function qp(e){let t=Ex(e);Al(t);let r=Date.now();Zn.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 nc(n)?new ec:n}}function Px(e){Yp(e);let t=e.slice(rc.length);if(!Sx.test(t))throw new Yn(e)}var vi=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},ec=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Yp(e){if(!e||!/^claude /.test(e))throw new Ql(e)}function Tx(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!bx.test(r))throw new Yn(`Unexpected flag: ${r}`);let n=xx[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Yn(`Flag ${r} requires a value`);if(!n.test(o))throw new Yn(`Unsafe value for flag ${r}`);t++;}}}async function De(e){Yp(e);let t=e.slice(rc.length).split(/\s+/).filter(Boolean);Tx(t);let r=Cx(t);Zn.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 Zn.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 nc(o)?new vi:o}}function Cx(e){return e.length>=3?e[2]:e.join(" ")}function nc(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function kx(e){return e.startsWith(Wp)?rc+e.slice(Wp.length):e}function Ax(e){return Ix.test(e)||vx.test(e)}function Rx(e){let t=0;for(;t<e.length&&Ax(e[t]);)t++;return e.slice(t)}var $x=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function _x(e,t){return !t||e.includes("--scope")||!$x.test(e)?e:`${e} --scope ${t}`}async function zo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Rx(r).map(i=>kx(i)).map(i=>_x(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Px(i);Zn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await De(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await De(o[i]),s.exitCode!==0)return s;return s}async function Ei(e,t,r){let n=Kn(e),o=t?.trim();if(!o&&(o=(await qn(`Plugin "${n}" could not be installed.
126
+ 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=yi(o),r?.(),Zn.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"}`);Zn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw nc(s)?new vi:s}}Nr();F();$e();R();var Nx=6e4,Br=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 Qe(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Nx},allowEnvironment:["GIT_TERMINAL_PROMPT","GIT_LFS_SKIP_SMUDGE"]}).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 Br("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Br(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Br(`Failed to clone ${e}: ${i}`,e,false,false)}}async function et(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 Vt(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 Bx(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Fx(e){return typeof e=="object"&&e!==null&&e.source==="url"}function jx(e){return typeof e=="object"&&e!==null&&e.source==="github"}function ar(e,t){let r=e.source;if(Bx(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(Fx(r))return {cloneUrl:r.url,subPath:"."};if(jx(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function dt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Pt=b("claude-code.adapter");function Hx(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=Wr();if(!ue__default.existsSync(s))return r;try{let i=JSON.parse(ue__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 im(e,t){let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=ar(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=Hx(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ma(s,e.name,"external"):a=join(zr(i==="user"?"global":"project"),e.name);let l=null;try{Le(e.name),l=await Qe(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(ue__default.existsSync(a)&&ue__default.rmSync(a,{recursive:!0,force:!0}),ue__default.mkdirSync(dirname(a),{recursive:!0}),ue__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Wl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],ut(d),Go(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Pt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await et(l).catch(()=>{});}}async function oc(e,t,r,n){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:fi(n),version:"unknown",duration_ms:t,interface:ee().interfaceType});}catch(o){Pt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function rm(e,t,r){try{await P(E.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:ee().interfaceType});}catch(n){Pt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var nm={async install(e,t){if(e.origin===Sn&&!e.installCommand&&!jn(e.name))return im(e,t);if(e.origin===Sn&&e.installCommand){let r=e.type??"skill",n=await zo(e.installCommand,t.scope);return n.exitCode===0?(await oc(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await rm(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(jn(e.name)){let r=e.type??"skill",n=Hn(e.name,t.scope);Pt.debug(`[${e.name}] Attempting install: ${n}`);let o=await De(n);if(o.exitCode===0)return await oc(e.name,o.duration_ms,r,t.scope),{success:true};Pt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ei(e.name,t.marketplaceSource,()=>{});let s=await De(n);return s.exitCode===0?(await oc(e.name,s.duration_ms,r,t.scope),{success:true}):(await rm(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 He(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Pt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Jo(e,t);},getInstallPath(e,t){return ""}};function om(e){return {async install(t,r){if(t.origin===Sn&&!t.installCommand&&!jn(t.name))return im(t,r);if(!t.installCommand)try{let o=await He(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Pt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Pt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await zo(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=xe(),o=`${t}@${Ue}`;if(n.plugins[o]){await Jo(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function Vx(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ue__default.existsSync(t))continue;let r=ue__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ue__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Gx(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!ue__default.existsSync(t))continue;let r=ue__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ue__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function sc(e,t,r,n){let o=await Wl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],ut(o);}var Jx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ar(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Vx(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Ps(r);ue__default.mkdirSync(l,{recursive:!0});let u=dt(e.name);if(a.length===1)ue__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=dt(basename(d,".md"));ue__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await sc(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){let r=Ps(t),n=dt(e);if(ue__default.existsSync(r))for(let a of ue__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ue__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=xe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;ut({...s,plugins:l});}else ut({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Ps(t),`${dt(e)}.md`)}},Wx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ar(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Gx(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=La(r);ue__default.mkdirSync(l,{recursive:!0});for(let u of a)ue__default.copyFileSync(u,join(l,basename(u)));return await sc(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return La(t)}},zx={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=ar(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{Le(e.name),s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!ue__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ue__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Lo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=zn(m,u);return Ws({...d,hooks:p}),await sc(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Pi=class{id="claude-code";name="Claude Code";async isAvailable(){return Vt("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:nm,plugin:nm,skill:om("skill"),mcp:om("mcp"),agent:Jx,hook:zx,rule:Wx}};function Ti(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}function eo(e){return {async install(t,r){try{Le(t.name);}catch{return {success:false,message:"Invalid plugin name."}}let n=t.catalogId?le.getAdapter(t.catalogId):void 0,o=ar(t,n?.source);if(!o)return {success:false,message:`Cannot install "${t.name}": unsupported source format.`};let s=null;try{s=await Qe(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=e(r.scope??"user"),l=join(a,t.name);return ue__default.existsSync(l)&&ue__default.rmSync(l,{recursive:!0,force:!0}),ue__default.mkdirSync(a,{recursive:!0}),ue__default.cpSync(i,l,{recursive:!0}),{success:!0,message:`Installed ${t.name}`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await et(s).catch(()=>{});}},async uninstall(t,r){Le(t);let n=join(e(r),t);ue__default.existsSync(n)&&ue__default.rmSync(n,{recursive:true,force:true});},getInstallPath(t,r){return join(e(r),t)}}}$e();var qx=new Set(["gh"]),Yx=Ti(qx,"use: gh copilot mcp remove <name>"),am=eo(e=>Iu(e)),Zx=eo(e=>vu(e)),Qx=eo(e=>Eu(e)),ki=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Vt("gh",["--version"])?Vt("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user","project"]}installers={mcp:Yx,skill:am,bundle:am,agent:Zx,hook:Qx}};$e();var eI=new Set(["opencode"]),tI=Ti(eI,"use: opencode config remove mcp <name>");function rI(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(`
127
+ `)}function lm(){return {async install(e,t){try{Le(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=ar(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Qe(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Es(t.scope??"user"),a=join(s,".opencode","plugins");if(ue__default.existsSync(a)){let l=ue__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/"};ue__default.mkdirSync(i,{recursive:!0}),ue__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ue__default.existsSync(l)&&ue__default.rmSync(l,{recursive:!0,force:!0}),ue__default.mkdirSync(l,{recursive:!0}),ue__default.cpSync(s,l,{recursive:!0}),ue__default.mkdirSync(i,{recursive:!0}),ue__default.writeFileSync(join(i,`${e.name}.js`),rI(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 et(o).catch(()=>{});}},async uninstall(e,t){Le(e);let r=Es(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ue__default.existsSync(n)&&ue__default.rmSync(n,{force:true}),ue__default.existsSync(o)&&ue__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Es(t),`${e}.js`)}}}var Ai=class{id="opencode";name="OpenCode";async isAvailable(){return Vt("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:tI,skill:lm(),bundle:lm()}};$e();var Ri=eo(e=>Pu(e)),$i=class{id="cursor";name="Cursor";async isAvailable(){return await Vt("cursor-agent",["--version"])||await Vt("cursor",["--version"])?true:ue__default.existsSync(join(Se__default.homedir(),".cursor"))}getSupportedScopes(){return ["user","project"]}installers={skill:Ri,bundle:Ri,agent:Ri,hook:Ri}};var Tt=new mi;Tt.register(new Pi);Rr()&&(Tt.register(new ki),Tt.register(new Ai),Tt.register(new $i));function cm({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(()=>{Tt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let w=l.find(x=>x.name===h);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let w=ip(h);w?r(w,c):s(false);},[r,c]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(w=>w.name),"Cancel"];return jsx(ct,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ct,{itemName:`${e} \u2014 Choose scope`,actions:op,descriptions:sp,onAction:f,onClose:g},"scope"):jsx(ct,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function dm({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,g)=>{g.upArrow?a(h=>Math.max(0,h-1)):g.downArrow?a(h=>Math.min(d.length-1,h+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let g=y(f.name??f.flowId),h=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",f]})},f))})]}):jsx(ct,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Li({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")}}N();function fm({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Li({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(ct,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function ym({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Li({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(ct,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var no=b("bundle:installer"),wm=/already exists/i;async function mI(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Xp(t)){let r=await qp(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(wm.test(n))return;throw new Error(n)}}else {let r=await zo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(wm.test(n))return;throw new Error(n)}}}async function fI(e,t){try{await P(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){no.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function gI(e,t,r){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){no.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Sm(e,t,r,n){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){no.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function hI(e,t,r,n,o){try{await P(E.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){no.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Ni(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await fI(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){no.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await Sm(i,g,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await mI(f),u++,await gI(i,g,h),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let x=w instanceof Error?w.message:String(w);no.error(`Failed to install artifact "${g}": ${x}`),l.push({name:g,type:h,reason:x}),await Sm(i,g,h,x),r?.({index:p+1,total:c,artifact:f,success:false,error:x});}}let d=Date.now()-a,m=l.length;return await hI(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function vm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Ni(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(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var Ie=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:fe()})}));N();function Em({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 ",Lt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function Pm({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Lt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((g,h)=>{let w=h===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:g.danger?"yellow":void 0,dimColor:!w,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 Tm(e){return e.adapter.removable!==false?4:2}F();N();function Cm({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Am({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 Rm({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(T=>r.has(`${T.name}@${o}`)),i=t.filter(T=>!r.has(`${T.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((T,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(O=>Math.max(0,O-1));return}$.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(Cm,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(st/2)),p=Math.min(a.length,m+st);p===a.length&&(m=Math.max(0,p-st));let f=a.slice(m,p),g=m,h=a.length-p,w=s.length>0&&m<s.length,x=p>s.length,_=f.filter(T=>r.has(`${T.name}@${o}`)),L=f.filter(T=>!r.has(`${T.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(T=>jsx(Am,{item:T,isSelected:a.indexOf(T)===l,isInstalled:true},T.name))]}),x&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(T=>jsx(Am,{item:T,isSelected:a.indexOf(T)===l,isInstalled:false},T.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}$l();var vI=/^https?:\/\/.+/;function EI(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function PI(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Lm(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,w=d.current;if(!vI.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let x=randomUUID(),_=new Gn(x,w,h);try{await _.fetchItems(),await or.add({id:x,name:w,source:h}),le.register(new Gn(x,w,h)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(L){let T=EI(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":PI(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";t(T,"error"),o("add-url");}},[e,t,r]);return useInput((h,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!w.ctrl&&!w.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,w)=>{if(w.escape){o("add-name");return}if(w.return){g();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!w.ctrl&&!w.meta&&(m.current=m.current+h,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Dm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await or.remove(o),le.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 Nm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=Ie(A=>A.installedItems),[o,s]=useState(()=>le.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&g("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=le.listAdapters(),j=await or.read(),J=new Map(j.map(Ne=>[Ne.id,Ne]));s(A.map(Ne=>({adapter:Ne,stored:J.get(Ne.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=h.current[i-1];if(!A)return;let j=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(J=>{j||p({items:J,loading:false,error:null});}).catch(J=>{j||p({items:[],loading:false,error:J instanceof Error?J.message:"Failed to load catalog"});}),()=>{j=true;}},[i]);let x=Lm(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),g("main");},[w]),{handleRemove:L}=Dm(_),T=useCallback(async A=>{g("removing"),await L(A);},[L]),$=useCallback(async A=>{try{let j=await A.adapter.fetchItems();if(p({items:j,loading:!1,error:null}),A.stored){let J=new Date().toISOString();await or.updateField(A.stored.id,{lastUpdated:J}),w();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[w,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await or.updateField(A.stored.id,{autoUpdate:!j}),w();},[w]),U=useCallback(()=>g("browse"),[]),se=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{$(j);},...J?[()=>{O(j);},()=>{T(j.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,T]),k=useCallback(()=>g("main"),[]),V=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),ne=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&T(A.adapter.id);},[o,i,T]);if(useInput((A,j)=>{if(j.upArrow){a(J=>Math.max(0,J-1));return}if(j.downArrow){a(J=>Math.min(o.length,J+1));return}(j.return||j.tab)&&(i===0?x.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&x.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,j)=>{if(j.escape||j.tab){u("list");return}if(j.upArrow){d(J=>Math.max(0,J-1));return}if(j.downArrow){let J=o[i-1],Ne=J?Tm(J)-1:0;d(Ss=>Math.min(Ss+1,Ne));return}j.return&&se(c);},{isActive:f==="main"&&x.phase==="idle"&&l==="detail"&&e==="marketplaces"}),x.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:x.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),x.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(x.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:x.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:x.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),x.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:x.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(x.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(Ne=>Ne.marketplace===A.adapter.name).map(Ne=>`${Ne.name}@${j}`));return jsx(Rm,{entry:A,items:m?.items??[],installedKeys:J,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let H=o[i-1]??null,Z=H?n.filter(A=>A.marketplace===H.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Em,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(Pm,{entry:H,detailData:m,installedCount:Z,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:V,onToggleAutoUpdate:ne,onRemove:K}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:H?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function Um(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=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o-1+ae.length)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o+1)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ae.findIndex(i=>i.id===r.activeTab),s=ae[(o+1)%ae.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]: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 Bm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Fm(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var RI=new Set(ae.filter(e=>e.focus!=="list").map(e=>e.focus));function os(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}=Ye.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 jm({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=Ye(g=>g.query),a=Ye(g=>g.setQuery),l=Ye(g=>g.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Ye.getState();h(g.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(hl(g,h,{activeTab:w}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(hl("",h,{activeTab:w}));},{isActive:RI.has(t)}),useInput((g,h)=>{let{activeTab:w,selectedIndex:x,actionMenuOpen:_}=S.getState();os(Um(g,h,{activeTab:w,selectedIndex:x},u.current));},{isActive:t==="list"}),useInput((g,h)=>{os(Bm(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let w=Fm(g,h,Ye.getState().query),x=w.queryUpdate;if(os(w.actions),x==="reset")l(),d("");else if(x!==null){let{query:_,cursorPosition:L,setCursorPosition:T}=Ye.getState();if("backspace"in x)L>0&&(a(_.slice(0,L-1)+_.slice(L)),T(L-1));else if("append"in x)a(_.slice(0,L)+x.append+_.slice(L)),T(L+x.append.length);else if("cursorMove"in x){let $=L+x.cursorMove;$>=0&&$<=_.length&&T($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:w}=S.getState();g===0?h(0):w>=g&&h(g-1);},[]),f=useCallback(g=>{if(!c)return u.current=g.length,g;let h=c.toLowerCase(),w=g.filter(x=>x.name.toLowerCase().includes(h)||x.description?.toLowerCase().includes(h));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Hm(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=at(a=>a.justAuthenticated),o=at(a=>a.credentials),s=at(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 Ge(e,t,r=false){return r?true:!uc.valid(e)||!uc.valid(t)?false:uc.gt(t,e)}F();R();var Wt=b("updater");async function $I(e,t,r,n,o,s){try{await P(E.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:ee().interfaceType});}catch(i){Wt.warn(`Failed to send update metrics: ${String(i)}`);}}function _I(e,t){let r=xe(),n=process.cwd();for(let o of Sr){let s=`${e}@${o}`,i=r.plugins[s];if(i&&i.length>0){let a=zl(i,t,n);if(a)return {pluginKey:s,entry:a}}}return null}async function ji(e,t={}){let r=Date.now(),n=null;try{Wt.debug(`[${e}] Acquiring lock...`),n=await ir();let o=_I(e,t.scope);if(!o)throw Wt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{pluginKey:s,entry:i}=o,a=i.version,l=i.installPath,u=s.slice(s.lastIndexOf("@")+1);Wt.debug(`[${e}] Fetching manifest...`);let d=(await Jn(e,t.source??u)).version;if(!a||!Ge(a,d,t.force))throw l&&await bi(l,i.scope),Wt.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Or(e,a??"unknown");Wt.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await He(e,{force:!0,skipMetrics:!0,source:t.source??u,scope:i.scope});if(l&&l!==m.path)try{let f=xe(),g=Object.values(f.plugins).flatMap(h=>h.map(w=>({installPath:w.installPath,scope:w.scope})));xi(l,i.scope,g);}catch(f){Wt.warn(`[${e}] Could not clean up previous version's hook entries (non-fatal): ${String(f)}`);}let p=Date.now()-r;return await $I(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),Wt.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){Wt.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await ir();let p=xe(),f=p.plugins[s]?.find(g=>g.scope===i.scope&&g.projectPath===i.projectPath);throw f&&(f.version=a,f.installPath=l,ut(p),Wt.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Nr();R();var Ki=b("dispatcher");async function MI(e,t,r,n,o){let s=Kn(e);return Ki.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Ei(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Ki.debug(`[${e}] Retrying install after marketplace add`),De(t)}async function Vm(e,t,r,n){let o=Hn(e,n),s=Kn(e);r?.onStatus?.(`Installing ${s}...`),Ki.debug(`[${e}] Attempting install: ${o}`);let i=await De(o);if(i.exitCode===0)return i;Ki.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return MI(e,o,a,t,r)}async function Gm(e,t,r){let n=e.type??"bundle",o=await Tt.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 Jm(){let e=Ie(i=>i.installedItems),t=Ie(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Gm(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=fe().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Tt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Wo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await ji(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var Vi=b("mcp");function ss(e,t){e.silent?_e({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):v(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function zm(e,t){e.silent?oe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(q(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&I(t.stdout));}function LI(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 dc(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 Xm(e,t,r){if(!await Y())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return ss(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Vi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=LI(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await X(`Install external MCP "${s}"?
128
128
  This will run: ${i}
129
- [y/N] `))return Hi.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:ca({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await De(n);return o?.stop(),s.exitCode!==0?(ss(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&I(`stdout: ${s.stdout}`),1):(zm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),ss(r,{name:e,action:"add",message:te(s)}),1}}async function qm(e,t){if(!await Y())return 1;Hi.debug(`[${e}] Starting MCP remove`);let r=uc(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await X(`Remove MCP "${o}"?
129
+ [y/N] `))return Vi.debug(`[${e}] Installation cancelled by user`),I("Operation cancelled."),0}let o=r.silent?void 0:ua({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await De(n);return o?.stop(),s.exitCode!==0?(ss(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&I(`stdout: ${s.stdout}`),1):(zm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),ss(r,{name:e,action:"add",message:te(s)}),1}}async function qm(e,t){if(!await Y())return 1;Vi.debug(`[${e}] Starting MCP remove`);let r=dc(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await X(`Remove MCP "${o}"?
130
130
  This will run: ${s}
131
- [y/N] `))return Hi.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:ca({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await De(r);return n?.stop(),o.exitCode!==0?(ss(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(zm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),ss(t,{name:e,action:"remove",message:te(o)}),1}}R();function Ym({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=b("pluginHandlers"),a=useRef(0),l=S(T=>T.setLoading),u=S(T=>T.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Jm(),f=async(T,$,O)=>{l(true,T),n();try{await $(),o(r.length),s(O,"success");}catch(U){let se=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${se}`),s(se,"error");}finally{l(false);}};return {handleInstall:(T,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:T,...$!==void 0?{providerId:$}:{},onDownloadProgress:(O,U)=>{let se=Date.now();(se-a.current>100||O>=U)&&(a.current=se,u(O,U));}}),"\u2713 Installed successfully"));},handleUninstall:T=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,T),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${T}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch(O){if(O instanceof Or)s(O.message,"info");else {let U=O instanceof Error?O.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${U}`),s(U,"error");}}finally{l(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let $=T.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let U=[];for(let V of T)U.push(await p(V.name).then(()=>({status:"fulfilled",value:void 0}),ne=>({status:"rejected",reason:ne})));let se=U.filter(V=>V.status==="fulfilled").length,k=U.map((V,ne)=>V.status==="rejected"?T[ne].name:null).filter(V=>V!==null);o(r.length),k.length===0?s(`\u2713 Updated ${se}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${se}/${$}; failed: ${k.join(", ")}`,se>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:T=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=uc(e.name,T),O=await De($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");xe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Fo();R();var is=b("api:bundle"),lo=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},as=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},NI=/^[a-zA-Z0-9_-]{1,128}$/;async function Qm(e,t){if(e instanceof HTTPError){let r=e.response.status;throw is.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new lo(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new as:new Error(`Server error (${r}) \u2014 please try again later.`)}throw is.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function ef(e){if(!NI.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);is.debug(`Fetching bundle by flowId "${e}"`);try{return await Kt().get(`v1/use-cases/${t}`).json()}catch(r){return Qm(r,e)}}async function Vi(e){let t=encodeURIComponent(e);is.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Kt().get(`v1/use-cases/by-name/${t}`).json(),is.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Qm(n,e)}if(r.length===0)throw new lo(e);return r[0]}R();var UI=b("tui:bundle-flow");function tf({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();UI.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?ef(d):Vi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),xe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var ls=["local","project","user"];function FI(e){let t=Se__default.homedir();return e===t||e.startsWith(t+"/")?`~${e.slice(t.length)}`:e}function rf(e){return FI(e.projectPath??e.installPath)}var jI=new Set(["--transport","--scope","-s"]);function nf(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(jI.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function hn(e,t){return t?`${e}::${t}`:e}function dc(e){return e===Ue?So:Sn}function of(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??So,flowId:e.flowId}}function pc(e,t){let r=dc(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function sf(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 ls.filter(r=>t.has(r)).map(r=>({scope:r,label:Xe[r].label,pathHint:Xe[r].pathHint,items:t.get(r)??[]}))}function af(e){let t=r=>{if(!r)return 1/0;let n=ls.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function lf({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>hn(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[hn(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let w=f.get(hn(h.name,h.author?.name))??g.get(h.name),x=w?.version,_=!!x&&!!h.version&&Ge(h.version,x);return {...h,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(hn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?nf(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>of(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>pc(f,f.catalogItem)):a.map(f=>pc(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let g=f.type??"bundle";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(h=>[hn(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(hn(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function mc(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await xp();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(E.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 cf(){return {items:xe(t=>t.installedItems)}}R();var JI=b("catalog");function df(){let e=S(Q=>Q.bundleInstallFlow),t=S(Q=>Q.activeTab),r=S(Q=>Q.notification),n=S(Q=>Q.loading),o=S(Q=>Q.loadingMessage),s=S(Q=>Q.downloadProgress),i=S(Q=>Q.downloadTotal),a=S(Q=>Q.catalogError),l=S(Q=>Q.setCatalogError),u=S(Q=>Q.catalogFilters),c=Ye(Q=>Q.query),{catalog:d,isLoading:m,error:p,refetch:f}=mc(),{items:g}=cf(),h=xe(Q=>Q.loadFromDisk),{items:w,emptyMessage:x,getSelectedCatalogItem:_,outdatedCount:L}=lf({catalog:d,installedItems:g,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:T,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:se}=jm({listLength:w.length}),k=se(w),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:af(k),[t,k]),ne=useMemo(()=>t==="installed"||t==="updates"?sf(V):[],[t,V]),K=V[O]??null,H=useMemo(()=>_(K),[_,K]),{notify:Z}=Hm(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:Ne,handleBatchUpdate:Ss,handleMcpConfigUninstall:my}=Ym({selectedItem:K,selectedCatalogItem:H,items:w,closeMenu:$,clampIndex:U,notify:Z}),{handleBundleInstallStart:fy,handleBundleDetailConfirm:gy,handleBundleDetailBack:hy,handleBundleInstallComplete:yy}=tf({closeMenu:$,notify:Z}),wy=useCallback(()=>Ss(V),[Ss,V]);return useEffect(()=>{h();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(JI.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),jsx(Rd,{outdatedCount:L}),t==="marketplaces"&&Rr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Nm,{})}):jsx(zd,{filteredItems:V,groups:ne,emptyMessage:x,onBatchUpdate:wy}),(n||m)&&jsxs(Fragment,{children:[jsx(ci,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(ui,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(di,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Xd,{message:r.message,type:r.type}),T&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(vm,{bundle:e.bundle,onComplete:yy}):jsx(dm,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>fy(K.name,K.flowId),onConfirm:gy,onClose:e?.phase==="detail"?hy:$}):jsx(cm,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(ym,{itemName:K.name,itemScope:K.scope??"user",onUninstall:my,onClose:$}):jsx(fm,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:j,onToggleStatus:Q=>J(Q),onUpdate:Ne,onClose:$})),jsx(li,{})]})}var M=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(xe.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Ce();var YI=3;function mf(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await wi();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{xe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let g=1;g<=YI;g++)try{await He(m.name,{onDownloadProgress:(h,w)=>{let x=Date.now();(x-l.current>100||h>=w)&&(l.current=x,o(m.name,h,w));}}),n(m.name,"success"),f=!0;break}catch(h){if(h instanceof Ze){n(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(n(m.name,"failed",p),P(E.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:ee().interfaceType}).catch(()=>{}));}let d=en();Qr("summary_review"),P(E.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),xe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var cs={cursorDelta:0,confirm:false,back:false};function ff(e,t){return t.upArrow?{...cs,cursorDelta:-1}:t.downArrow?{...cs,cursorDelta:1}:t.escape?{...cs,back:true}:t.return?{...cs,confirm:true}:cs}var ZI={cursorDelta:0,select:false};function gf(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:ZI}N();var hf=gS.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var bc=5;function yf({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(ci,{message:"Loading Starter Kits..."});if(o)return jsx(di,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(On,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(bc/2)),i=Math.min(t.length,s+bc);i===t.length&&(s=Math.max(0,i-bc));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(hf,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var Sf=gS.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var vc=8;function bf(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(E.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(vc/2)),i=Math.min(t.length,s+vc);i===t.length&&(s=Math.max(0,i-vc));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Sf,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var av=["Retry failed","Continue anyway"];function xf({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(ui,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function If({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(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(xf,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(xf,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:av.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 vf(){let e=M(k=>k.step),t=M(k=>k.starterKits),r=M(k=>k.selectedStarterKitIndex),n=M(k=>k.setSelectedStarterKitIndex),o=M(k=>k.selectStarterKit),s=M(k=>k.plugins),i=M(k=>k.pluginCursorIndex),a=M(k=>k.setPluginCursorIndex),l=M(k=>k.setStep),u=M(k=>k.summaryActionIndex),c=M(k=>k.setSummaryActionIndex),d=M(k=>k.failedCount),m=M(k=>k.resetForRetry),p=M(k=>k.goBackToList),f=S(k=>k.setScreen),g=S(k=>k.setFocus),h=S(k=>k.focus),w=at(k=>k.setJustAuthenticated),x=at(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:L}=mf(),T=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),T.current||(T.current=true,Qr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let ne=await re();ne&&await Pr({...ne,starterKit:k.slug});}P(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:en()}).catch(()=>{});let{successCount:V}=M.getState();P(E.CLI_ONBOARDING_COMPLETED,{duration_ms:Cr(),tools_installed_count:V}).catch(()=>{}),w(false),g("verify"),f("verify");},[w,g,f]),O=useCallback(()=>{m(),L();},[m,L]),U=useCallback(()=>{_();},[_]),se=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((k,V)=>{if(V.escape)Gs("esc"),se();else if(V.upArrow&&r>0)n(r-1);else if(V.downArrow&&r<t.length-1)n(r+1);else if(V.return&&t.length>0){let ne=en();o(t[r]),Qr("kit_display"),P(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ne}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((k,V)=>{let ne=ff(k,V);if(ne.cursorDelta!==0){let K=i+ne.cursorDelta;K>=0&&K<s.length&&a(K);}if(ne.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await re())?.starterKit!==K.slug&&P(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=en();Qr("kit_confirmation"),P(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let Z=en();Qr("tool_installation"),P(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Z}).catch(()=>{}),l("installing"),L();}if(ne.back){let K=M.getState().selectedStarterKit;K&&P(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let ne=gf(k,V);if(ne.cursorDelta!==0){let K=u+ne.cursorDelta;K>=0&&K<=1&&c(K);}ne.select&&(u===0?O():$());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),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."}),!x&&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(yf,{onRetry:U}),e==="starterKitDetail"&&jsx(bf,{}),(e==="installing"||e==="summary")&&jsx(If,{onComplete:$,onRetry:O})]}),jsx(li,{})]})}F();var Tf=null;function Cf(){return Tf}async function Zi(){let t=sn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=me.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await kf(n);(o||s)&&await xt({...r,installedVersion:o,installMethod:s});}}async function kf(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 jt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function uo(e){let t=await Promise.all(e.map(r=>uv(r)));return Tf=t,t}async function uv(e){let t=Ef(e.versionCommand);t==="permission-denied"&&(dv(e.versionCommand[0]),t=Ef(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await jt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!lt(e.alias)){let{installedVersion:l,installMethod:u}=await kf(e);await xt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Ef(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function dv(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=ue__default.realpathSync(r),{mode:o}=ue__default.statSync(n);ue__default.chmodSync(n,o|73);}catch{}}function fv(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 Mf(e,t){let[r,n]=useState(()=>fv(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let x=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(x+1)%w.availableStrategies.length];n(L=>L.map(T=>T.module.alias===w.module.alias?{...T,selectedStrategy:_}:T));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function Df({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Mf(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(ct,{itemName:m,actions:d,onAction:c,onClose:u})]})}var Sv=/^https?:\/\/.+/;function Of({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&Sv.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function xv(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 Bf(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=xv(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await Mr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}F();N();function Ff({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function Vf({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=Bf(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{an().catch(()=>{}),n("list");let w=fe().some(x=>x.name===he);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,x)=>{x.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,g=a-f,h=[];return g>0&&h.push(jsxs(Text,{color:"green",children:[g," installed"]},"i")),f>0&&h.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(Ff,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((w,x,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(x),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Jf(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(dd(p)){an().catch(()=>{}),l("list");let g=fe().some(h=>h.name===he);u(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=Cf();if(p){c(p);return}uo(me).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(g=>g.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Df,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Of,{onConfirm:m}),e==="installation"&&jsx(Vf,{confirmedItems:o,customUrl:i})]})}F();R();var $v=b("ClaudeMdSuggestion"),_v=[`Install ${he}`,"Skip for now"],Mv=["Retry","Skip for now"];function Xf(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{P(E.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,P(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await He(he),o("installed");}catch(m){if(m instanceof Ze){o("installed");return}$v.warn(`Failed to install ${he}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Mv:_v;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),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(zf,{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(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",he,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",he," 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:["/",he]})]}),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 ",he]}),jsx(zf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function zf({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 Nv=promisify(execFile),na="@ciandt-flow/cli";async function qf(){let e=ye;if(cc.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:na};try{let t=await fetch(`https://registry.npmjs.org/${na}/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:na}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:na}}}async function oa(e){try{return await Nv(tr(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Uv(e){let t=lt(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await jt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await xt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Yf(e){let t=await Uv(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function Zf(e,t){let r=lt(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await jt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await xt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Qf(e){let r=lt(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 eg(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...me.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([qf(),uo(me),Promise.all(me.map(l=>Yf(l)))]);if(Zi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await oa(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=me.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 Zf(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:Qf(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await an(),t(l=>({...l,outcome:"done"}));}catch{await an(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function Vv({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{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 Gv({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 tg(){let{outcome:e,items:t}=eg(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=fe().some(i=>i.name===he);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(Vv,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(Gv,{outcome:e})})]})}Ce();Rn();R();Oa();var Xv={debug:"gray",info:"cyan",warn:"yellow",error:"red"},rg=10;function ng(){let[e,t]=useState(Da());useEffect(()=>ku(()=>{t([...Da()]);}),[]);let r=e.slice(-rg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",rg,") \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:Xv[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Qv=b("app"),eE={auth:Id,starterKitSetup:vf,moduleSetup:Jf,claudeMdSuggestion:Xf,verify:tg,main:df};function ig(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function si(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function ag(){P(E.CLI_SESSION_STARTED,{cli_version:ye,os:process.platform,node_version:process.version,duration_ms:Cr(),interface:"tui"}).catch(()=>{});}async function cg(){let e=await re();if(e&&cd()&&await Tr()){e.customUrl&&Dt(e.customUrl);let{clientSecret:n,...o}=e;at.getState().setCredentials(o),ag(),si(e);return}if(!e){ig();return}try{e.customUrl&&Dt(e.customUrl),await Nt();}catch(n){Qv.debug(`Token validation failed: ${String(n)}`),ig();return}ag();let{clientSecret:t,...r}=e;at.getState().setCredentials(r),si(e);}function ug(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=eE[r],{pendingExit:o}=ed(),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(ng,{}),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]})}Ce();Hs();N();F();R();Po();Ce();async function Dc(e,t={}){let r=zs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Xs(r),await Pr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=b("auth");function pg(){qe.clearFallbackFile(),Bs();}var tE=3,dg=3,mg=` \u2139 The data collected during setup is used solely to improve
131
+ [y/N] `))return Vi.debug(`[${e}] Removal cancelled by user`),I("Operation cancelled."),0}let n=t.silent?void 0:ua({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await De(r);return n?.stop(),o.exitCode!==0?(ss(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&I(`stdout: ${o.stdout}`),1):(zm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),ss(t,{name:e,action:"remove",message:te(o)}),1}}R();function Ym({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=b("pluginHandlers"),a=useRef(0),l=S(T=>T.setLoading),u=S(T=>T.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Jm(),f=async(T,$,O)=>{l(true,T),n();try{await $(),o(r.length),s(O,"success");}catch(U){let se=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${se}`),s(se,"error");}finally{l(false);}};return {handleInstall:(T,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:T,...$!==void 0?{providerId:$}:{},onDownloadProgress:(O,U)=>{let se=Date.now();(se-a.current>100||O>=U)&&(a.current=se,u(O,U));}}),"\u2713 Installed successfully"));},handleUninstall:T=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,T),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${T}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch(O){if(O instanceof Or)s(O.message,"info");else {let U=O instanceof Error?O.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${U}`),s(U,"error");}}finally{l(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let $=T.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let U=[];for(let V of T)U.push(await p(V.name).then(()=>({status:"fulfilled",value:void 0}),ne=>({status:"rejected",reason:ne})));let se=U.filter(V=>V.status==="fulfilled").length,k=U.map((V,ne)=>V.status==="rejected"?T[ne].name:null).filter(V=>V!==null);o(r.length),k.length===0?s(`\u2713 Updated ${se}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${se}/${$}; failed: ${k.join(", ")}`,se>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:T=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=dc(e.name,T),O=await De($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");Ie.getState().loadFromDisk();},"\u2713 MCP removed");}}}Fo();R();var is=b("api:bundle"),lo=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},as=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},NI=/^[a-zA-Z0-9_-]{1,128}$/;async function Qm(e,t){if(e instanceof HTTPError){let r=e.response.status;throw is.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new lo(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new as:new Error(`Server error (${r}) \u2014 please try again later.`)}throw is.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function ef(e){if(!NI.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);is.debug(`Fetching bundle by flowId "${e}"`);try{return await Kt().get(`v1/use-cases/${t}`).json()}catch(r){return Qm(r,e)}}async function Gi(e){let t=encodeURIComponent(e);is.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Kt().get(`v1/use-cases/by-name/${t}`).json(),is.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Qm(n,e)}if(r.length===0)throw new lo(e);return r[0]}R();var UI=b("tui:bundle-flow");function tf({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();UI.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?ef(d):Gi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),Ie.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var ls=["local","project","user"];function FI(e){let t=Se__default.homedir();return e===t||e.startsWith(t+"/")?`~${e.slice(t.length)}`:e}function rf(e){return FI(e.projectPath??e.installPath)}var jI=new Set(["--transport","--scope","-s"]);function nf(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(jI.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function hn(e,t){return t?`${e}::${t}`:e}function pc(e){return e===Ue?So:Sn}function of(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??So,flowId:e.flowId}}function mc(e,t){let r=pc(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function sf(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 ls.filter(r=>t.has(r)).map(r=>({scope:r,label:Xe[r].label,pathHint:Xe[r].pathHint,items:t.get(r)??[]}))}function af(e){let t=r=>{if(!r)return 1/0;let n=ls.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function lf({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>hn(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[hn(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let w=f.get(hn(h.name,h.author?.name))??g.get(h.name),x=w?.version,_=!!x&&!!h.version&&Ge(h.version,x);return {...h,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(hn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?nf(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>of(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>mc(f,f.catalogItem)):a.map(f=>mc(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let g=f.type??"bundle";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(h=>[hn(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(hn(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function fc(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Ip();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(E.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 cf(){return {items:Ie(t=>t.installedItems)}}R();var JI=b("catalog");function df(){let e=S(Q=>Q.bundleInstallFlow),t=S(Q=>Q.activeTab),r=S(Q=>Q.notification),n=S(Q=>Q.loading),o=S(Q=>Q.loadingMessage),s=S(Q=>Q.downloadProgress),i=S(Q=>Q.downloadTotal),a=S(Q=>Q.catalogError),l=S(Q=>Q.setCatalogError),u=S(Q=>Q.catalogFilters),c=Ye(Q=>Q.query),{catalog:d,isLoading:m,error:p,refetch:f}=fc(),{items:g}=cf(),h=Ie(Q=>Q.loadFromDisk),{items:w,emptyMessage:x,getSelectedCatalogItem:_,outdatedCount:L}=lf({catalog:d,installedItems:g,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:T,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:se}=jm({listLength:w.length}),k=se(w),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:af(k),[t,k]),ne=useMemo(()=>t==="installed"||t==="updates"?sf(V):[],[t,V]),K=V[O]??null,H=useMemo(()=>_(K),[_,K]),{notify:Z}=Hm(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:Ne,handleBatchUpdate:Ss,handleMcpConfigUninstall:my}=Ym({selectedItem:K,selectedCatalogItem:H,items:w,closeMenu:$,clampIndex:U,notify:Z}),{handleBundleInstallStart:fy,handleBundleDetailConfirm:gy,handleBundleDetailBack:hy,handleBundleInstallComplete:yy}=tf({closeMenu:$,notify:Z}),wy=useCallback(()=>Ss(V),[Ss,V]);return useEffect(()=>{h();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(JI.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),jsx($d,{outdatedCount:L}),t==="marketplaces"&&Rr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Nm,{})}):jsx(Xd,{filteredItems:V,groups:ne,emptyMessage:x,onBatchUpdate:wy}),(n||m)&&jsxs(Fragment,{children:[jsx(ci,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(ui,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(di,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(qd,{message:r.message,type:r.type}),T&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(vm,{bundle:e.bundle,onComplete:yy}):jsx(dm,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>fy(K.name,K.flowId),onConfirm:gy,onClose:e?.phase==="detail"?hy:$}):jsx(cm,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(ym,{itemName:K.name,itemScope:K.scope??"user",onUninstall:my,onClose:$}):jsx(fm,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:j,onToggleStatus:Q=>J(Q),onUpdate:Ne,onClose:$})),jsx(li,{})]})}var M=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(Ie.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Ce();var YI=3;function mf(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await wi();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{Ie.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let g=1;g<=YI;g++)try{await He(m.name,{onDownloadProgress:(h,w)=>{let x=Date.now();(x-l.current>100||h>=w)&&(l.current=x,o(m.name,h,w));}}),n(m.name,"success"),f=!0;break}catch(h){if(h instanceof Ze){n(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(n(m.name,"failed",p),P(E.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:ee().interfaceType}).catch(()=>{}));}let d=en();Qr("summary_review"),P(E.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),Ie.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var cs={cursorDelta:0,confirm:false,back:false};function ff(e,t){return t.upArrow?{...cs,cursorDelta:-1}:t.downArrow?{...cs,cursorDelta:1}:t.escape?{...cs,back:true}:t.return?{...cs,confirm:true}:cs}var ZI={cursorDelta:0,select:false};function gf(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:ZI}N();var hf=gS.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var xc=5;function yf({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(ci,{message:"Loading Starter Kits..."});if(o)return jsx(di,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(On,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(xc/2)),i=Math.min(t.length,s+xc);i===t.length&&(s=Math.max(0,i-xc));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(hf,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var Sf=gS.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var Ec=8;function bf(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(E.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(Ec/2)),i=Math.min(t.length,s+Ec);i===t.length&&(s=Math.max(0,i-Ec));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Sf,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}N();var av=["Retry failed","Continue anyway"];function xf({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(ui,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function If({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(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(xf,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(xf,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:av.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 vf(){let e=M(k=>k.step),t=M(k=>k.starterKits),r=M(k=>k.selectedStarterKitIndex),n=M(k=>k.setSelectedStarterKitIndex),o=M(k=>k.selectStarterKit),s=M(k=>k.plugins),i=M(k=>k.pluginCursorIndex),a=M(k=>k.setPluginCursorIndex),l=M(k=>k.setStep),u=M(k=>k.summaryActionIndex),c=M(k=>k.setSummaryActionIndex),d=M(k=>k.failedCount),m=M(k=>k.resetForRetry),p=M(k=>k.goBackToList),f=S(k=>k.setScreen),g=S(k=>k.setFocus),h=S(k=>k.focus),w=at(k=>k.setJustAuthenticated),x=at(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:L}=mf(),T=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),T.current||(T.current=true,Qr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let ne=await re();ne&&await Pr({...ne,starterKit:k.slug});}P(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:en()}).catch(()=>{});let{successCount:V}=M.getState();P(E.CLI_ONBOARDING_COMPLETED,{duration_ms:Cr(),tools_installed_count:V}).catch(()=>{}),w(false),g("verify"),f("verify");},[w,g,f]),O=useCallback(()=>{m(),L();},[m,L]),U=useCallback(()=>{_();},[_]),se=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((k,V)=>{if(V.escape)Gs("esc"),se();else if(V.upArrow&&r>0)n(r-1);else if(V.downArrow&&r<t.length-1)n(r+1);else if(V.return&&t.length>0){let ne=en();o(t[r]),Qr("kit_display"),P(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ne}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((k,V)=>{let ne=ff(k,V);if(ne.cursorDelta!==0){let K=i+ne.cursorDelta;K>=0&&K<s.length&&a(K);}if(ne.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await re())?.starterKit!==K.slug&&P(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=en();Qr("kit_confirmation"),P(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let Z=en();Qr("tool_installation"),P(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Z}).catch(()=>{}),l("installing"),L();}if(ne.back){let K=M.getState().selectedStarterKit;K&&P(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let ne=gf(k,V);if(ne.cursorDelta!==0){let K=u+ne.cursorDelta;K>=0&&K<=1&&c(K);}ne.select&&(u===0?O():$());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),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."}),!x&&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(yf,{onRetry:U}),e==="starterKitDetail"&&jsx(bf,{}),(e==="installing"||e==="summary")&&jsx(If,{onComplete:$,onRetry:O})]}),jsx(li,{})]})}F();var Tf=null;function Cf(){return Tf}async function Qi(){let t=sn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=me.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await kf(n);(o||s)&&await xt({...r,installedVersion:o,installMethod:s});}}async function kf(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 jt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function uo(e){let t=await Promise.all(e.map(r=>uv(r)));return Tf=t,t}async function uv(e){let t=Ef(e.versionCommand);t==="permission-denied"&&(dv(e.versionCommand[0]),t=Ef(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await jt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!lt(e.alias)){let{installedVersion:l,installMethod:u}=await kf(e);await xt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Ef(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function dv(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=ue__default.realpathSync(r),{mode:o}=ue__default.statSync(n);ue__default.chmodSync(n,o|73);}catch{}}function fv(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 Mf(e,t){let[r,n]=useState(()=>fv(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let x=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(x+1)%w.availableStrategies.length];n(L=>L.map(T=>T.module.alias===w.module.alias?{...T,selectedStrategy:_}:T));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function Df({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Mf(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(ct,{itemName:m,actions:d,onAction:c,onClose:u})]})}var Sv=/^https?:\/\/.+/;function Of({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&Sv.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function xv(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 Bf(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=xv(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await Mr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}F();N();function Ff({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function Vf({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=Bf(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{an().catch(()=>{}),n("list");let w=fe().some(x=>x.name===he);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,x)=>{x.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,g=a-f,h=[];return g>0&&h.push(jsxs(Text,{color:"green",children:[g," installed"]},"i")),f>0&&h.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(Ff,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((w,x,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(x),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Jf(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(pd(p)){an().catch(()=>{}),l("list");let g=fe().some(h=>h.name===he);u(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=Cf();if(p){c(p);return}uo(me).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(g=>g.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Df,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Of,{onConfirm:m}),e==="installation"&&jsx(Vf,{confirmedItems:o,customUrl:i})]})}F();R();var $v=b("ClaudeMdSuggestion"),_v=[`Install ${he}`,"Skip for now"],Mv=["Retry","Skip for now"];function Xf(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{P(E.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,P(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await He(he),o("installed");}catch(m){if(m instanceof Ze){o("installed");return}$v.warn(`Failed to install ${he}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Mv:_v;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Dn,{}),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(zf,{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(Im,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",he,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",he," 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:["/",he]})]}),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 ",he]}),jsx(zf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function zf({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 Nv=promisify(execFile),oa="@ciandt-flow/cli";async function qf(){let e=ye;if(uc.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:oa};try{let t=await fetch(`https://registry.npmjs.org/${oa}/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:oa}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:oa}}}async function sa(e){try{return await Nv(rr(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Uv(e){let t=lt(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await jt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await xt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Yf(e){let t=await Uv(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function Zf(e,t){let r=lt(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await jt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await xt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Qf(e){let r=lt(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 eg(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...me.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([qf(),uo(me),Promise.all(me.map(l=>Yf(l)))]);if(Qi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await sa(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=me.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 Zf(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:Qf(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await an(),t(l=>({...l,outcome:"done"}));}catch{await an(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function Vv({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Im,{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 Gv({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 tg(){let{outcome:e,items:t}=eg(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=fe().some(i=>i.name===he);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(Vv,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(Gv,{outcome:e})})]})}Ce();Rn();R();Na();var Xv={debug:"gray",info:"cyan",warn:"yellow",error:"red"},rg=10;function ng(){let[e,t]=useState(Oa());useEffect(()=>Au(()=>{t([...Oa()]);}),[]);let r=e.slice(-rg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",rg,") \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:Xv[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var Qv=b("app"),eE={auth:vd,starterKitSetup:vf,moduleSetup:Jf,claudeMdSuggestion:Xf,verify:tg,main:df};function ig(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function si(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function ag(){P(E.CLI_SESSION_STARTED,{cli_version:ye,os:process.platform,node_version:process.version,duration_ms:Cr(),interface:"tui"}).catch(()=>{});}async function cg(){let e=await re();if(e&&ud()&&await Tr()){e.customUrl&&Dt(e.customUrl);let{clientSecret:n,...o}=e;at.getState().setCredentials(o),ag(),si(e);return}if(!e){ig();return}try{e.customUrl&&Dt(e.customUrl),await Nt();}catch(n){Qv.debug(`Token validation failed: ${String(n)}`),ig();return}ag();let{clientSecret:t,...r}=e;at.getState().setCredentials(r),si(e);}function ug(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=eE[r],{pendingExit:o}=td(),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(ng,{}),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]})}Ce();Hs();N();F();R();Po();Ce();async function Oc(e,t={}){let r=zs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Xs(r),await Pr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=b("auth");function pg(){qe.clearFallbackFile(),Bs();}var tE=3,dg=3,mg=` \u2139 The data collected during setup is used solely to improve
132
132
  Flow's internal tools and will not be shared externally.
133
- `;function Xt(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===`
133
+ `;function qt(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===`
134
134
  `){l(),process.stdout.write(`
135
135
  `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function rE(){let e=nn();return process.stdout.write(`
136
136
  `+C.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
137
- `),(await Xt(C.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function fg(e,t,r){try{await Dc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof on))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${nn()} and retry.`,{cause:n});if(!await rE())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Dc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function nE(){if((await Xt(C.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Xt(C.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(bn.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${xn}. Try again.
138
- `));}}async function oE(){let e=(await Xt(C.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await Xt(C.cyan(" ? ")+"Enter your email address: ")).trim();if(In.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${vn}. Try again.
137
+ `),(await qt(C.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function fg(e,t,r){try{await Oc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof on))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${nn()} and retry.`,{cause:n});if(!await rE())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Oc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function nE(){if((await qt(C.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await qt(C.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(bn.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${xn}. Try again.
138
+ `));}}async function oE(){let e=(await qt(C.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await qt(C.cyan(" ? ")+"Enter your email address: ")).trim();if(In.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${vn}. Try again.
139
139
  `));}}async function gg(e,t){process.stdout.write(C.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await oi(e,t);return r?process.stdout.write(C.yellow(` \u26A0 npm install failed. Please contact Flow support.
140
140
  `)):o?process.stdout.write(C.yellow(` \u26A0 Unexpected error. Please contact Flow support.
141
141
  `)):n?process.stdout.write(C.yellow(`
142
142
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
143
143
  `)):process.stdout.write(C.green(` done
144
- `)),{initFailed:n}}async function hg(){for(let e=1;e<=dg;e++)try{return await wi()}catch{if(e===dg)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function yg(){let e=await hg();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await Xt(C.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
144
+ `)),{initFailed:n}}async function hg(){for(let e=1;e<=dg;e++)try{return await wi()}catch{if(e===dg)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function yg(){let e=await hg();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await qt(C.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
145
145
  `+C.cyan(" ? ")+`Starter Kit:
146
146
  `),e.forEach((r,n)=>{process.stdout.write(` ${C.cyan(`${n+1})`)} ${y(r.name)}
147
147
  `);}),process.stdout.write(`
148
- `);;){let r=(await Xt(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),n=parseInt(r,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
148
+ `);;){let r=(await qt(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),n=parseInt(r,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
149
149
  `));}}async function wg(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
150
150
  Starter kit '${y(e.name)}' has no plugins to install.
151
151
  `)),true;process.stdout.write(`
@@ -158,7 +158,7 @@ This will run: ${s}
158
158
  `),process.stdout.write(C.bold(` Personalize your Claude Code
159
159
  `)),process.stdout.write(C.dim(` This plugin helps Claude understand your preferences and work style.
160
160
 
161
- `));let e=(await Xt(C.cyan(" ? ")+`Install ${he}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){P(E.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(`
161
+ `));let e=(await qt(C.cyan(" ? ")+`Install ${he}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){P(E.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(`
162
162
  You can always install it later from the catalog.
163
163
  `));return}P(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(` Installing ${he}...`));try{await He(he),process.stdout.write(C.green(` done
164
164
  `));}catch(t){if(t instanceof Ze)process.stdout.write(C.green(` already installed
@@ -186,7 +186,7 @@ This will run: ${s}
186
186
  `)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return Rt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${s}
187
187
  `)),1}}async function iE(e,t){pg(),Rt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
188
188
  `),process.stdout.write(mg+`
189
- `);let r=(await Xt(C.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Rt.error("[auth] Validation failed: JWT is required"),process.stderr.write(C.red(` \u2717 JWT is required
189
+ `);let r=(await qt(C.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Rt.error("[auth] Validation failed: JWT is required"),process.stderr.write(C.red(` \u2717 JWT is required
190
190
  `)),1;let n;try{n=Do(r);}catch(l){let u=y(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${u}
191
191
  `)),1}let o=e??await nE(),s=t??await oE();o&&Dt(o),Rt.debug(`[${n.tenant}] Authenticating tenant`);try{await Zr(n);}catch(l){let u=y(l instanceof Error?l.message:"unknown error");return Rt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${u}
192
192
  `)),1}let{initFailed:i}=await gg(o,s),a=await yg();return await fg({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await wg(a):process.stdout.write(C.dim(`
@@ -196,42 +196,42 @@ This will run: ${s}
196
196
 
197
197
  `)),i&&process.stdout.write(C.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
198
198
  `)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return Rt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${n}
199
- `)),1}}async function Oc(e={}){if(e.jwt)return sE({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!bn.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${xn}.
199
+ `)),1}}async function Nc(e={}){if(e.jwt)return sE({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!bn.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${xn}.
200
200
  `)),1;if(e.customEmail!==void 0&&!In.test(e.customEmail))return process.stderr.write(C.red(` \u2717 ${vn}.
201
201
  `)),1;try{return await iE(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
202
202
  `),130;throw t}}async function aE(){try{return process.stdout.write(`
203
- `),(await Xt(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
203
+ `),(await qt(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
204
204
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
205
205
  `),130;throw e}}async function bg(e){if(!await re())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
206
- `)),0;if(!e){let t=await aE();if(t!==null)return t}try{return await Fu(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
206
+ `)),0;if(!e){let t=await aE();if(t!==null)return t}try{return await ju(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
207
207
  `)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
208
208
  `)),1}}async function xg(){let e=await re();return e?await Tr()?(process.stdout.write(`
209
209
  `+C.bold(` Authenticated
210
210
  `)),process.stdout.write(C.dim(" Tenant: ")+y(e.tenant)+`
211
211
  `),process.stdout.write(C.dim(" Client ID: ")+y(e.clientId)+`
212
212
  `),process.stdout.write(C.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
213
- `),process.stdout.write(C.dim(" Config: ")+y(await ju())+`
213
+ `),process.stdout.write(C.dim(" Config: ")+y(await Ku())+`
214
214
  `),process.stdout.write(`
215
- `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();$e();F();function Ig(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function cE(e,t,r=process.env){return Ig(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Ig(r.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:t?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:t?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function vg(e){switch(e.reason){case "env-disabled":return "DISABLE_AUTOUPDATER is set";case "env-forced":return "FORCE_AUTOUPDATE_PLUGINS is set";case "flag":return e.enabled?"autoUpdate: true":"autoUpdate: false";case "default":return "default (no explicit flag)"}}function ia(e=process.env){let t=Wr();if(!ue__default.existsSync(t))return [];try{let r=JSON.parse(ue__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>cE(n,o,e))}catch{return []}}function Eg(){let e=Wr(),t={fixed:[],skipped:[]};if(!ue__default.existsSync(e))return t;let r;try{r=JSON.parse(ue__default.readFileSync(e,"utf-8"));}catch{return t.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),t}let n=false;for(let o of Sr){let s=r[o];if(!s){t.skipped.push({name:o,reason:"not registered on this machine"});continue}if("autoUpdate"in s){t.skipped.push({name:o,reason:s.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}s.autoUpdate=true,t.fixed.push(o),n=true;}if(n){let o=`${e}.${randomUUID()}.tmp`;ue__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(o,e);}return t}async function uE(e){let t=fe(),r;try{r=await or(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(Ir(r.map(o=>({...o,installed:n.has(o.name)}))),0):(xr(["","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 dE(e){let t=fe(),r=await or(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ge(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(Ir(o),0):o.length===0?(I("All plugins are up to date."),0):(xr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
215
+ `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();$e();F();function Ig(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function cE(e,t,r=process.env){return Ig(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Ig(r.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:t?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:t?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function vg(e){switch(e.reason){case "env-disabled":return "DISABLE_AUTOUPDATER is set";case "env-forced":return "FORCE_AUTOUPDATE_PLUGINS is set";case "flag":return e.enabled?"autoUpdate: true":"autoUpdate: false";case "default":return "default (no explicit flag)"}}function aa(e=process.env){let t=Wr();if(!ue__default.existsSync(t))return [];try{let r=JSON.parse(ue__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>cE(n,o,e))}catch{return []}}function Eg(){let e=Wr(),t={fixed:[],skipped:[]};if(!ue__default.existsSync(e))return t;let r;try{r=JSON.parse(ue__default.readFileSync(e,"utf-8"));}catch{return t.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),t}let n=false;for(let o of Sr){let s=r[o];if(!s){t.skipped.push({name:o,reason:"not registered on this machine"});continue}if("autoUpdate"in s){t.skipped.push({name:o,reason:s.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}s.autoUpdate=true,t.fixed.push(o),n=true;}if(n){let o=`${e}.${randomUUID()}.tmp`;ue__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),ue__default.renameSync(o,e);}return t}async function uE(e){let t=fe(),r;try{r=await sr(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(Ir(r.map(o=>({...o,installed:n.has(o.name)}))),0):(xr(["","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 dE(e){let t=fe(),r=await sr(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ge(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(Ir(o),0):o.length===0?(I("All plugins are up to date."),0):(xr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
216
216
  ${o.length} plugin(s) outdated.
217
- `),0)}async function pE(e){let t=fe();if(P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return Ir(t),0;let r;try{r=await or(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(ia().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=ls.indexOf(i.scope??"user"),u=ls.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return xr(["Name","Version","Type","Origin","Scope","Project","Status","Auto-Update","Installed at"],s.map(i=>{let a=n.get(i.name),l=a?.type??"bundle",u=a?.origin??dc(i.marketplace),c=i.marketplace?o.get(i.marketplace):void 0,d=c===void 0?"n/a":c?"on":"off";return [i.name??"",i.version??"n/a",br[l]?.label??"Plugin",u,i.scope??"user",rf(i),i.status??"enabled",d,Lt(i.installedAt??"")]})),process.stdout.write(`
217
+ `),0)}async function pE(e){let t=fe();if(P(E.CLI_CATALOG_VIEWED,{interface:ee().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return I("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return Ir(t),0;let r;try{r=await sr(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(aa().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=ls.indexOf(i.scope??"user"),u=ls.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return xr(["Name","Version","Type","Origin","Scope","Project","Status","Auto-Update","Installed at"],s.map(i=>{let a=n.get(i.name),l=a?.type??"bundle",u=a?.origin??pc(i.marketplace),c=i.marketplace?o.get(i.marketplace):void 0,d=c===void 0?"n/a":c?"on":"off";return [i.name??"",i.version??"n/a",br[l]?.label??"Plugin",u,i.scope??"user",rf(i),i.status??"enabled",d,Lt(i.installedAt??"")]})),process.stdout.write(`
218
218
  ${t.length} plugin(s) installed.
219
- `),0}async function Pg(e){if(!await Y())return 1;try{return e.available?await uE(e):e.outdated?await dE(e):await pE(e)}catch(t){return v(t instanceof Error?t.message:"Failed to list plugins."),1}}Nr();N();F();function aa(e){let t=Te().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function qt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function la(e,t,r){return I(`${e} is already installed ${qt(r)}.`),X(` Move it to ${Xe[t].actionLabel} instead? This uninstalls it from ${qt(r)} first. [y/N] `)}N();F();R();var be=b("manage"),mE=["local","project","user"];async function fE(){return xi("Which scope do you want to uninstall from?",mE.map(e=>({value:e,label:Xe[e].actionLabel,description:Xe[e].description})))}function ua(e,t){return t?fe().find(r=>r.name===e&&r.scope===t):fe().find(r=>r.name===e)}function gE(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=ca({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function hE(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(Hn(e,r.scope));if(!await X(`${t}Install external plugin "${i}"?
219
+ `),0}async function Pg(e){if(!await Y())return 1;try{return e.available?await uE(e):e.outdated?await dE(e):await pE(e)}catch(t){return v(t instanceof Error?t.message:"Failed to list plugins."),1}}Nr();N();F();function la(e){let t=xe().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function Yt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function ca(e,t,r){return I(`${e} is already installed ${Yt(r)}.`),X(` Move it to ${Xe[t].actionLabel} instead? This uninstalls it from ${Yt(r)} first. [y/N] `)}N();F();R();var be=b("manage"),mE=["local","project","user"];async function fE(){return Ii("Which scope do you want to uninstall from?",mE.map(e=>({value:e,label:Xe[e].actionLabel,description:Xe[e].description})))}function da(e,t){return t?fe().find(r=>r.name===e&&r.scope===t):fe().find(r=>r.name===e)}function gE(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,I(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=ua({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function hE(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(Hn(e,r.scope));if(!await X(`${t}Install external plugin "${i}"?
220
220
  This will run: ${a}
221
- [y/N] `))return be.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=ca({text:`${t}Installing ${e}...`}).start());}let s=o?gE(t,o):void 0;try{let i=await Vm(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?_e({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?oe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):q(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=te(i);return r.silent?_e({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function yE(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=aa(e);if(!o)return {proceed:true,spinner:n};n?.stop();let s=r.scope??"user";if(o.scope===s){let c=`${e} is already installed ${qt(o)}. Use --force to reinstall.`;return r.silent?oe({status:"already_installed",plugin:e,message:c}):I(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${qt(o)}. Re-run with --force to install here too.`;return r.silent?oe({status:"already_installed",plugin:e,message:c}):I(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await la(e,s,o)?await ms(e,{force:true,scope:o.scope})!==0?(I(`${t}Could not remove ${e} from ${qt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:ca({text:`${t}Installing ${e}...`}).start()}:(I(`${t}Skipped ${e}.`),{proceed:false})}async function wE(e,t,r){let n=r.silent?void 0:ca({text:`${t}Installing ${e}...`}).start();if(jn(e))return hE(e,t,r,n);let o=await yE(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await He(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=Un(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?oe({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):q(`${t}${e} v${s.version} installed successfully`),{name:e,success:!0,version:s.version,duration_ms:s.duration_ms}}catch(s){if(n?.stop(),s instanceof Ze)return r.silent?oe({status:"already_installed",plugin:e,message:s.message}):I(`${t}${s.message}`),{name:e,success:true};let i=te(s);return r.silent?_e({status:"error",plugin:e,message:i}):v(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function SE(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
222
- Installation summary: ${t} succeeded, ${r} failed`);}async function bE(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await or();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function go(e,t={}){if(!await Y())return 1;let r=[],n=await bE(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await wE(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?oe({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):SE(r)),r.some(o=>!o.success)?1:0}async function ms(e,t){if(!await Y())return 1;let r=t.scope,n=t.isInteractive??!!process.stdin.isTTY;!r&&n&&(r=await fE());let o=r??"user";if(be.debug(`[${e}] Looking up installed plugin`),!t.force){let s=ua(e,o);if(!s)return be.error(`[${e}] Plugin is not installed`),v(r?`Plugin "${e}" is not installed in ${r} scope`:`Plugin "${e}" is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`),1;let i=y(s.name),a=s.version?y(s.version):void 0,l=` (${o})`;if(!await X(`Remove ${i} ${a?`v${a}`:"(n/a)"}${l}? [y/N] `))return be.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return be.debug(`[${e}] Uninstalling plugin (scope: ${o})`),await Jo(e,o),be.info(`[${e}] Uninstalled successfully`),q("Plugin removed successfully"),0}catch(s){return be.error(`[${e}] Failed to uninstall: ${te(s)}`),v(te(s)),1}}async function kg(e,t={}){if(!await Y())return 1;be.debug(`[${e}] Looking up installed plugin`);let r=ua(e,t.scope);if(!r)return be.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return be.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return be.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Wo(e,"enabled",t.scope),be.info(`[${e}] Enabled successfully`),q(`${r.name} enabled successfully`),0}catch(n){return be.error(`[${e}] Failed to enable: ${te(n)}`),v(te(n)),1}}async function Ag(e,t={}){if(!await Y())return 1;be.debug(`[${e}] Looking up installed plugin`);let r=ua(e,t.scope);if(!r)return be.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return be.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return be.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Wo(e,"disabled",t.scope),be.info(`[${e}] Disabled successfully`),q(`${r.name} disabled successfully`),0}catch(n){return be.error(`[${e}] Failed to disable: ${te(n)}`),v(te(n)),1}}async function Rg(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await Fi(e,r);return r.silent?oe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):q(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Or)return r.silent?oe({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=te(n);return r.silent?_e({status:"error",plugin:e,message:o}):v(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function xE(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
223
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function IE(e,t,r){try{let n=await Jn(e,r.source);Ge(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return v(te(n)),1}return 0}function vE(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function EE(e,t,r){let n=t.get(e.name);return n?e.version&&Ge(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function PE(e,t){try{let r=await or(t.source),n=vE(r),o=0;for(let s of e)EE(s,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return v(te(r)),1}return 0}async function TE(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Rg(e[n].name,o,t);r.push(s);}return t.silent?oe({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}:{}}))}):xE(r),r.some(n=>!n.success)?1:0}async function $g(e,t={}){if(!await Y())return 1;if(e){let o=ua(e,t.scope);return o?t.dryRun?IE(e,o.version??"",t):(await Rg(e,"",t)).success?0:1:(t.silent?_e({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):v(`Plugin "${e}" is not installed`),1)}let n=fe().filter(o=>Sr.includes(o.marketplace??""));return n.length===0?(t.silent?oe({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?PE(n,t):TE(n,t)}function Tg(e){for(let t of e)I(` ${t.pluginName}@${t.version} (${t.marketplace}) \u2014 ${Dr(t.sizeBytes)}`);}function Cg(e){for(let t of e)I(` ${t.pluginName}@${t.marketplace} (${t.scope}) \u2014 ${t.projectPath} (no longer exists)`);}async function _g(e={}){if(!await Y())return 1;let t=jp(),r=Hp();if(t.length===0&&r.length===0)return e.silent?oe({status:"empty",message:"Nothing to prune"}):I("Nothing to prune \u2014 no stale cached versions and no orphaned project entries."),0;let n=t.reduce((s,i)=>s+i.sizeBytes,0);if(e.dryRun)return e.silent?oe({status:"dry-run",candidates:t.map(s=>({plugin:s.pluginName,version:s.version,marketplace:s.marketplace,path:s.path,size_bytes:s.sizeBytes})),total_bytes:n,orphaned_entries:r.map(s=>({plugin:s.pluginName,marketplace:s.marketplace,scope:s.scope,project_path:s.projectPath}))}):(t.length>0&&(I(`Would remove ${t.length} stale version(s), freeing ${Dr(n)}:`),Tg(t)),r.length>0&&(I(`Would remove ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),Cg(r))),0;if(!e.force){if(e.silent)return _e({status:"error",message:"--silent requires --force to delete without an interactive confirmation"}),1;if(t.length>0&&(I(`Found ${t.length} stale version(s), ${Dr(n)} total:`),Tg(t)),r.length>0&&(I(`Found ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),Cg(r)),!await X(`Remove these ${t.length+r.length} item(s)? [y/N] `))return I("Operation cancelled."),0}let o=await Kp(t);if(Vp(r),e.silent)oe({status:"summary",removed:o.removed.length,failed:o.failed.length,freed_bytes:o.freedBytes,orphaned_entries_removed:r.length,details:o.failed.map(s=>({plugin:s.candidate.pluginName,version:s.candidate.version,error:s.error}))});else if(q(`Removed ${o.removed.length} stale version(s), freed ${Dr(o.freedBytes)}`+(r.length>0?`, removed ${r.length} orphaned project entr${r.length===1?"y":"ies"}`:"")),o.failed.length>0){v(`Failed to remove ${o.failed.length} version(s):`);for(let{candidate:s,error:i}of o.failed)v(` ${s.pluginName}@${s.version}: ${i}`);}return o.failed.length>0?1:0}N();R();var fs=b("cli:bundle");function CE(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function kE(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
221
+ [y/N] `))return be.debug(`[${e}] Installation cancelled by user`),r.silent||I(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=ua({text:`${t}Installing ${e}...`}).start());}let s=o?gE(t,o):void 0;try{let i=await Vm(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?_e({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?oe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):q(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=te(i);return r.silent?_e({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function yE(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=la(e);if(!o)return {proceed:true,spinner:n};n?.stop();let s=r.scope??"user";if(o.scope===s){let c=`${e} is already installed ${Yt(o)}. Use --force to reinstall.`;return r.silent?oe({status:"already_installed",plugin:e,message:c}):I(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${Yt(o)}. Re-run with --force to install here too.`;return r.silent?oe({status:"already_installed",plugin:e,message:c}):I(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await ca(e,s,o)?await ms(e,{force:true,scope:o.scope})!==0?(I(`${t}Could not remove ${e} from ${Yt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:ua({text:`${t}Installing ${e}...`}).start()}:(I(`${t}Skipped ${e}.`),{proceed:false})}async function wE(e,t,r){let n=r.silent?void 0:ua({text:`${t}Installing ${e}...`}).start();if(jn(e))return hE(e,t,r,n);let o=await yE(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await He(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=Un(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?oe({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):q(`${t}${e} v${s.version} installed successfully`),{name:e,success:!0,version:s.version,duration_ms:s.duration_ms}}catch(s){if(n?.stop(),s instanceof Ze)return r.silent?oe({status:"already_installed",plugin:e,message:s.message}):I(`${t}${s.message}`),{name:e,success:true};let i=te(s);return r.silent?_e({status:"error",plugin:e,message:i}):v(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function SE(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;I(`
222
+ Installation summary: ${t} succeeded, ${r} failed`);}async function bE(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await sr();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function go(e,t={}){if(!await Y())return 1;let r=[],n=await bE(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await wE(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?oe({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):SE(r)),r.some(o=>!o.success)?1:0}async function ms(e,t){if(!await Y())return 1;let r=t.scope,n=t.isInteractive??!!process.stdin.isTTY;!r&&n&&(r=await fE());let o=r??"user";if(be.debug(`[${e}] Looking up installed plugin`),!t.force){let s=da(e,o);if(!s)return be.error(`[${e}] Plugin is not installed`),v(r?`Plugin "${e}" is not installed in ${r} scope`:`Plugin "${e}" is not installed in user (global) scope. Pass --scope project or --scope local to remove it from this repo instead.`),1;let i=y(s.name),a=s.version?y(s.version):void 0,l=` (${o})`;if(!await X(`Remove ${i} ${a?`v${a}`:"(n/a)"}${l}? [y/N] `))return be.debug(`[${e}] Uninstall cancelled by user`),I("Operation cancelled."),0}try{return be.debug(`[${e}] Uninstalling plugin (scope: ${o})`),await Jo(e,o),be.info(`[${e}] Uninstalled successfully`),q("Plugin removed successfully"),0}catch(s){return be.error(`[${e}] Failed to uninstall: ${te(s)}`),v(te(s)),1}}async function kg(e,t={}){if(!await Y())return 1;be.debug(`[${e}] Looking up installed plugin`);let r=da(e,t.scope);if(!r)return be.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return be.debug(`[${e}] Already enabled, skipping`),I(`${r.name} is already enabled`),0;try{return be.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Wo(e,"enabled",t.scope),be.info(`[${e}] Enabled successfully`),q(`${r.name} enabled successfully`),0}catch(n){return be.error(`[${e}] Failed to enable: ${te(n)}`),v(te(n)),1}}async function Ag(e,t={}){if(!await Y())return 1;be.debug(`[${e}] Looking up installed plugin`);let r=da(e,t.scope);if(!r)return be.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return be.debug(`[${e}] Already disabled, skipping`),I(`${r.name} is already disabled`),0;try{return be.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Wo(e,"disabled",t.scope),be.info(`[${e}] Disabled successfully`),q(`${r.name} disabled successfully`),0}catch(n){return be.error(`[${e}] Failed to disable: ${te(n)}`),v(te(n)),1}}async function Rg(e,t,r){r.silent||I(`${t}Updating ${e}...`);try{let n=await ji(e,r);return r.silent?oe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):q(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Or)return r.silent?oe({status:"up_to_date",plugin:e,message:n.message}):I(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=te(n);return r.silent?_e({status:"error",plugin:e,message:o}):v(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function xE(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;I(`
223
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function IE(e,t,r){try{let n=await Jn(e,r.source);Ge(t,n.version,r.force)?I(`Would update ${e}: v${t} \u2192 v${n.version}`):I(`${e} is already up to date (v${t})`);}catch(n){return v(te(n)),1}return 0}function vE(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function EE(e,t,r){let n=t.get(e.name);return n?e.version&&Ge(e.version,n,r)?(I(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(I(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(I(`Skipping ${e.name}: not found in catalog`),false)}async function PE(e,t){try{let r=await sr(t.source),n=vE(r),o=0;for(let s of e)EE(s,n,t.force)&&o++;o===0&&I("All plugins are up to date");}catch(r){return v(te(r)),1}return 0}async function TE(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Rg(e[n].name,o,t);r.push(s);}return t.silent?oe({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}:{}}))}):xE(r),r.some(n=>!n.success)?1:0}async function $g(e,t={}){if(!await Y())return 1;if(e){let o=da(e,t.scope);return o?t.dryRun?IE(e,o.version??"",t):(await Rg(e,"",t)).success?0:1:(t.silent?_e({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):v(`Plugin "${e}" is not installed`),1)}let n=fe().filter(o=>Sr.includes(o.marketplace??""));return n.length===0?(t.silent?oe({status:"empty",message:"No plugins installed"}):I("No plugins installed"),0):t.dryRun?PE(n,t):TE(n,t)}function Tg(e){for(let t of e)I(` ${t.pluginName}@${t.version} (${t.marketplace}) \u2014 ${Dr(t.sizeBytes)}`);}function Cg(e){for(let t of e)I(` ${t.pluginName}@${t.marketplace} (${t.scope}) \u2014 ${t.projectPath} (no longer exists)`);}async function _g(e={}){if(!await Y())return 1;let t=jp(),r=Hp();if(t.length===0&&r.length===0)return e.silent?oe({status:"empty",message:"Nothing to prune"}):I("Nothing to prune \u2014 no stale cached versions and no orphaned project entries."),0;let n=t.reduce((s,i)=>s+i.sizeBytes,0);if(e.dryRun)return e.silent?oe({status:"dry-run",candidates:t.map(s=>({plugin:s.pluginName,version:s.version,marketplace:s.marketplace,path:s.path,size_bytes:s.sizeBytes})),total_bytes:n,orphaned_entries:r.map(s=>({plugin:s.pluginName,marketplace:s.marketplace,scope:s.scope,project_path:s.projectPath}))}):(t.length>0&&(I(`Would remove ${t.length} stale version(s), freeing ${Dr(n)}:`),Tg(t)),r.length>0&&(I(`Would remove ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),Cg(r))),0;if(!e.force){if(e.silent)return _e({status:"error",message:"--silent requires --force to delete without an interactive confirmation"}),1;if(t.length>0&&(I(`Found ${t.length} stale version(s), ${Dr(n)} total:`),Tg(t)),r.length>0&&(I(`Found ${r.length} orphaned project entr${r.length===1?"y":"ies"}:`),Cg(r)),!await X(`Remove these ${t.length+r.length} item(s)? [y/N] `))return I("Operation cancelled."),0}let o=await Kp(t);if(Vp(r),e.silent)oe({status:"summary",removed:o.removed.length,failed:o.failed.length,freed_bytes:o.freedBytes,orphaned_entries_removed:r.length,details:o.failed.map(s=>({plugin:s.candidate.pluginName,version:s.candidate.version,error:s.error}))});else if(q(`Removed ${o.removed.length} stale version(s), freed ${Dr(o.freedBytes)}`+(r.length>0?`, removed ${r.length} orphaned project entr${r.length===1?"y":"ies"}`:"")),o.failed.length>0){v(`Failed to remove ${o.failed.length} version(s):`);for(let{candidate:s,error:i}of o.failed)v(` ${s.pluginName}@${s.version}: ${i}`);}return o.failed.length>0?1:0}N();R();var fs=b("cli:bundle");function CE(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function kE(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
224
224
  Bundle: ${y(e)} (${t.length} artifacts)
225
225
  `);for(let o of t)process.stdout.write(`${CE(o)}
226
226
  `);process.stdout.write(`
227
227
  ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
228
228
 
229
- `);}async function Mg(e){if(!e.trim())return v("Bundle name cannot be empty."),1;if(!await Y())return 1;fs.debug(`Fetching bundle "${e}"`);let r;try{r=await Vi(e);}catch(a){return a instanceof lo||a instanceof as?(v(a.message),1):(v(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(fs.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),kE(r.title,n),o.length===0)return v("No artifacts available for installation in this bundle."),1;if(!await X(`Install ${o.length} artifact(s)? [Y/n] `))return fs.debug("Installation cancelled by user"),0;fs.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Oi(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
229
+ `);}async function Mg(e){if(!e.trim())return v("Bundle name cannot be empty."),1;if(!await Y())return 1;fs.debug(`Fetching bundle "${e}"`);let r;try{r=await Gi(e);}catch(a){return a instanceof lo||a instanceof as?(v(a.message),1):(v(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(fs.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),kE(r.title,n),o.length===0)return v("No artifacts available for installation in this bundle."),1;if(!await X(`Install ${o.length} artifact(s)? [Y/n] `))return fs.debug("Installation cancelled by user"),0;fs.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Ni(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
230
230
  `),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
231
231
  `),a===l&&process.stdout.write(`
232
232
  `);}});if(fs.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&q(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");v(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");I(`${i.skipped} unavailable: ${a}`);}return 0}Nr();N();R();var Lg=b("marketplace");function RE(e){return `claude plugin marketplace add ${e}`}async function Dg(e,t){if(!await Y())return 1;let r;try{r=yi(e);}catch(s){let i=te(s);return t.silent?_e({status:"error",source:e,message:i}):v(i),1}Lg.debug(`[marketplace] Adding marketplace source: ${r}`);let n=RE(r);if(!t.force){let s=y(r),i=y(n);if(!await X(`Add marketplace "${s}"?
233
233
  This will run: ${i}
234
- [y/N] `))return Lg.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:ca({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await De(n);return o?.stop(),s.exitCode!==0?(t.silent?_e({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(v(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&I(`stdout: ${s.stdout}`)),1):(t.silent?oe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(q(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&I(s.stdout)),0)}catch(s){o?.stop();let i=te(s);return t.silent?_e({status:"error",source:r,message:i}):v(`Failed to add marketplace "${r}": ${i}`),1}}Ce();N();async function LE(){return await re()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function DE(){let e=Date.now();try{await or();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 OE(){return await Tr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function NE(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function UE(){let e=ia();if(e.length!==0){process.stdout.write(`
234
+ [y/N] `))return Lg.debug("[marketplace] Operation cancelled by user"),I("Operation cancelled."),0}let o=t.silent?void 0:ua({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await De(n);return o?.stop(),s.exitCode!==0?(t.silent?_e({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(v(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&I(`stdout: ${s.stdout}`)),1):(t.silent?oe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(q(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&I(s.stdout)),0)}catch(s){o?.stop();let i=te(s);return t.silent?_e({status:"error",source:r,message:i}):v(`Failed to add marketplace "${r}": ${i}`),1}}Ce();N();async function LE(){return await re()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function DE(){let e=Date.now();try{await sr();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 OE(){return await Tr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function NE(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function UE(){let e=aa();if(e.length!==0){process.stdout.write(`
235
235
  `+C.bold(` Marketplace Auto-Update
236
236
 
237
237
  `));for(let t of e){let r=t.enabled?C.green("[ON] "):C.dim("[OFF]"),n=y(t.name).padEnd(20),o=y(vg(t));process.stdout.write(` ${r} ${n} ${C.dim(o)}
@@ -254,26 +254,26 @@ This will run: ${i}
254
254
 
255
255
  `)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
256
256
 
257
- `)),1)}Ce();Yr();F();async function Ng(e){let t=await re(),r=Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Zt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await fp.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}Rn();Ks();Ce();N();R();var jE=b("commands:usage"),da=20,Ug="EMAIL",Bg="MONTHLY CONSUMPTION (USD)",Fg="STATUS";function KE(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*da),n=da-r,o=C.green;return t>=90?o=C.red:t>=70&&(o=C.yellow),o("\u2588".repeat(r))+C.dim("\u2591".repeat(n))}function jg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function HE(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?C.green(`\u2299 ${n}`):t==="warning"?C.yellow(`\u26A0 ${n}`):t==="blocked"?C.red("\u2717 Budget limit reached"):C.red(`\u2717 ${n}`)}function VE(e){let t=Lt(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function GE(e){try{let t=await kn();if(t?.email)return y(t.email);let r=An(e);return y(r.email??"")}catch(t){return jE.debug(`JWT email decode failed: ${String(t)}`),""}}async function Kg(e){if(!await Y())return 1;let r;try{r=await Nt();}catch(h){return v(`Authentication error: ${te(h)}`),1}let n;try{n=await Ng(r);}catch(h){return v(`Failed to fetch usage data: ${te(h)}`),1}if(e.json)return Ir(n),0;let o=await GE(r)||y(n.user_id),s=jg(n.consumed_usd),i=jg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(Ug.length,o.length+2),c=Math.max(Bg.length,da+2+l.length),d=` ${Ug.padEnd(u)} ${Bg.padEnd(c)} ${Fg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(Fg.length)}`,p=`${C.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${KE(n.percentage)} ${l.padEnd(c-da-2)}`,g=` ${C.dim("Resets")} ${VE(n.renewal_date)}`;return process.stdout.write(`
257
+ `)),1)}Ce();Yr();F();async function Ng(e){let t=await re(),r=Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Qt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await gp.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}Rn();Ks();Ce();N();R();var jE=b("commands:usage"),pa=20,Ug="EMAIL",Bg="MONTHLY CONSUMPTION (USD)",Fg="STATUS";function KE(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*pa),n=pa-r,o=C.green;return t>=90?o=C.red:t>=70&&(o=C.yellow),o("\u2588".repeat(r))+C.dim("\u2591".repeat(n))}function jg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function HE(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?C.green(`\u2299 ${n}`):t==="warning"?C.yellow(`\u26A0 ${n}`):t==="blocked"?C.red("\u2717 Budget limit reached"):C.red(`\u2717 ${n}`)}function VE(e){let t=Lt(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function GE(e){try{let t=await kn();if(t?.email)return y(t.email);let r=An(e);return y(r.email??"")}catch(t){return jE.debug(`JWT email decode failed: ${String(t)}`),""}}async function Kg(e){if(!await Y())return 1;let r;try{r=await Nt();}catch(h){return v(`Authentication error: ${te(h)}`),1}let n;try{n=await Ng(r);}catch(h){return v(`Failed to fetch usage data: ${te(h)}`),1}if(e.json)return Ir(n),0;let o=await GE(r)||y(n.user_id),s=jg(n.consumed_usd),i=jg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(Ug.length,o.length+2),c=Math.max(Bg.length,pa+2+l.length),d=` ${Ug.padEnd(u)} ${Bg.padEnd(c)} ${Fg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(Fg.length)}`,p=`${C.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${KE(n.percentage)} ${l.padEnd(c-pa-2)}`,g=` ${C.dim("Resets")} ${VE(n.renewal_date)}`;return process.stdout.write(`
258
258
  `),process.stdout.write(C.dim(d)+`
259
259
  `),process.stdout.write(C.dim(m)+`
260
260
  `),process.stdout.write(` ${p} ${f} ${HE(n.status)}
261
261
  `),process.stdout.write(g+`
262
262
  `),process.stdout.write(`
263
- `),0}var zE=["github.com","www.github.com"],XE=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,qE=/^([^@]+)@(.+)$/;function YE(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Nc(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 ZE(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=Nc(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Nc(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function pa(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(YE(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:")&&zE.includes(r.hostname))return ZE(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(XE);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(qE);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=Nc(m));}return d}}return {type:"git",url:t}}function ma(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 Hg(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 Bc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Jg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function nP(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Uc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function gs(e){try{let t=await readFile(e,"utf-8"),{data:r}=Hg(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 Wg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Uc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Bc.has(a.name)).map(a=>Wg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function ha(e,t){let r=[],n=new Set;if(t&&!nP(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Uc(o)){let i=await gs(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 Uc(u)){let c=await gs(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Wg(o);for(let a of i){let l=await gs(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function zg(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}$e();var Zg=1,cP={retries:5,minTimeout:50};async function Qg(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:cP});try{return await t()}finally{await r();}}function Xg(){return {version:Zg,skills:{}}}async function ya(e){let t=Io(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Zg?Xg():n}catch{return Xg()}}function uP(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function eh(e,t){let r=Io(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:uP(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
264
- `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function th(e,t,r){let n=Io(r);await Qg(n,async()=>{let o=await ya(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await eh(o,r);});}async function rh(e,t){let r=Io(t);await Qg(r,async()=>{let n=await ya(t);e in n.skills&&(delete n.skills[e],await eh(n,t));});}$e();R();var nh=b("skillInstaller");async function wP(e,t,r,n){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:ee().interfaceType});}catch(o){nh.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function SP(e,t){try{await P(E.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:ee().interfaceType});}catch(r){nh.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function bP(e,t){await cp(e,t,{recursive:true,dereference:false,filter:r=>{if(Bc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function xP(e,t,r){let n=dt(e.name),o=zr(t),s=join(o,n);if(!Jg(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 bP(e.path,s);let a=ma(r)??r.url;return await th(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 oh(e,t){let r=pa(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 Qe(r.url,r.ref),o=n;let s=await ha(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?zg(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await xP(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await wP(c.name,t.scope,u,p):await SP(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await et(n).catch(()=>{});}}$e();N();R();var TP=b("skills");async function CP(e){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:ee().interfaceType});}catch(t){TP.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function kP(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function AP(e){let t=pa(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return v("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${y(e)}...`),r=await Qe(t.url,t.ref),n=r;let o=await ha(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let i=ma(t)??y(e);I(`Found ${o.length} skill(s) in ${i}:
263
+ `),0}var zE=["github.com","www.github.com"],XE=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,qE=/^([^@]+)@(.+)$/;function YE(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Uc(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 ZE(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=Uc(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Uc(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ma(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(YE(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:")&&zE.includes(r.hostname))return ZE(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(XE);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(qE);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=Uc(m));}return d}}return {type:"git",url:t}}function fa(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 Hg(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 Fc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Jg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function nP(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Bc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function gs(e){try{let t=await readFile(e,"utf-8"),{data:r}=Hg(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 Wg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Bc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Fc.has(a.name)).map(a=>Wg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function ya(e,t){let r=[],n=new Set;if(t&&!nP(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Bc(o)){let i=await gs(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 Bc(u)){let c=await gs(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Wg(o);for(let a of i){let l=await gs(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function zg(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}$e();var Zg=1,cP={retries:5,minTimeout:50};async function Qg(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bw.lock(e+".lock",{realpath:false,retries:cP});try{return await t()}finally{await r();}}function Xg(){return {version:Zg,skills:{}}}async function wa(e){let t=Io(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Zg?Xg():n}catch{return Xg()}}function uP(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function eh(e,t){let r=Io(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:uP(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
264
+ `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function th(e,t,r){let n=Io(r);await Qg(n,async()=>{let o=await wa(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await eh(o,r);});}async function rh(e,t){let r=Io(t);await Qg(r,async()=>{let n=await wa(t);e in n.skills&&(delete n.skills[e],await eh(n,t));});}$e();R();var nh=b("skillInstaller");async function wP(e,t,r,n){try{await P(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:ee().interfaceType});}catch(o){nh.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function SP(e,t){try{await P(E.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:ee().interfaceType});}catch(r){nh.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function bP(e,t){await cp(e,t,{recursive:true,dereference:false,filter:r=>{if(Fc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function xP(e,t,r){let n=dt(e.name),o=zr(t),s=join(o,n);if(!Jg(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 bP(e.path,s);let a=fa(r)??r.url;return await th(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 oh(e,t){let r=ma(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 Qe(r.url,r.ref),o=n;let s=await ya(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?zg(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await xP(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await wP(c.name,t.scope,u,p):await SP(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await et(n).catch(()=>{});}}$e();N();R();var TP=b("skills");async function CP(e){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:ee().interfaceType});}catch(t){TP.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function kP(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function AP(e){let t=ma(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return v("Invalid local path."),1;n=t.localPath;}else I(`Fetching skills from ${y(e)}...`),r=await Qe(t.url,t.ref),n=r;let o=await ya(n,t.subpath);if(o.length===0)return I("No skills found in this source."),0;let i=fa(t)??y(e);I(`Found ${o.length} skill(s) in ${i}:
265
265
  `);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${C.bold(l)} ${C.dim(u)}
266
266
  `);}return process.stdout.write(`
267
267
  `),0}catch(n){return n instanceof Br?v(n.message):v(n instanceof Error?n.message:String(n)),1}finally{r&&await et(r).catch(()=>{});}}function RP(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);q(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else v(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
268
- `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&v(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function ih(e,t){if(t.list)return AP(e);let r=t.global?"global":"project";try{let n=await oh(e,{scope:r,skillFilter:t.skill,yes:t.yes});return RP(n),n.failed>0?1:0}catch(n){return n instanceof Br?v(n.message):v(n instanceof Error?n.message:String(n)),1}}async function ah(e){let t=zr(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 gs(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 lh(e){let t=e.global?"global":"project",r=await ah(t),n=await ya(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[dt(i.name)]?.source}));return Ir(s),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
268
+ `);let t=e.source;e.installed>0&&I(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&v(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?I("No skills found in this source."):e.results.length===0&&e.discovered>0&&I(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function ih(e,t){if(t.list)return AP(e);let r=t.global?"global":"project";try{let n=await oh(e,{scope:r,skillFilter:t.skill,yes:t.yes});return RP(n),n.failed>0?1:0}catch(n){return n instanceof Br?v(n.message):v(n instanceof Error?n.message:String(n)),1}}async function ah(e){let t=zr(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 gs(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 lh(e){let t=e.global?"global":"project",r=await ah(t),n=await wa(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[dt(i.name)]?.source}));return Ir(s),0}if(r.length===0)return I(`No skills installed (${t==="global"?"global":"project"} scope).`),0;I(`${t==="global"?"Global":"Project"} skills (${r.length}):
269
269
  `);for(let s of r){let i=n.skills[dt(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?C.dim(` (${i})`):"";process.stdout.write(` ${C.bold(a)}${c}
270
270
  `),process.stdout.write(` ${C.dim(u)}
271
271
 
272
272
  `);}return 0}async function ch(e,t){let r=t.global?"global":"project";if(!e){let i=await ah(r);if(i.length===0)return I("No skills installed."),0;I("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
273
273
  `);return process.stdout.write(`
274
- `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=dt(e),o=zr(r),s=join(o,n);try{await stat(s);}catch{return v(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await kP(`Remove skill "${y(n)}"?`))return I("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await rh(n,r),await CP(n),q(`Skill "${y(n)}" removed.`),0}catch(i){return v(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();F();var wa=b("transfer"),jc=1;function $P(e){return e.marketplace&&e.marketplace!==Ue?`${e.name}@${e.marketplace}`:e.name}function _P(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&I(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),I(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function ph(e){let t=W__default.resolve(e.output);try{let r=fe(),n={version:jc,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 ue__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),q(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=te(r);return wa.error(`Export failed: ${n}`),v(`Failed to export plugins: ${n}`),1}}async function mh(e,t={}){if(!await Y())return 1;let r;try{let a=ue__default.readFileSync(W__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return v(`Failed to read import file "${e}": ${te(a)}`),1}if(r.version!==jc)return v(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${jc}`),1;if(!Array.isArray(r.plugins))return v('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return I("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;wa.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(wa.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&I(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(fe().map(l=>l.name));_P(n,a);}if(t.dryRun)return I("Dry-run mode: no plugins were installed"),0;if(n.length===0){I(`
275
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}I(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=$P(a);wa.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await go([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}I(`
276
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function D(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var LP=b("moduleProxy");function DP(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Yl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function fh(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await P(E.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{LP.warn(`Failed to emit proxy executed event: ${String(s)}`);}),D(o);}async function hh(e,t){let r=me.find(o=>o.alias===e);if(!r){v(`Unknown module alias: '${e}'`),D(1);return}if(!await Bt(r.binaryName)){v(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),D(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await jt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){v(`No supported installation method available for '${e}' on this platform.`),D(1);return}if(await DP("Would you like to install it now? [Y/n] ")){await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Mr(r,"inline",s);if(!a.success){v(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),D(1);return}await fh(r,t);}else I(`To install manually, run: flow modules install ${e}`),await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),D(1);return}await fh(r,t);}N();var BP=promisify(execFile);async function FP(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await BP(tr(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ye}`,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 jP(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ge(t,r)?"outdated":"installed"}async function Kc(){let e=await Promise.all(me.map(async t=>{let[r,n]=await Promise.all([Bt(t.binaryName),FP(t)]),s=lt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=jP(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return xr(["Name","Alias","Version","Status","Platform"],e),0}async function Sh(e){let t=me.find(i=>i.alias===e);if(!t)return v(`Unknown module alias: '${e}'`),1;let[r]=await uo([t]);if(r.alreadyInstalled){let i=lt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return I(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?v(`Module ${t.name} is not supported on ${process.platform}.${a}`):v(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=ca({text:`Installing ${t.name}...`}).start(),s;try{s=await Mr(t,"on_demand",n);}finally{o.stop();}return s.success?(q(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(v(s.error?.message??"Installation failed"),1)}async function yh(e,t){let r=ca({text:`Updating ${e.name}...`}).start(),n;try{n=await ri(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 bh(e){if(e!==null){let n=me.find(i=>i.alias===e);if(!n)return v(`Unknown module alias: '${e}'`),1;let o=lt(n.alias);return o?.installMethod?await yh(n,o.installedVersion??"unknown")==="error"?1:0:(v(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=sn().filter(n=>n.installMethod!==null);if(t.length===0)return I("No installed modules to update."),0;let r=0;for(let n of t){let o=me.find(i=>i.alias===n.alias);if(!o)continue;await yh(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var hs=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
274
+ `),I("Specify a skill name to remove: flow skills remove <name>"),1}let n=dt(e),o=zr(r),s=join(o,n);try{await stat(s);}catch{return v(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await kP(`Remove skill "${y(n)}"?`))return I("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await rh(n,r),await CP(n),q(`Skill "${y(n)}" removed.`),0}catch(i){return v(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();F();var Sa=b("transfer"),Kc=1;function $P(e){return e.marketplace&&e.marketplace!==Ue?`${e.name}@${e.marketplace}`:e.name}function _P(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&I(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),I(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function ph(e){let t=W__default.resolve(e.output);try{let r=fe(),n={version:Kc,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 ue__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),q(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=te(r);return Sa.error(`Export failed: ${n}`),v(`Failed to export plugins: ${n}`),1}}async function mh(e,t={}){if(!await Y())return 1;let r;try{let a=ue__default.readFileSync(W__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return v(`Failed to read import file "${e}": ${te(a)}`),1}if(r.version!==Kc)return v(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Kc}`),1;if(!Array.isArray(r.plugins))return v('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return I("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let u=`entry[${a}]`;Sa.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(Sa.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&I(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(fe().map(l=>l.name));_P(n,a);}if(t.dryRun)return I("Dry-run mode: no plugins were installed"),0;if(n.length===0){I(`
275
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}I(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=$P(a);Sa.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await go([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}I(`
276
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function D(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var LP=b("moduleProxy");function DP(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Zl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function fh(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await P(E.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{LP.warn(`Failed to emit proxy executed event: ${String(s)}`);}),D(o);}async function hh(e,t){let r=me.find(o=>o.alias===e);if(!r){v(`Unknown module alias: '${e}'`),D(1);return}if(!await Bt(r.binaryName)){v(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),D(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await jt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){v(`No supported installation method available for '${e}' on this platform.`),D(1);return}if(await DP("Would you like to install it now? [Y/n] ")){await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Mr(r,"inline",s);if(!a.success){v(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),D(1);return}await fh(r,t);}else I(`To install manually, run: flow modules install ${e}`),await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),D(1);return}await fh(r,t);}N();var BP=promisify(execFile);async function FP(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await BP(rr(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${ye}`,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 jP(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ge(t,r)?"outdated":"installed"}async function Hc(){let e=await Promise.all(me.map(async t=>{let[r,n]=await Promise.all([Bt(t.binaryName),FP(t)]),s=lt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=jP(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return xr(["Name","Alias","Version","Status","Platform"],e),0}async function Sh(e){let t=me.find(i=>i.alias===e);if(!t)return v(`Unknown module alias: '${e}'`),1;let[r]=await uo([t]);if(r.alreadyInstalled){let i=lt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return I(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?v(`Module ${t.name} is not supported on ${process.platform}.${a}`):v(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=ua({text:`Installing ${t.name}...`}).start(),s;try{s=await Mr(t,"on_demand",n);}finally{o.stop();}return s.success?(q(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(v(s.error?.message??"Installation failed"),1)}async function yh(e,t){let r=ua({text:`Updating ${e.name}...`}).start(),n;try{n=await ri(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 bh(e){if(e!==null){let n=me.find(i=>i.alias===e);if(!n)return v(`Unknown module alias: '${e}'`),1;let o=lt(n.alias);return o?.installMethod?await yh(n,o.installedVersion??"unknown")==="error"?1:0:(v(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=sn().filter(n=>n.installMethod!==null);if(t.length===0)return I("No installed modules to update."),0;let r=0;for(let n of t){let o=me.find(i=>i.alias===n.alias);if(!o)continue;await yh(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var hs=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
277
277
  title: "0-current-state \u2014 Index"
278
278
  type: index
279
279
  domain: platform
@@ -564,17 +564,17 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
564
564
  **6. Source code never in monitored folders.**
565
565
  If you create a folder with app or script source code, keep it out of the 5 numbered folders
566
566
  entirely (e.g. \`prototypes/\`).
567
- `},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];N();var Wc="CLAUDE.md";function VP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function GP(){return {new:0,unchanged:0,divergent:0,declined:0}}async function Ih(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??zP,i=e.confirmCreate??XP,a=[],l=GP(),u=hs.find(m=>m.path===Wc),c=u?existsSync(join(t,u.path)):true;if(u&&!c){let m=join(t,u.path);o?await i(u.path)?(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8"))):I(`declined: ${Wc} not created`):e.assistant==="claude-code"&&(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8")));}for(let m of hs){if(m.path===Wc&&!c)continue;let p=join(t,m.path),f=await JP({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:g=>s(g)});a.push({path:m.path,status:f.status}),l[f.status]++,f.write&&!r&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8"));}let d=l.divergent>0||l.declined>0;return {files:a,counts:l,hasUnresolved:d}}async function JP(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?VP(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(WP(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function WP(e){I(`${e} differs from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status" and "git diff ${e}", or open your IDE's diff/history view for this file. Once overwritten, uncommitted local changes are gone for good.`);}async function zP(e){return X(` Overwrite ${e} with the updated template? [y/N] `)}async function XP(e){return X(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}N();R();Ce();Yr();R();var zc=b("lib:otelMetrics"),YP="flow-plugins-cli",ZP="1.0.0",QP=5e3;function eT(){return Ot("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function tT(e,t){return typeof t=="number"?{key:e,value:{intValue:String(t)}}:typeof t=="boolean"?{key:e,value:{boolValue:t}}:{key:e,value:{stringValue:t}}}function rT(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:YP,version:ZP},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>tT(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Xc(e,t={}){try{let[r,n]=await Promise.all([kn(),re()]),o=r?.email,s=n?.tenant;if(!o||!s){zc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=rT(e,t);await fp.post(eT(),{json:i,timeout:QP,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),zc.debug(`OTel metric sent: ${e}`);}catch(r){zc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var qc=b("cli:init"),oT={new:{label:"new",color:C.green},unchanged:{label:"unchanged",color:C.dim},divergent:{label:"kept (differs from template)",color:C.yellow},declined:{label:"pending (declined)",color:C.yellow}};function sT(e){process.stdout.write(`
567
+ `},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];N();var zc="CLAUDE.md";function VP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function GP(){return {new:0,unchanged:0,divergent:0,declined:0}}async function Ih(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??zP,i=e.confirmCreate??XP,a=[],l=GP(),u=hs.find(m=>m.path===zc),c=u?existsSync(join(t,u.path)):true;if(u&&!c){let m=join(t,u.path);o?await i(u.path)?(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8"))):I(`declined: ${zc} not created`):e.assistant==="claude-code"&&(a.push({path:u.path,status:"new"}),l.new++,r||(mkdirSync(dirname(m),{recursive:true}),writeFileSync(m,u.content,"utf8")));}for(let m of hs){if(m.path===zc&&!c)continue;let p=join(t,m.path),f=await JP({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:g=>s(g)});a.push({path:m.path,status:f.status}),l[f.status]++,f.write&&!r&&(mkdirSync(dirname(p),{recursive:true}),writeFileSync(p,m.content,"utf8"));}let d=l.divergent>0||l.declined>0;return {files:a,counts:l,hasUnresolved:d}}async function JP(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?VP(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(WP(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function WP(e){I(`${e} differs from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status" and "git diff ${e}", or open your IDE's diff/history view for this file. Once overwritten, uncommitted local changes are gone for good.`);}async function zP(e){return X(` Overwrite ${e} with the updated template? [y/N] `)}async function XP(e){return X(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}N();R();Ce();Yr();R();var Xc=b("lib:otelMetrics"),YP="flow-plugins-cli",ZP="1.0.0",QP=5e3;function eT(){return Ot("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function tT(e,t){return typeof t=="number"?{key:e,value:{intValue:String(t)}}:typeof t=="boolean"?{key:e,value:{boolValue:t}}:{key:e,value:{stringValue:t}}}function rT(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:YP,version:ZP},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>tT(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function qc(e,t={}){try{let[r,n]=await Promise.all([kn(),re()]),o=r?.email,s=n?.tenant;if(!o||!s){Xc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=rT(e,t);await gp.post(eT(),{json:i,timeout:QP,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Xc.debug(`OTel metric sent: ${e}`);}catch(r){Xc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Yc=b("cli:init"),oT={new:{label:"new",color:C.green},unchanged:{label:"unchanged",color:C.dim},divergent:{label:"kept (differs from template)",color:C.yellow},declined:{label:"pending (declined)",color:C.yellow}};function sT(e){process.stdout.write(`
568
568
  `+C.bold(` flow setup strategy
569
569
  `)),process.stdout.write(C.dim(` Target: ${e}
570
570
 
571
571
  `)),process.stdout.write(C.dim(` Files evaluated:
572
572
  `));for(let t of hs)process.stdout.write(C.dim(` \xB7 ${t.path}
573
573
  `));process.stdout.write(`
574
- `);}function iT(e,t,r,n){P(E.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_divergent:e.divergent,files_declined:e.declined,dry_run:t,duration_ms:n,exit_code:r}).catch(o=>{qc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),Xc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function aT(e,t){P(E.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{qc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),Xc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function lT(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function cT(e){let t=simpleGit(e);await t.init(),await t.checkoutLocalBranch("main");}async function uT(){return X(" Initialize a git repository here (git init -b main)? [y/N] ")}async function Sa(e){if(qc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await Y())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmInitGit??uT;if(!await lT(t)){let m=`${t} is not a git repository. Strategy docs are meant to be version-controlled.`;if(!r)return e.json?_e({error:m,exitCode:1}):v(`${m} Re-run interactively to confirm, or run "git init" first.`),1;if(I(m),!await n())return 1;await cT(t),q(`Initialized a git repository in ${t} (branch: main).`);}e.json||sT(t);let o=Date.now(),s;try{s=await Ih({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(m){throw aT(m instanceof Error?m.message:String(m),Date.now()-o),m}let i=s.hasUnresolved?2:0;if(iT(s.counts,!!e.dryRun,i,Date.now()-o),e.json)return oe({dryRun:!!e.dryRun,counts:s.counts,files:s.files,exitCode:i}),i;let a=e.dryRun?C.dim("[dry-run] "):"";process.stdout.write(C.bold(` Result:
574
+ `);}function iT(e,t,r,n){P(E.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_divergent:e.divergent,files_declined:e.declined,dry_run:t,duration_ms:n,exit_code:r}).catch(o=>{Yc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),qc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function aT(e,t){P(E.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{Yc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),qc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function lT(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function cT(e){let t=simpleGit(e);await t.init(),await t.checkoutLocalBranch("main");}async function uT(){return X(" Initialize a git repository here (git init -b main)? [y/N] ")}async function ba(e){if(Yc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await Y())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmInitGit??uT;if(!await lT(t)){let m=`${t} is not a git repository. Strategy docs are meant to be version-controlled.`;if(!r)return e.json?_e({error:m,exitCode:1}):v(`${m} Re-run interactively to confirm, or run "git init" first.`),1;if(I(m),!await n())return 1;await cT(t),q(`Initialized a git repository in ${t} (branch: main).`);}e.json||sT(t);let o=Date.now(),s;try{s=await Ih({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(m){throw aT(m instanceof Error?m.message:String(m),Date.now()-o),m}let i=s.hasUnresolved?2:0;if(iT(s.counts,!!e.dryRun,i,Date.now()-o),e.json)return oe({dryRun:!!e.dryRun,counts:s.counts,files:s.files,exitCode:i}),i;let a=e.dryRun?C.dim("[dry-run] "):"";process.stdout.write(C.bold(` Result:
575
575
  `));for(let m of s.files){let{label:p,color:f}=oT[m.status];process.stdout.write(` ${a}${f(p.padEnd(18))} ${m.path}
576
576
  `);}process.stdout.write(`
577
- `);let{new:l,unchanged:u,divergent:c,declined:d}=s.counts;return q(`${l} new, ${u} unchanged, ${c} kept (differs from template)`+(d>0?`, ${d} pending confirmation`:"")),(c>0||d>0)&&I(`Some files differ from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status"/"git diff" or your IDE's diff view. Re-run with --force to overwrite them.`),i!==0&&v("flow setup strategy finished with unresolved files \u2014 see above."),i}N();F();var yo=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Qc="repos.yaml",mT="projects";function fT(e,t,r){if(e===void 0)return [];if(!Array.isArray(e))return r.push(`"${t}:" must be a list \u2014 ignoring the whole section.`),[];let n=[];return e.forEach((o,s)=>{if(typeof o!="object"||o===null){r.push(`${t}[${s}] is not a mapping \u2014 skipped.`);return}let i=o,a=i.name!==void 0?String(i.name):"",l=i.remote!==void 0?String(i.remote):"";if(!a||!l){let u=a||`${t}[${s}]`,c=[!a&&"name",!l&&"remote"].filter(Boolean).join(" and ");r.push(`${u}: missing required field "${c}" \u2014 skipped (did you mean "remote:" instead of "url:"?)`);return}n.push({name:a,remote:l,group:i.group!==void 0?String(i.group):void 0});}),n}function eu(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}function Ch(e){let t=[];return {repos:e.map(n=>{let o=eu(n.remote);if(o===n.remote)return n;let s={...n,remote:o};return t.push({before:n,after:s}),s}),converted:t}}var gT=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function xa(e){let t=[],r=[];for(let n of e){if(!n.name.trim()){r.push({entry:n,reason:"empty name"});continue}if(!n.remote.trim()){r.push({entry:n,reason:"empty remote"});continue}if(!gT.test(n.remote.trim())){r.push({entry:n,reason:`remote does not look like a valid git URL: ${n.remote}`});continue}t.push(n);}return {valid:t,invalid:r}}function kh(e){let t=join(e,Qc);if(!existsSync(t))return null;let r=parse(readFileSync(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return null;let n=[],o=r.workspace;o!==void 0&&(typeof o!="object"||o===null)&&n.push('"workspace:" must be a mapping \u2014 using the default (repos_dir).');let s=o&&typeof o=="object"?o:{};return r.repos_dir!==void 0&&n.push('"repos_dir" must be nested under "workspace:", not at the top level \u2014 using the default.'),(r.references!==void 0||s.refs_dir!==void 0)&&n.push('legacy "references:"/"refs_dir" key found \u2014 delete repos.yaml and re-run "flow setup workspace" to regenerate it clean.'),{workspace:{repos_dir:String(s.repos_dir??mT)},repos:fT(r.repos,"repos",n),warnings:n}}function Ia(e,t){let r=join(e,Qc),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function Ah(e){Ho(e,Qc);}function Rh(e,t){Ho(e,`${t}/`);}function $h(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
577
+ `);let{new:l,unchanged:u,divergent:c,declined:d}=s.counts;return q(`${l} new, ${u} unchanged, ${c} kept (differs from template)`+(d>0?`, ${d} pending confirmation`:"")),(c>0||d>0)&&I(`Some files differ from the Flow strategy template. Review your local changes before overwriting \u2014 run "git status"/"git diff" or your IDE's diff view. Re-run with --force to overwrite them.`),i!==0&&v("flow setup strategy finished with unresolved files \u2014 see above."),i}N();F();var yo=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var eu="repos.yaml",mT="projects";function fT(e,t,r){if(e===void 0)return [];if(!Array.isArray(e))return r.push(`"${t}:" must be a list \u2014 ignoring the whole section.`),[];let n=[];return e.forEach((o,s)=>{if(typeof o!="object"||o===null){r.push(`${t}[${s}] is not a mapping \u2014 skipped.`);return}let i=o,a=i.name!==void 0?String(i.name):"",l=i.remote!==void 0?String(i.remote):"";if(!a||!l){let u=a||`${t}[${s}]`,c=[!a&&"name",!l&&"remote"].filter(Boolean).join(" and ");r.push(`${u}: missing required field "${c}" \u2014 skipped (did you mean "remote:" instead of "url:"?)`);return}n.push({name:a,remote:l,group:i.group!==void 0?String(i.group):void 0});}),n}function tu(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}function Ch(e){let t=[];return {repos:e.map(n=>{let o=tu(n.remote);if(o===n.remote)return n;let s={...n,remote:o};return t.push({before:n,after:s}),s}),converted:t}}var gT=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function Ia(e){let t=[],r=[];for(let n of e){if(!n.name.trim()){r.push({entry:n,reason:"empty name"});continue}if(!n.remote.trim()){r.push({entry:n,reason:"empty remote"});continue}if(!gT.test(n.remote.trim())){r.push({entry:n,reason:`remote does not look like a valid git URL: ${n.remote}`});continue}t.push(n);}return {valid:t,invalid:r}}function kh(e){let t=join(e,eu);if(!existsSync(t))return null;let r=parse(readFileSync(t,"utf8"));if(!r||typeof r!="object"||Array.isArray(r))return null;let n=[],o=r.workspace;o!==void 0&&(typeof o!="object"||o===null)&&n.push('"workspace:" must be a mapping \u2014 using the default (repos_dir).');let s=o&&typeof o=="object"?o:{};return r.repos_dir!==void 0&&n.push('"repos_dir" must be nested under "workspace:", not at the top level \u2014 using the default.'),(r.references!==void 0||s.refs_dir!==void 0)&&n.push('legacy "references:"/"refs_dir" key found \u2014 delete repos.yaml and re-run "flow setup workspace" to regenerate it clean.'),{workspace:{repos_dir:String(s.repos_dir??mT)},repos:fT(r.repos,"repos",n),warnings:n}}function va(e,t){let r=join(e,eu),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function Ah(e){Ho(e,eu);}function Rh(e,t){Ho(e,`${t}/`);}function $h(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
578
578
  `).map(l=>l.trim())),s=[t.repos_dir].filter(l=>!o.has(`${l}/`));if(s.length===0)return;let i=n?"":`# Paths excluded from Claude Code context.
579
579
  `,a=s.map(l=>`# ${l}/ \u2014 repos cloned via flow setup workspace, not part of this repo's own docs.
580
580
  ${l}/`).join(`
@@ -592,12 +592,12 @@ ${Eh}
592
592
  `;return appendFileSync(n,`${o.endsWith(`
593
593
  `)?"":`
594
594
  `}${s}`,"utf8"),"appended"}var Mh="projects";function hT(e){let t=e.match(/^git@[^:]+:[^/]+\/([^/.]+)(\.git)?\/?$/);if(t)return t[1]??null;let r=e.match(/^https?:\/\/[^/]+\/[^/]+\/([^/.]+)(\.git)?\/?$/);return r?r[1]??null:null}async function Lh(){for(;;){let e=await qn(" Repo URL \u2014 SSH or HTTPS (leave empty and press ENTER to finish): ");if(!e)return null;let t=hT(e);if(!t){process.stdout.write(` Could not parse a repo name from that URL \u2014 expected an SSH (git@host:org/repo.git) or HTTPS (https://host/org/repo) GitHub URL. Try again.
595
- `);continue}let r=await qn(` Group/category for '${t}' (optional, default: general): `),n=eu(e);return {name:t,remote:n,group:r||"general"}}}async function Dh(){if(!await X("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await qn(` Folder for work repos (default: ${Mh}): `),r=[];for(process.stdout.write(C.bold(`
595
+ `);continue}let r=await qn(` Group/category for '${t}' (optional, default: general): `),n=tu(e);return {name:t,remote:n,group:r||"general"}}}async function Dh(){if(!await X("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await qn(` Folder for work repos (default: ${Mh}): `),r=[];for(process.stdout.write(C.bold(`
596
596
  Add repos (leave the URL empty to finish):
597
597
  `));;){let n=await Lh();if(!n)break;r.push(n),process.stdout.write(C.green(` \u2713 added ${n.name}
598
598
  `));}return r.length===0?null:(process.stdout.write(C.dim(`
599
599
  ${r.length} repo(s) added.
600
- `)),{workspace:{repos_dir:t||Mh},repos:r,warnings:[]})}async function Oh(e){let{valid:t,invalid:r}=xa(e);process.stdout.write(C.bold(`
600
+ `)),{workspace:{repos_dir:t||Mh},repos:r,warnings:[]})}async function Oh(e){let{valid:t,invalid:r}=Ia(e);process.stdout.write(C.bold(`
601
601
  Current repos in repos.yaml (${e.length}):
602
602
  `));for(let i of e){let a=r.find(u=>u.entry===i),l=a?` \u2717 (${a.reason})`:" \u2713";process.stdout.write(` - ${i.name} (${i.remote})${l}
603
603
  `);}let n=t,o=false;if(r.length>0&&(await X(` Remove the ${r.length} invalid entr${r.length===1?"y":"ies"} listed above? [y/N] `)?o=true:n=e),await X(" Add more repos to repos.yaml? [y/N] "))for(process.stdout.write(C.bold(`
@@ -605,7 +605,7 @@ ${Eh}
605
605
  `));;){let i=await Lh();if(!i)break;n=[...n,i],o=true,process.stdout.write(C.green(` \u2713 added ${i.name}
606
606
  `));}return {repos:n,changed:o}}R();var Nh=b("workspace:repos"),Uh=6e4;async function ST(e){try{return (await simpleGit(e).status()).current}catch{return null}}function Bh(){let{HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n}=process.env;return {HOME:e,PATH:t,USER:r,SSH_AUTH_SOCK:n,GIT_TERMINAL_PROMPT:"0"}}var Fh=["GIT_TERMINAL_PROMPT"];function jh(e){return e?{progress:({progress:t})=>e(t)}:{}}async function bT(e,t){await simpleGit(e,{timeout:{block:Uh},allowEnvironment:Fh,...jh(t)}).env(Bh()).pull(["--ff-only"]);}async function xT(e,t,r){await simpleGit({timeout:{block:Uh},allowEnvironment:Fh,...jh(r)}).env(Bh()).clone(e,t);}var IT=["Authentication failed","could not read Username","Permission denied","Repository not found","Could not read from remote repository"],vT='This usually means the wrong default SSH identity is being used for this host, not a real access problem. Add a dedicated Host alias to ~/.ssh/config (e.g. "Host github.com-<org>" with IdentityFile pointing at the key that has access to this org), then point this repo\'s `remote:` in repos.yaml at that alias and retry.';function ET(e){return IT.some(r=>e.includes(r))?`${e}
607
607
 
608
- ${vT}`:e}async function Kh(e,t,r){let n=join(t,e.name),o=join(n,".git");if(existsSync(o)){let s=await ST(n);if(s==="main"||s==="master")try{return await bT(n,r),{name:e.name,outcome:"updated",path:n}}catch(i){return Nh.warn(`[${e.name}] pull failed (branch diverged?): ${String(i)}`),{name:e.name,outcome:"skipped",path:n}}return {name:e.name,outcome:"skipped",path:n}}try{return mkdirSync(t,{recursive:!0}),await xT(e.remote,n,r),{name:e.name,outcome:"cloned",path:n}}catch(s){let i=s instanceof Error?s.message:String(s);return Nh.error(`[${e.name}] clone failed: ${i}`),{name:e.name,outcome:"failed",error:ET(i)}}}function va(e,t){return !existsSync(join(t,e.name,".git"))}var PT="general";function Hh(e){return e.group??PT}function Vh(e){return [...new Set(e.map(Hh))].sort()}function Gh(e,t,r){return r===null?e:e.filter(n=>!va(n,t)||r.has(Hh(n)))}function Jh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var kT=promisify(execFile),Wh=5e3;async function zh(){try{let{stdout:e,stderr:t}=await kT("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${Wh/1e3}`],{timeout:Wh+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Xh(e){let t=Math.max(1,cpus().length);return Math.max(1,Math.min(t,4,e))}async function qh(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;;){let a=o++;if(a>=e.length)return;n[a]=await r(e[a],a);}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}var ou="All";async function $T(e,t){let r=e.filter(s=>va(s,t)),n=Vh(r);if(n.length<=1)return null;let o=await Xl("Some repos are not cloned yet \u2014 which groups do you want to clone?",[{value:ou,label:ou},...n.map(s=>({value:s,label:s}))]);return o.length===0||o.includes(ou)?null:new Set(o)}function su(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Zh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=kh(t);if(n){if(r){let x=await Oh(n.repos);x.changed?(n={...n,repos:x.repos},Ia(t,n)):n={...n,repos:x.repos};}}else {if(!r)return su();let x=await Dh();if(!x)return su();Ia(t,x),Ah(t),n=x;}let{repos:o,converted:s}=Ch(n.repos);s.length>0&&(n={...n,repos:o},Ia(t,n)),$h(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=xa(n.repos),u=[...n.warnings,...l.map(x=>`${x.entry.name||"(unnamed)"}: ${x.reason} \u2014 skipped`),...s.map(x=>`${x.before.name}: remote is HTTPS \u2014 converted to SSH (${x.after.remote}) and saved to repos.yaml`)],c=r?await $T(a,i):null,d=Gh(a,i,c);if(d.some(x=>va(x,i))&&!await zh())return su({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let p=Xh(d.length),f=await qh(d,p,async(x,_)=>{e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:"start"});let L=await Kh(x,i,T=>{e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:"start",progress:T});});return e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:L.outcome,path:L.path}),L}),g=new Set(a.map(x=>x.name)),h=Jh(i,g),w=0;if(e.prune&&h.length>0)for(let x of h)rmSync(join(i,x),{recursive:true,force:true}),w++;return Rh(t,n.workspace.repos_dir),{repos:f,orphans:e.prune?[]:h,prunedCount:w,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}var OT=promisify(execFile),NT=`#!/usr/bin/env bash
608
+ ${vT}`:e}async function Kh(e,t,r){let n=join(t,e.name),o=join(n,".git");if(existsSync(o)){let s=await ST(n);if(s==="main"||s==="master")try{return await bT(n,r),{name:e.name,outcome:"updated",path:n}}catch(i){return Nh.warn(`[${e.name}] pull failed (branch diverged?): ${String(i)}`),{name:e.name,outcome:"skipped",path:n}}return {name:e.name,outcome:"skipped",path:n}}try{return mkdirSync(t,{recursive:!0}),await xT(e.remote,n,r),{name:e.name,outcome:"cloned",path:n}}catch(s){let i=s instanceof Error?s.message:String(s);return Nh.error(`[${e.name}] clone failed: ${i}`),{name:e.name,outcome:"failed",error:ET(i)}}}function Ea(e,t){return !existsSync(join(t,e.name,".git"))}var PT="general";function Hh(e){return e.group??PT}function Vh(e){return [...new Set(e.map(Hh))].sort()}function Gh(e,t,r){return r===null?e:e.filter(n=>!Ea(n,t)||r.has(Hh(n)))}function Jh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var kT=promisify(execFile),Wh=5e3;async function zh(){try{let{stdout:e,stderr:t}=await kT("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${Wh/1e3}`],{timeout:Wh+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Xh(e){let t=Math.max(1,cpus().length);return Math.max(1,Math.min(t,4,e))}async function qh(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;;){let a=o++;if(a>=e.length)return;n[a]=await r(e[a],a);}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}var su="All";async function $T(e,t){let r=e.filter(s=>Ea(s,t)),n=Vh(r);if(n.length<=1)return null;let o=await ql("Some repos are not cloned yet \u2014 which groups do you want to clone?",[{value:su,label:su},...n.map(s=>({value:s,label:s}))]);return o.length===0||o.includes(su)?null:new Set(o)}function iu(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Zh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=kh(t);if(n){if(r){let x=await Oh(n.repos);x.changed?(n={...n,repos:x.repos},va(t,n)):n={...n,repos:x.repos};}}else {if(!r)return iu();let x=await Dh();if(!x)return iu();va(t,x),Ah(t),n=x;}let{repos:o,converted:s}=Ch(n.repos);s.length>0&&(n={...n,repos:o},va(t,n)),$h(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=Ia(n.repos),u=[...n.warnings,...l.map(x=>`${x.entry.name||"(unnamed)"}: ${x.reason} \u2014 skipped`),...s.map(x=>`${x.before.name}: remote is HTTPS \u2014 converted to SSH (${x.after.remote}) and saved to repos.yaml`)],c=r?await $T(a,i):null,d=Gh(a,i,c);if(d.some(x=>Ea(x,i))&&!await zh())return iu({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let p=Xh(d.length),f=await qh(d,p,async(x,_)=>{e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:"start"});let L=await Kh(x,i,T=>{e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:"start",progress:T});});return e.onRepoProgress?.({name:x.name,index:_,total:d.length,status:L.outcome,path:L.path}),L}),g=new Set(a.map(x=>x.name)),h=Jh(i,g),w=0;if(e.prune&&h.length>0)for(let x of h)rmSync(join(i,x),{recursive:true,force:true}),w++;return Rh(t,n.workspace.repos_dir),{repos:f,orphans:e.prune?[]:h,prunedCount:w,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}var OT=promisify(execFile),NT=`#!/usr/bin/env bash
609
609
  # .githooks/pre-commit \u2014 blocks a commit if trufflehog finds a secret in the
610
610
  # staged diff, with extra attention to .claude/settings*.json.
611
611
  #
@@ -690,12 +690,12 @@ fi
690
690
 
691
691
  echo -e "\${GREEN}\u2713\${RESET} No secrets found in staged changes."
692
692
  exit 0
693
- `;async function ey(e){let t=join(e,".githooks");mkdirSync(t,{recursive:true}),writeFileSync(join(t,"pre-commit"),NT,{mode:493}),await OT("git",["config","core.hooksPath",".githooks"],{cwd:e});}R();function iu(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function ty(e,t,r){let n=`[${t+1}/${r}]`;if(!e||e.status==="start"){if(e?.progress===void 0)return C.dim(` ${n} ${e?.name??"waiting..."}`);let{bar:s}=Un(e.progress,100);return C.yellow(` ${n} ${e.name} ${s} ${e.progress}%`)}let o=iu(e.status);if(e.status==="cloned"||e.status==="updated"){let s=e.path?` \u2192 ${e.path}`:"";return C.green(` ${n} ${e.name}: ${o}${s}`)}return e.status==="failed"?C.red(` ${n} ${e.name}: ${o}`):C.dim(` ${n} ${e.name}: ${o}`)}function UT(e){return e.map((t,r)=>ty(t,r,e.length)).join(`
693
+ `;async function ey(e){let t=join(e,".githooks");mkdirSync(t,{recursive:true}),writeFileSync(join(t,"pre-commit"),NT,{mode:493}),await OT("git",["config","core.hooksPath",".githooks"],{cwd:e});}R();function au(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function ty(e,t,r){let n=`[${t+1}/${r}]`;if(!e||e.status==="start"){if(e?.progress===void 0)return C.dim(` ${n} ${e?.name??"waiting..."}`);let{bar:s}=Un(e.progress,100);return C.yellow(` ${n} ${e.name} ${s} ${e.progress}%`)}let o=au(e.status);if(e.status==="cloned"||e.status==="updated"){let s=e.path?` \u2192 ${e.path}`:"";return C.green(` ${n} ${e.name}: ${o}${s}`)}return e.status==="failed"?C.red(` ${n} ${e.name}: ${o}`):C.dim(` ${n} ${e.name}: ${o}`)}function UT(e){return e.map((t,r)=>ty(t,r,e.length)).join(`
694
694
  `)}function BT(e){return e!==void 0&&e.status!=="start"}function ry(){let e=[],t=false;return r=>{e.length===0&&(e=new Array(r.total).fill(void 0)),e[r.index]=r,t?(process.stdout.write(`\x1B[${e.length-1}A`),e.forEach((n,o)=>{process.stdout.write(`\r\x1B[2K${ty(n,o,e.length)}`),o<e.length-1&&process.stdout.write(`
695
695
  `);})):(process.stdout.write(UT(e)),t=true),e.every(BT)&&process.stdout.write(`
696
- `);}}var FT=["local","project","user"],oy=[{name:"cit-tools",description:"CI&T-branded content tools (deck-architect agent, ciandt-pptx, ciandt-clay-render, pptx-builder, refiner skills)"},{name:"commons-claude",description:"Claude Code machine-setup skills (setup-claude-defaults, setup-session-recap, setup-statusline) \u2014 not product tooling, personal environment config"}],au=oy.map(e=>e.name);function jT(e){return e.filter(t=>!au.includes(t))}function KT(){I(`The following ${yo.length} runbook bundles will be installed:`);for(let e of yo)process.stdout.write(` - ${e}
697
- `);}async function HT(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of oy)await X(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function VT(){return xi(" Install scope:",FT.map(e=>({value:e,label:Xe[e].actionLabel,description:Xe[e].description})))}var ws=Symbol("skip");async function ny(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=aa(e);if(a){if(a.scope===n)return o||I(`${t}${e} is already installed ${qt(a)}. Use --force to reinstall.`),ws;if(o||!s)return o||I(`${t}Skipping ${e} \u2014 already installed ${qt(a)}. Re-run with --force to install here too.`),ws;if(!await la(e,n,a))return I(`${t}Skipped ${e}.`),ws;let u=await ms(e,{force:true,scope:a.scope});if(u!==0)return I(`${t}Could not remove ${e} from ${qt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||I(`${t}Installing ${e}...`),go([e],{scope:n,silent:o,force:i})}async function lu(e={}){if(!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=jT(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${au.join(", ")}`;return e.silent?oe({error:a}):v(a),1}}e.silent||KT();let r=e.scope;if(!r&&!e.silent&&t)try{r=await VT();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
698
- `),130;throw i}let n=e.force??false,o={scope:r,silent:e.silent,isInteractive:t,force:n},s=[];try{for(let a=0;a<yo.length;a++){let l=yo[a],u=`[${a+1}/${yo.length}] `,c=await ny(l,u,o);c!==ws&&s.push(c);}let i=e.extraPlugins?au.filter(a=>e.extraPlugins.includes(a)):await HT(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await ny(l,u,o);c!==ws&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
696
+ `);}}var FT=["local","project","user"],oy=[{name:"cit-tools",description:"CI&T-branded content tools (deck-architect agent, ciandt-pptx, ciandt-clay-render, pptx-builder, refiner skills)"},{name:"commons-claude",description:"Claude Code machine-setup skills (setup-claude-defaults, setup-session-recap, setup-statusline) \u2014 not product tooling, personal environment config"}],lu=oy.map(e=>e.name);function jT(e){return e.filter(t=>!lu.includes(t))}function KT(){I(`The following ${yo.length} runbook bundles will be installed:`);for(let e of yo)process.stdout.write(` - ${e}
697
+ `);}async function HT(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of oy)await X(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function VT(){return Ii(" Install scope:",FT.map(e=>({value:e,label:Xe[e].actionLabel,description:Xe[e].description})))}var ws=Symbol("skip");async function ny(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=la(e);if(a){if(a.scope===n)return o||I(`${t}${e} is already installed ${Yt(a)}. Use --force to reinstall.`),ws;if(o||!s)return o||I(`${t}Skipping ${e} \u2014 already installed ${Yt(a)}. Re-run with --force to install here too.`),ws;if(!await ca(e,n,a))return I(`${t}Skipped ${e}.`),ws;let u=await ms(e,{force:true,scope:a.scope});if(u!==0)return I(`${t}Could not remove ${e} from ${Yt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||I(`${t}Installing ${e}...`),go([e],{scope:n,silent:o,force:i})}async function cu(e={}){if(!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=jT(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${lu.join(", ")}`;return e.silent?oe({error:a}):v(a),1}}e.silent||KT();let r=e.scope;if(!r&&!e.silent&&t)try{r=await VT();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
698
+ `),130;throw i}let n=e.force??false,o={scope:r,silent:e.silent,isInteractive:t,force:n},s=[];try{for(let a=0;a<yo.length;a++){let l=yo[a],u=`[${a+1}/${yo.length}] `,c=await ny(l,u,o);c!==ws&&s.push(c);}let i=e.extraPlugins?lu.filter(a=>e.extraPlugins.includes(a)):await HT(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await ny(l,u,o);c!==ws&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
699
699
  `),130;throw i}return s.some(i=>i!==0)?1:0}var GT=b("cli:setup-workspace");function JT(){I("SSH key not configured for GitHub (or not added to your account)."),process.stdout.write(` Stopping before cloning \u2014 configure SSH and run this command again:
700
700
  `),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
701
701
  `),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
@@ -704,18 +704,18 @@ exit 0
704
704
  `),process.stdout.write(` 5. Copy the public key: pbcopy < ~/.ssh/id_ed25519.pub (macOS)
705
705
  `),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
706
706
  `),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
707
- `);}function WT(e){if(e.length===0)return;let t=e.map(r=>[r.outcome==="cloned"||r.outcome==="updated"?"\u2713":r.outcome==="skipped"?"\u25CB":"\u2717",r.name,iu(r.outcome),r.error??""]);xr(["","Repo","Outcome","Detail"],t);}async function zT(e,t,r,n){if(r||!n||t.skippedNoManifest||!t.workspaceDirs)return;let{repos_dir:o}=t.workspaceDirs,s=await X(` Add an off-limits note to CLAUDE.md for '${o}/'? [y/N] `),i=_h(e,t.workspaceDirs,s);i==="appended"?I(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?I("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&I("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function XT(e,t,r){if(!(t||!r||e.length===0||!await X(" Install a pre-commit secret-scan hook (trufflehog-based) in the newly cloned repo(s)? Blocks a commit if trufflehog finds a secret in the staged diff (skips with a warning if trufflehog isn't on PATH). Bypass: git commit --no-verify. [y/N] ")))for(let o of e)o.path&&(await ey(o.path),I(`Pre-commit secret-scan hook installed in ${o.name}.`));}async function cu(e={}){if(GT.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Zh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:ry()});if(e.json)return oe({repos:r.repos,orphans:r.orphans,prunedCount:r.prunedCount,skippedNoManifest:r.skippedNoManifest,manifestWarnings:r.manifestWarnings,sshBlocked:r.sshBlocked}),r.sshBlocked||r.repos.some(l=>l.outcome==="failed")?1:0;for(let l of r.manifestWarnings)I(`repos.yaml: ${l}`);if(r.sshBlocked)return JT(),1;if(r.skippedNoManifest)return I("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;WT(r.repos);let n=r.repos.filter(l=>l.outcome==="cloned").length,o=r.repos.filter(l=>l.outcome==="updated").length,s=r.repos.filter(l=>l.outcome==="skipped").length,i=r.repos.filter(l=>l.outcome==="failed").length;q(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&I(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`);let a=r.repos.filter(l=>l.outcome==="cloned");return await XT(a,e.json,t),await zT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var qT=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>Sa({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>lu({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>cu({path:e})}];async function YT(e){return X(` Run ${e}? [y/N] `)}async function sy(e={}){if(!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??YT,n=!!e.yes||!t;!e.yes&&!t&&I("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of qT){if(!(n||await r(s.label))){I(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var ZT=">=2.9.0-beta.28 <2.10.2-beta.49";function QT(e){return cc.valid(e)?cc.satisfies(e,ZT,{includePrerelease:true}):false}function ay(e=ye){return QT(e)?{blocked:true,message:`@ciandt-flow/cli@${e} is a known-affected version (FLWP-72469): it embeds internal flow-harness documentation in the published package.
707
+ `);}function WT(e){if(e.length===0)return;let t=e.map(r=>[r.outcome==="cloned"||r.outcome==="updated"?"\u2713":r.outcome==="skipped"?"\u25CB":"\u2717",r.name,au(r.outcome),r.error??""]);xr(["","Repo","Outcome","Detail"],t);}async function zT(e,t,r,n){if(r||!n||t.skippedNoManifest||!t.workspaceDirs)return;let{repos_dir:o}=t.workspaceDirs,s=await X(` Add an off-limits note to CLAUDE.md for '${o}/'? [y/N] `),i=_h(e,t.workspaceDirs,s);i==="appended"?I(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?I("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&I("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function XT(e,t,r){if(!(t||!r||e.length===0||!await X(" Install a pre-commit secret-scan hook (trufflehog-based) in the newly cloned repo(s)? Blocks a commit if trufflehog finds a secret in the staged diff (skips with a warning if trufflehog isn't on PATH). Bypass: git commit --no-verify. [y/N] ")))for(let o of e)o.path&&(await ey(o.path),I(`Pre-commit secret-scan hook installed in ${o.name}.`));}async function uu(e={}){if(GT.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Zh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:ry()});if(e.json)return oe({repos:r.repos,orphans:r.orphans,prunedCount:r.prunedCount,skippedNoManifest:r.skippedNoManifest,manifestWarnings:r.manifestWarnings,sshBlocked:r.sshBlocked}),r.sshBlocked||r.repos.some(l=>l.outcome==="failed")?1:0;for(let l of r.manifestWarnings)I(`repos.yaml: ${l}`);if(r.sshBlocked)return JT(),1;if(r.skippedNoManifest)return I("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;WT(r.repos);let n=r.repos.filter(l=>l.outcome==="cloned").length,o=r.repos.filter(l=>l.outcome==="updated").length,s=r.repos.filter(l=>l.outcome==="skipped").length,i=r.repos.filter(l=>l.outcome==="failed").length;q(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&I(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`);let a=r.repos.filter(l=>l.outcome==="cloned");return await XT(a,e.json,t),await zT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var qT=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ba({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>cu({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>uu({path:e})}];async function YT(e){return X(` Run ${e}? [y/N] `)}async function sy(e={}){if(!await Y())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??YT,n=!!e.yes||!t;!e.yes&&!t&&I("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of qT){if(!(n||await r(s.label))){I(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var ZT=">=2.9.0-beta.28 <2.10.2-beta.49";function QT(e){return uc.valid(e)?uc.satisfies(e,ZT,{includePrerelease:true}):false}function ay(e=ye){return QT(e)?{blocked:true,message:`@ciandt-flow/cli@${e} is a known-affected version (FLWP-72469): it embeds internal flow-harness documentation in the published package.
708
708
  Run: npm install -g @ciandt-flow/cli@latest
709
709
  Then re-run this command.`}:{blocked:false}}function eC(e){let t=["",C.bold("All commands:"),""];function r(n,o,s){if(n.name()==="help")return;let i=`${o} ${n.name()}`,a=" ".repeat(s),l=n.description()?C.dim(` \u2014 ${n.description()}`):"";t.push(`${a}${C.cyan(`flow${i}`)}${l}`);for(let u of n.commands)r(u,i,s+1);}for(let n of e.commands)r(n,"",1);return t.push("",C.dim("Without arguments, opens the interactive interface (TUI)."),C.dim("Use 'flow <command> --help' for details and examples on each command.")),t.join(`
710
710
  `)}function ly(e){let t=new Command;t.enablePositionalOptions(),t.configureHelp({styleTitle:c=>C.bold(c),styleCommandText:c=>C.cyan.bold(c),styleSubcommandText:c=>C.cyan(c),styleOptionTerm:c=>C.yellow(c),styleArgumentTerm:c=>C.green(c),styleDescriptionText:c=>C.dim(c)}),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ye}`,"-V, --version","Display the CLI version").addHelpText("after",()=>eC(t)).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
711
711
  Examples:
712
- $ flow setup init`).action(async()=>{let c=await Oc();D(c);}),r.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addOption(new Option("--assistant <name>","Also scaffold a config file for this coding assistant (e.g. CLAUDE.md). Interactive: asks for confirmation before creating it. Non-interactive: never creates it, even with this flag set.").choices(["claude-code"])).addHelpText("after",`
712
+ $ flow setup init`).action(async()=>{let c=await Nc();D(c);}),r.command("strategy").description("Scaffold the numbered strategy documentation structure (0-current-state, 1-strategy, 2-plan, 3-delivery, 4-learn)").option("--dry-run","Preview changes without writing files or prompting",false).option("--json","Output machine-readable JSON",false).option("--force","Skip confirmation before overwriting an up-to-date file, and overwrite customized files too",false).option("--path <dir>","Target repository root (defaults to the current directory)").addOption(new Option("--assistant <name>","Also scaffold a config file for this coding assistant (e.g. CLAUDE.md). Interactive: asks for confirmation before creating it. Non-interactive: never creates it, even with this flag set.").choices(["claude-code"])).addHelpText("after",`
713
713
  Examples:
714
714
  $ flow setup strategy
715
715
  $ flow setup strategy --dry-run
716
716
  $ flow setup strategy --force
717
717
  $ flow setup strategy --assistant claude-code
718
- $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await Sa({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant});D(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
718
+ $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await ba({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant});D(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
719
719
  Examples:
720
720
  $ flow setup harness
721
721
  $ flow setup harness --scope project
@@ -731,11 +731,11 @@ here too without asking, leaving the bundle enabled in both places.
731
731
  After the 7 bundles, an interactive run also asks once per opt-in extra
732
732
  (cit-tools, commons-claude) unless --extra-plugins was passed, which installs
733
733
  exactly the named bundles with no prompt \u2014 required in --silent or
734
- non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await lu({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});D(d);}),r.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
734
+ non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await cu({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});D(d);}),r.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
735
735
  Examples:
736
736
  $ flow setup workspace
737
737
  $ flow setup workspace --prune
738
- $ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await cu({path:c.path,prune:c.prune,json:c.json});D(d);}),r.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
738
+ $ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await uu({path:c.path,prune:c.prune,json:c.json});D(d);}),r.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
739
739
  Examples:
740
740
  $ flow setup framework-strategy
741
741
  $ flow setup framework-strategy --yes
@@ -831,7 +831,7 @@ Examples:
831
831
  $ flow auth login --jwt <token>
832
832
  $ flow auth login --jwt <token> --starter-kit dev
833
833
  $ flow auth login --jwt <token> --custom-email name@example.com
834
- $ flow auth login --verbose`).action(async c=>{Be("cli",{verbose:c.verbose});let d=await Oc(c);D(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
834
+ $ flow auth login --verbose`).action(async c=>{Be("cli",{verbose:c.verbose});let d=await Nc(c);D(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
835
835
  Examples:
836
836
  $ flow auth logout
837
837
  $ flow auth logout --force`).action(async c=>{let d=await bg(c.force);D(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
@@ -859,16 +859,16 @@ Examples:
859
859
  $ flow health --fix`).action(async c=>{let d=await Og(c);D(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
860
860
  Examples:
861
861
  $ flow usage
862
- $ flow usage --json`).action(async c=>{let d=await Kg(c);D(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Kc();D(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
862
+ $ flow usage --json`).action(async c=>{let d=await Kg(c);D(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Hc();D(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
863
863
  Examples:
864
- $ flow modules list`).action(async()=>{let c=await Kc();D(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
864
+ $ flow modules list`).action(async()=>{let c=await Hc();D(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
865
865
  Examples:
866
866
  $ flow modules install metrics
867
867
  $ flow modules install dashboard`).action(async c=>{let d=await Sh(c);D(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",`
868
868
  Examples:
869
869
  $ flow modules update
870
- $ flow modules update metrics`).action(async c=>{let d=await bh(c??null);D(d);}),t.addCommand(u);for(let c of me)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await hh(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=ay();if(m)throw new Error(p)}),t.hook("preAction",()=>{Zi();}),t}R();function nC(){return W__default.join(Se__default.homedir(),".claude","settings.json")}function uy(){let e=nC();try{if(!ue__default.existsSync(e))return !0;let r=JSON.parse(ue__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var cC=b("updateChecker"),uC=promisify(execFile),dC=1440*60*1e3,dy=3e4;function pC(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"update.lock")}async function py(e){try{let{stdout:t}=await uC(tr(),["view",e,"version"],{timeout:dy,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function mC(e){let t=new AbortController,r=setTimeout(()=>t.abort(),dy);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 fC(e){return e.versionCheck.type==="npm-registry"?py(e.versionCheck.package):mC(e.versionCheck.repo)}async function gC(){let e=await py("@ciandt-flow/cli");return e&&Ge(ye,e)?(oa({currentVersion:ye,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function hC(){let e=sn().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=me.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<dC)return;let s=await fC(r);try{await xt({...t,lastChecked:new Date().toISOString()});}catch(i){cC.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ge(t.installedVersion,s)&&ri(r,"background").catch(()=>{});}));}async function du(){let e=uy();if(e===false)return;let t=pC();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r;try{r=await Bw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await gC().catch(()=>null);n&&process.stdout.write(`
870
+ $ flow modules update metrics`).action(async c=>{let d=await bh(c??null);D(d);}),t.addCommand(u);for(let c of me)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await hh(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=ay();if(m)throw new Error(p)}),t.hook("preAction",()=>{Qi();}),t}R();function nC(){return W__default.join(Se__default.homedir(),".claude","settings.json")}function uy(){let e=nC();try{if(!ue__default.existsSync(e))return !0;let r=JSON.parse(ue__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var cC=b("updateChecker"),uC=promisify(execFile),dC=1440*60*1e3,dy=3e4;function pC(){let e=process.env.FLOW_HOME??W__default.join(Se__default.homedir(),".flow");return W__default.join(e,"update.lock")}async function py(e){try{let{stdout:t}=await uC(rr(),["view",e,"version"],{timeout:dy,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function mC(e){let t=new AbortController,r=setTimeout(()=>t.abort(),dy);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 fC(e){return e.versionCheck.type==="npm-registry"?py(e.versionCheck.package):mC(e.versionCheck.repo)}async function gC(){let e=await py("@ciandt-flow/cli");return e&&Ge(ye,e)?(sa({currentVersion:ye,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function hC(){let e=sn().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=me.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<dC)return;let s=await fC(r);try{await xt({...t,lastChecked:new Date().toISOString()});}catch(i){cC.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ge(t.installedVersion,s)&&ri(r,"background").catch(()=>{});}));}async function pu(){let e=uy();if(e===false)return;let t=pC();ue__default.mkdirSync(W__default.dirname(t),{recursive:true});let r;try{r=await Bw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await gC().catch(()=>null);n&&process.stdout.write(`
871
871
  \u26A0 @ciandt-flow/cli v${n} installing in background.
872
872
  Restart flow to apply the update.
873
873
 
874
- `);}await hC().catch(()=>{});}finally{await r().catch(()=>{});}}N();var wC=b("cli"),pu=ly(async()=>{Be("tui"),Xu("tui"),qu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Co("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Co("sigterm",t,r).finally(()=>process.exit(143));}),await du().catch(()=>{}),await wp().catch(t=>{wC.error(`Failed to init catalog registry: ${String(t)}`);}),await cg();let{waitUntilExit:e}=render(jsx(ug,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});pu.hook("preAction",async(e,t)=>{t!==pu&&await du().catch(()=>{});});try{await pu.parseAsync();}catch(e){v(e instanceof Error?e.message:String(e)),D(1);}
874
+ `);}await hC().catch(()=>{});}finally{await r().catch(()=>{});}}N();var wC=b("cli"),mu=ly(async()=>{Be("tui"),qu("tui"),Yu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Co("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Co("sigterm",t,r).finally(()=>process.exit(143));}),await pu().catch(()=>{}),await Sp().catch(t=>{wC.error(`Failed to init catalog registry: ${String(t)}`);}),await cg();let{waitUntilExit:e}=render(jsx(ug,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});mu.hook("preAction",async(e,t)=>{t!==mu&&await pu().catch(()=>{});});try{await mu.parseAsync();}catch(e){v(e instanceof Error?e.message:String(e)),D(1);}