@ciandt-flow/cli 2.12.0-beta.61 → 2.12.1-beta.62

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 +93 -93
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import*as Pn from'crypto';import {randomUUID,createHash}from'crypto';import*as Te from'os';import Te__default,{tmpdir,homedir,cpus}from'os';import*as oe from'path';import oe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as le from'fs';import le__default,{readFileSync,mkdirSync,existsSync,writeFileSync,readdirSync,statSync,rmSync,appendFileSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as Xl from'readline';import {createInterface}from'readline';import Qa from'conf';import cp,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Xw,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import aw from'jsonwebtoken';import Sw from'proper-lockfile';import Kw from'ink-big-text';import am from'ink-spinner';import*as Vt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import YS from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import ac from'semver';import aa from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var Qh=Object.defineProperty;var W=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var pu=(e,t)=>{for(var r in t)Qh(e,r,{get:t[r],enumerable:true});};var yr,Ue,Ta,wr,ho,bn,Sr,Ca,mu,ka,Lt,ge,tt,Qt,Ss,xn,vn,In,En,F=W(()=>{"use strict";yr="FLOW",Ue="flow-skills",Ta="flow-cli",wr=[Ue,"flow-harness"],ho="internal",bn="external",Sr={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"}},Ca=new Set(Object.keys(Sr)),mu={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},ka=new Set(["internal","external"]),Lt={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"}},ge="flow-claude-md-setup",tt=5,Qt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Ss="https://flow.ciandt.com",xn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,vn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",In=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,En="Must be a valid email address (e.g. name@example.com)";});var bs,ty,fu,yo,Aa=W(()=>{"use strict";bs="aes-256-gcm",ty=16,fu=16,yo=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=Pn.randomBytes(ty),n=Pn.createCipheriv(bs,this.key,r,{authTagLength:fu}),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:bs}}decrypt(t){if(t.algorithm!==bs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=Pn.createDecipheriv(bs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:fu});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Ra(e){return e.replace(sy,"").replace(iy,"").replace(ay,"").replace(ry,"Bearer ***").replace(ny,"***").replace(oy,"***").replace(/\r\n|\r|\n/g,"\\n")}var ry,ny,oy,sy,iy,ay,$a=W(()=>{"use strict";ry=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,ny=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,oy=/[A-Za-z0-9+/]{40,}={0,2}/g,sy=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,iy=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,ay=/\x1b/g;});function vs(e){return e||Ue}function gu(e,t,r){return La(vs(r),e,t)}function _a(e,t){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(t),"plugins","native",e)}function wo(e){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(e),".claude-plugin","marketplace.json")}function zr(){return oe.join(Te.homedir(),ht,"plugins","known_marketplaces.json")}function Ma(e){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(e))}function hu(){return oe.join(Te.homedir(),xs,"cache","install.lock")}function yu(){return oe.join(Te.homedir(),xs,"logs","flowsetup.log")}function La(e,t,r){return oe.join(Te.homedir(),ht,"plugins","cache",e,t,r)}function Xr(e){let t=e==="global"?Te.homedir():process.cwd();return oe.join(t,".claude","skills")}function So(e){let t=e==="global"?Te.homedir():process.cwd();return oe.join(t,".claude","skills-lock.json")}function Is(e="user"){return e==="project"?oe.join(process.cwd(),".opencode","plugins"):oe.join(Te.homedir(),".config","opencode","plugins")}function wu(){return oe.join(Te.homedir(),xs,"flow-catalogs.json")}function Su(){let e=process.env.FLOW_HOME??oe.join(Te.homedir(),xs);return oe.join(e,"config.json")}function Es(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"agents"):oe.join(Te.homedir(),ht,"agents")}function Tn(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"rules"):oe.join(Te.homedir(),ht,"rules")}function Da(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"hooks"):oe.join(Te.homedir(),ht,"hooks")}var ht,xs,Ne=W(()=>{"use strict";F();ht=".claude",xs=".flow";});var ly,cy,Ps,bu=W(()=>{"use strict";Ne();ly=5*1024*1024,cy=3,Ps=class{filePath;constructor(){this.filePath=yu(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{le.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=oe.dirname(this.filePath);le.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(le.statSync(this.filePath).size>ly){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);le.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=oe.dirname(this.filePath),r=oe.basename(this.filePath,".log"),n=le.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(cy))le.unlinkSync(oe.join(t,o));}catch{}}};});var Ts,xu=W(()=>{"use strict";Ts=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
2
+ import*as Pn from'crypto';import {randomUUID,createHash}from'crypto';import*as Te from'os';import Te__default,{tmpdir,homedir,cpus}from'os';import*as oe from'path';import oe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as le from'fs';import le__default,{readFileSync,mkdirSync,existsSync,writeFileSync,readdirSync,statSync,rmSync,appendFileSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as Xl from'readline';import {createInterface}from'readline';import Qa from'conf';import cp,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import qw,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import lw from'jsonwebtoken';import bw from'proper-lockfile';import Hw from'ink-big-text';import lm from'ink-spinner';import*as Vt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp as cp$1}from'fs/promises';import ZS from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import ac from'semver';import aa from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var ey=Object.defineProperty;var W=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var pu=(e,t)=>{for(var r in t)ey(e,r,{get:t[r],enumerable:true});};var yr,Ue,Ta,wr,ho,bn,Sr,Ca,mu,ka,Lt,ge,tt,Qt,Ss,xn,vn,In,En,F=W(()=>{"use strict";yr="FLOW",Ue="flow-skills",Ta="flow-cli",wr=[Ue,"flow-harness"],ho="internal",bn="external",Sr={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"}},Ca=new Set(Object.keys(Sr)),mu={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},ka=new Set(["internal","external"]),Lt={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"}},ge="flow-claude-md-setup",tt=5,Qt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Ss="https://flow.ciandt.com",xn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,vn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",In=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,En="Must be a valid email address (e.g. name@example.com)";});var bs,ry,fu,yo,Aa=W(()=>{"use strict";bs="aes-256-gcm",ry=16,fu=16,yo=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=Pn.randomBytes(ry),n=Pn.createCipheriv(bs,this.key,r,{authTagLength:fu}),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:bs}}decrypt(t){if(t.algorithm!==bs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=Pn.createDecipheriv(bs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:fu});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Ra(e){return e.replace(iy,"").replace(ay,"").replace(ly,"").replace(ny,"Bearer ***").replace(oy,"***").replace(sy,"***").replace(/\r\n|\r|\n/g,"\\n")}var ny,oy,sy,iy,ay,ly,$a=W(()=>{"use strict";ny=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,oy=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,sy=/[A-Za-z0-9+/]{40,}={0,2}/g,iy=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,ay=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,ly=/\x1b/g;});function vs(e){return e||Ue}function gu(e,t,r){return La(vs(r),e,t)}function _a(e,t){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(t),"plugins","native",e)}function wo(e){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(e),".claude-plugin","marketplace.json")}function zr(){return oe.join(Te.homedir(),ht,"plugins","known_marketplaces.json")}function Ma(e){return oe.join(Te.homedir(),ht,"plugins","marketplaces",vs(e))}function hu(){return oe.join(Te.homedir(),xs,"cache","install.lock")}function yu(){return oe.join(Te.homedir(),xs,"logs","flowsetup.log")}function La(e,t,r){return oe.join(Te.homedir(),ht,"plugins","cache",e,t,r)}function Xr(e){let t=e==="global"?Te.homedir():process.cwd();return oe.join(t,".claude","skills")}function So(e){let t=e==="global"?Te.homedir():process.cwd();return oe.join(t,".claude","skills-lock.json")}function Is(e="user"){return e==="project"?oe.join(process.cwd(),".opencode","plugins"):oe.join(Te.homedir(),".config","opencode","plugins")}function wu(){return oe.join(Te.homedir(),xs,"flow-catalogs.json")}function Su(){let e=process.env.FLOW_HOME??oe.join(Te.homedir(),xs);return oe.join(e,"config.json")}function Es(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"agents"):oe.join(Te.homedir(),ht,"agents")}function Tn(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"rules"):oe.join(Te.homedir(),ht,"rules")}function Da(e="user"){return e==="project"||e==="local"?oe.join(process.cwd(),ht,"hooks"):oe.join(Te.homedir(),ht,"hooks")}var ht,xs,Ne=W(()=>{"use strict";F();ht=".claude",xs=".flow";});var cy,uy,Ps,bu=W(()=>{"use strict";Ne();cy=5*1024*1024,uy=3,Ps=class{filePath;constructor(){this.filePath=yu(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{le.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=oe.dirname(this.filePath);le.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(le.statSync(this.filePath).size>cy){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);le.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=oe.dirname(this.filePath),r=oe.basename(this.filePath,".log"),n=le.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(uy))le.unlinkSync(oe.join(t,o));}catch{}}};});var Ts,xu=W(()=>{"use strict";Ts=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
4
  `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var Cs,vu=W(()=>{"use strict";Cs=class{write(t){process.stdout.write(t.message+`
5
- `);}};});function Ua(){return ks}function Iu(e){return Oa.add(e),()=>{Oa.delete(e);}}var ks,Oa,As,Na=W(()=>{"use strict";ks=[],Oa=new Set;As=class{write(t){ks.push(t),ks.length>100&&ks.shift();for(let r of Oa)r();}};});function uy(){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=uy();Yr={context:e,transports:[new As,new Ps],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Yr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Yr={context:e,transports:[new Ts("cli")],minLevel:"debug",debugModules:null}:Yr={context:e,transports:[new Cs],minLevel:"info",debugModules:null};}function Eu(){return Yr.transports}function Pu(e,t){let{debugModules:r,minLevel:n}=Yr;return Yr.context==="tui"&&r&&r!=="all"?r.has(t)?Cn[e]>=Cn.debug:Cn[e]>=Cn.warn:Cn[e]>=Cn[n]}var Cn,Yr,Ba=W(()=>{"use strict";bu();xu();vu();Na();Cn={debug:0,info:1,warn:2,error:3},Yr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Rs(e,t,r){if(!Pu(e,t))return;let n={level:e,module:t,message:Ra(r),timestamp:new Date};for(let o of Eu())o.write(n);}function b(e){let t=Tu.get(e);if(t)return t;let r={debug:n=>Rs("debug",e,n),info:n=>Rs("info",e,n),warn:n=>Rs("warn",e,n),error:n=>Rs("error",e,n)};return Tu.set(e,r),r}var Tu,Cu=W(()=>{"use strict";$a();Ba();Tu=new Map;});var R=W(()=>{"use strict";Cu();Ba();$a();});function dy(e){return typeof e=="object"&&e!==null&&ja in e&&e[ja]===true}function Ka(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ja]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Fa.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(dy(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Fa.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Fa.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Fa,ja,Ha=W(()=>{"use strict";R();Fa=b("encryption"),ja="__encrypted__";});var Va,fy,yt,kn,Wa=W(()=>{"use strict";R();Va=promisify(execFile),fy=promisify(exec),yt=b("encryption:macos-keyvault"),kn=class{static async isAvailable(){try{let{stdout:t}=await fy("command -v security");return yt.debug(`security binary found at: ${t.trim()}`),!0}catch{return yt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{yt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Va("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return yt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return yt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{yt.debug(`Storing secret: service=${t}, account=${r}`),await Va("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),yt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw yt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return yt.debug(`Deleting secret: service=${t}, account=${r}`),await Va("security",["delete-generic-password","-a",r,"-s",t]),yt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return yt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function w(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 X(e){process.stdout.write(T.green(` \u2713 ${w(e)}
5
+ `);}};});function Ua(){return ks}function Iu(e){return Oa.add(e),()=>{Oa.delete(e);}}var ks,Oa,As,Na=W(()=>{"use strict";ks=[],Oa=new Set;As=class{write(t){ks.push(t),ks.length>100&&ks.shift();for(let r of Oa)r();}};});function dy(){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=dy();Yr={context:e,transports:[new As,new Ps],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Yr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Yr={context:e,transports:[new Ts("cli")],minLevel:"debug",debugModules:null}:Yr={context:e,transports:[new Cs],minLevel:"info",debugModules:null};}function Eu(){return Yr.transports}function Pu(e,t){let{debugModules:r,minLevel:n}=Yr;return Yr.context==="tui"&&r&&r!=="all"?r.has(t)?Cn[e]>=Cn.debug:Cn[e]>=Cn.warn:Cn[e]>=Cn[n]}var Cn,Yr,Ba=W(()=>{"use strict";bu();xu();vu();Na();Cn={debug:0,info:1,warn:2,error:3},Yr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Rs(e,t,r){if(!Pu(e,t))return;let n={level:e,module:t,message:Ra(r),timestamp:new Date};for(let o of Eu())o.write(n);}function b(e){let t=Tu.get(e);if(t)return t;let r={debug:n=>Rs("debug",e,n),info:n=>Rs("info",e,n),warn:n=>Rs("warn",e,n),error:n=>Rs("error",e,n)};return Tu.set(e,r),r}var Tu,Cu=W(()=>{"use strict";$a();Ba();Tu=new Map;});var R=W(()=>{"use strict";Cu();Ba();$a();});function py(e){return typeof e=="object"&&e!==null&&ja in e&&e[ja]===true}function Ka(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ja]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Fa.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(py(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Fa.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Fa.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Fa,ja,Ha=W(()=>{"use strict";R();Fa=b("encryption"),ja="__encrypted__";});var Va,gy,yt,kn,Wa=W(()=>{"use strict";R();Va=promisify(execFile),gy=promisify(exec),yt=b("encryption:macos-keyvault"),kn=class{static async isAvailable(){try{let{stdout:t}=await gy("command -v security");return yt.debug(`security binary found at: ${t.trim()}`),!0}catch{return yt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{yt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Va("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return yt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return yt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{yt.debug(`Storing secret: service=${t}, account=${r}`),await Va("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),yt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw yt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return yt.debug(`Deleting secret: service=${t}, account=${r}`),await Va("security",["delete-generic-password","-a",r,"-s",t]),yt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return yt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function w(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 X(e){process.stdout.write(T.green(` \u2713 ${w(e)}
6
6
  `));}function I(e){process.stderr.write(T.red(` \u2717 ${w(e)}
7
7
  `));}function x(e){process.stdout.write(T.cyan(` \u2139 ${w(e)}
8
8
  `));}function br(e,t){let r=t.map(a=>a.map(w)),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 Pn from'crypto';import {randomUUID,createHash}from'crypto';import*as T
13
13
  `);}function xr(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
14
  `);}function ne(e){process.stdout.write(JSON.stringify(e)+`
15
15
  `);}function _e(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function ee(e){return e instanceof Error?e.message:String(e)}function Dt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=W(()=>{"use strict";});async function Sy(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 by(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Ja,Ga,wy,ie,vr,za=W(()=>{"use strict";R();N();Ja=promisify(execFile),Ga=promisify(exec),wy=[{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 Ja("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 wy)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 by(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return ie.info(`Running: ${t.command}`),await Sy("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 Ja("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 Ja("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 qa(e,t){return `${e}:${t}`}function xo(e){return e.replace(/'/g,"''")}function $s(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Cy(e){return `Add-Type -TypeDefinition @'
16
+ `);}function ee(e){return e instanceof Error?e.message:String(e)}function Dt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=W(()=>{"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 xy(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Ja,Ga,Sy,ie,vr,za=W(()=>{"use strict";R();N();Ja=promisify(execFile),Ga=promisify(exec),Sy=[{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 Ja("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 Sy)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 xy(" ? 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 Ja("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 Ja("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 qa(e,t){return `${e}:${t}`}function xo(e){return e.replace(/'/g,"''")}function $s(e){return ["-NoProfile","-NonInteractive","-Command",e]}function ky(e){return `Add-Type -TypeDefinition @'
17
17
  ${Ya}
18
18
  '@
19
- [FlowCredManager]::Read('${xo(e)}')`}function ky(e,t,r){return `Add-Type -TypeDefinition @'
19
+ [FlowCredManager]::Read('${xo(e)}')`}function Ay(e,t,r){return `Add-Type -TypeDefinition @'
20
20
  ${Ya}
21
21
  '@
22
- [FlowCredManager]::Write('${xo(e)}', '${xo(t)}', '${xo(r)}')`}function Ay(e){return `Add-Type -TypeDefinition @'
22
+ [FlowCredManager]::Write('${xo(e)}', '${xo(t)}', '${xo(r)}')`}function Ry(e){return `Add-Type -TypeDefinition @'
23
23
  ${Ya}
24
24
  '@
25
- [FlowCredManager]::Delete('${xo(e)}')`}async function _s(e){return Iy("powershell.exe",e)}var Iy,wt,Xa,Ey,Py,Ty,Ya,An,Za=W(()=>{"use strict";R();Iy=promisify(execFile),wt=b("encryption:windows-keyvault"),Xa=1,Ey=1,Py=2,Ty=3;Ya=`
25
+ [FlowCredManager]::Delete('${xo(e)}')`}async function _s(e){return Ey("powershell.exe",e)}var Ey,wt,Xa,Py,Ty,Cy,Ya,An,Za=W(()=>{"use strict";R();Ey=promisify(execFile),wt=b("encryption:windows-keyvault"),Xa=1,Py=1,Ty=2,Cy=3;Ya=`
26
26
  using System;
27
27
  using System.Runtime.InteropServices;
28
28
  using System.Text;
@@ -72,7 +72,7 @@ public class FlowCredManager {
72
72
  byte[] bytes = Encoding.UTF8.GetBytes(secret);
73
73
  IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
74
74
  IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
75
- int[] persistLevels = new int[] { ${Py}, ${Ty}, ${Ey} };
75
+ int[] persistLevels = new int[] { ${Ty}, ${Cy}, ${Py} };
76
76
  int lastErr = 0;
77
77
  try {
78
78
  foreach (int persist in persistLevels) {
@@ -102,41 +102,41 @@ public class FlowCredManager {
102
102
  }
103
103
  }
104
104
  `;An=class{static async isAvailable(){try{let{stdout:t}=await _s($s('Write-Output "ok"')),r=t.trim()==="ok";return wt.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
- `)[0]:"unknown error";return wt.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=qa(t,r);wt.debug(`Looking up secret: target=${n}`);let o=Cy(n),{stdout:s}=await _s($s(o)),i=s.trim();return wt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
- `)[0]:"unknown error";return wt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=qa(t,r);wt.debug(`Storing secret: target=${o}`);let s=ky(o,n,r),{stdout:i}=await _s($s(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];wt.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 wt.error(i),new Error(i,{cause:o})}}async deleteSecret(t,r){try{let n=qa(t,r);wt.debug(`Deleting secret: target=${n}`);let o=Ay(n),{stdout:s}=await _s($s(o)),i=s.trim()==="True";return wt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
- `)[0]:"unknown error";return wt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function My(){let e=`${Te.hostname()}${Te.userInfo().username}`;return Pn.scryptSync(e,$y,Ry)}function Ly(){let e=My(),t=new yo(e),r=Ka(t);return new Qa({projectName:el,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function Ms(){return Ls||(Ls=Ly()),Ls}var Ry,$y,el,_y,Ls,ze,vo=W(()=>{"use strict";Aa();Ha();Ry=32,$y="flow-plugins-cli-fallback",el="flow-plugins-cli-fallback",_y={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)"};Ls=null;ze=class{warned=!1;async getSecret(t,r){return Ms().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=_y[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 wt.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=qa(t,r);wt.debug(`Looking up secret: target=${n}`);let o=ky(n),{stdout:s}=await _s($s(o)),i=s.trim();return wt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
+ `)[0]:"unknown error";return wt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=qa(t,r);wt.debug(`Storing secret: target=${o}`);let s=Ay(o,n,r),{stdout:i}=await _s($s(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];wt.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 wt.error(i),new Error(i,{cause:o})}}async deleteSecret(t,r){try{let n=qa(t,r);wt.debug(`Deleting secret: target=${n}`);let o=Ry(n),{stdout:s}=await _s($s(o)),i=s.trim()==="True";return wt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
+ `)[0]:"unknown error";return wt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Ly(){let e=`${Te.hostname()}${Te.userInfo().username}`;return Pn.scryptSync(e,_y,$y)}function Dy(){let e=Ly(),t=new yo(e),r=Ka(t);return new Qa({projectName:el,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function Ms(){return Ls||(Ls=Dy()),Ls}var $y,_y,el,My,Ls,ze,vo=W(()=>{"use strict";Aa();Ha();$y=32,_y="flow-plugins-cli-fallback",el="flow-plugins-cli-fallback",My={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)"};Ls=null;ze=class{warned=!1;async getSecret(t,r){return Ms().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=My[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;}Ms().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ms(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return Ms().path}static hasExistingData(){try{let t=new Qa({projectName:el});return le.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Qa({projectName:el});le.rmSync(t.path,{force:!0});}catch{}Ls=null;}};});async function tl(){if(ze.hasExistingData())return new ze;switch(process.platform){case "darwin":return await kn.isAvailable()?new kn:new ze;case "linux":return await vr.isAvailable()?new vr:await vr.ensureInstalled()?new vr:new ze;case "win32":return await An.isAvailable()?new An:new ze;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var _u=W(()=>{"use strict";Wa();za();Za();vo();});var Mu=W(()=>{"use strict";Aa();Ha();_u();Wa();za();Za();vo();});async function Ir(){return Us||(Us=tl()),Us}function Ns(){Us=null;}async function te(){let t=await(await Ir()).getSecret(er,rl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Er(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 Lu.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ir()).setSecret(er,rl,JSON.stringify(e));}async function Du(){let e=await Ir();await e.deleteSecret(er,rl),await e.deleteSecret(er,nl),await e.deleteSecret(er,ol);}async function Ou(){return (await Ir()).getStoragePath()}async function Uu(e){await(await Ir()).setSecret(er,nl,JSON.stringify(e));}async function Bs(){let t=await(await Ir()).getSecret(er,nl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Fs(e){await(await Ir()).setSecret(er,ol,JSON.stringify(e));}async function Rn(){let t=await(await Ir()).getSecret(er,ol);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pr(){let e=await Bs();return e?new Date(e.expiresAt)>new Date:false}function Ot(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/`,Lu.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Lu,er,rl,nl,ol,Us,Ce=W(()=>{"use strict";Mu();R();Lu=b("config:credentials"),er="flow-plugins-cli",rl="credentials",nl="token-cache",ol="user-info",Us=null;});function $n(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 js=W(()=>{"use strict";});function Dy(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 sl(e){if(Nu.some(r=>r.test(e)))return true;let t=Dy(e);return !!(t&&Nu.some(r=>r.test(t)))}function Oy(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ut(e,t){let r=Oy(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&&sl(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Nu,Zr=W(()=>{"use strict";Nu=[/^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 By(e){if(!Qt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Fy(e){if(e instanceof HTTPError){let t=e.response.status;il.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&&Bu[r]?new Error(Bu[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?(il.debug(`Non-HTTP error during authentication: ${e.message}`),e):(il.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qr(e){let t=Ut("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");By(e.tenant);let r;try{r=await cp.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Fy(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Er(e),await Uu({accessToken:r.access_token,expiresAt:n});let o=$n(r.access_token);await Fs({sub:o.sub,name:o.name,email:o.email});}var il,Bu,Ks=W(()=>{"use strict";Ce();js();Zr();R();F();il=b("api:auth");Bu={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 Pr()){let n=await Bs();if(n)return n.accessToken}Fu.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");ze.clearFallbackFile(),Ns(),await Qr(t);let r=await Bs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Fu.debug("Token refreshed successfully"),r.accessToken}var Fu,_n=W(()=>{"use strict";Ce();Ks();vo();R();Fu=b("lib:tokenProvider");});function Ht(){return cp.create({prefix:Ut("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 te();r?.tenant&&Qt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Uo=W(()=>{"use strict";Zr();Ce();_n();F();});function tp(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 Fn(e,t,r){let n=Ht(),o=tp({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function rp(e,t={}){let r=Ht(),n=tp(t);return n?r.head(e,n):r.head(e)}async function jn(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 kl=W(()=>{"use strict";Uo();});function No(e){if(!e||!OS.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Kn(e){return US.test(e)}function Hn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Rl(e){if(!NS.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 Vn(e,t){let r=Hn(e);Rl(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(!BS.test(t)&&!FS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var OS,US,NS,BS,FS,Or=W(()=>{"use strict";OS=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;US=/^[^@]+@[^@]+$/;NS=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;BS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,FS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var sp={};pu(sp,{FlowApiAdapter:()=>Wn});var jS,Wn,$l=W(()=>{"use strict";Uo();kl();R();Or();jS=b("catalog.flow-api"),Wn=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 Fn("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 jn(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){No(t);try{return await Fn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await jn(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 Ht().head("v1/plugins/catalog"),jS.debug("ping ok"),!0}catch{return !1}}};});function HS(){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 ap(){return ip??=HS(),ip}var ip,lp=W(()=>{"use strict";});var dp={};pu(dp,{GitRepoAdapter:()=>Jn});function up(e,t){if(!VS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var VS,Jn,_l=W(()=>{"use strict";lp();Zr();VS=/^[a-zA-Z0-9_.-]+$/;Jn=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(sl(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return up(a,"owner"),up(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 cp.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 cp.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 ap();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(Ca),origins:new Set(ka)},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(Ca)},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(ka)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ce();_n();js();F();Zr();R();var Hs=b("api:metrics");function ju(){return Ut("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ku(e,t,r){return cp.post(e,{json:t,headers:r})}async function Ky(e){let t=await Rn();if(t)return t;let r=$n(e),n={sub:r.sub,name:r.name,email:r.email};return await Fs(n),n}async function P(e,t){let r=await Nt(),n=await Ky(r),o=await te();if(!Qt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ta,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Ku(ju(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Hs.debug(`Metrics event sent: ${e}`);}catch(i){throw Hs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Hu(e,t,r){try{let n=r&&Qt.test(r)?r:"unknown",o={action:e,booster:Ta,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Ku(ju(),o,{FlowTenant:n}),Hs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Hs.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 Hy={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},St={...Hy};function Vu(e){let t=Date.now();St={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function en(e){St.currentStep=e,St.stepStart=Date.now();}function Q(){return {...St}}function Tr(){return St.sessionStart===0?0:Date.now()-St.sessionStart}function tn(){return St.stepStart===0?0:Date.now()-St.stepStart}function Wu(){St.tuiSessionStart=Date.now();}function Ju(){return St.tuiSessionStart===0?0:Date.now()-St.tuiSessionStart}R();var Vy=3e3,Wy=b("abandonment");async function Vs(e){let{currentStep:t,sessionStart:r}=Q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Tr()};try{await Promise.race([P(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Vy))]);}catch(o){Wy.warn(`Abandonment event failed: ${String(o)}`);}}function Gu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var Jy=3e3,Gy=b("session-end");async function Eo(e,t,r){let n=Ju(),s=[P(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Vs(e));try{await Gu(Promise.all(s).then(()=>{}),Jy);}catch(i){Gy.warn(`Session end event failed: ${String(i)}`);}}var Yy=2e3;function Xu(){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),Eo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Yy);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var tw=16;function qu({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(tw)}),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 Yu({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:En}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function Zu({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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 Qu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[yr," \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 nt=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})}));Ks();F();function on(){return oe__default.join(Te__default.homedir(),".claude","settings.json")}function td(e){return `${(e&&e.trim().length>0?e.trim():Ss).replace(/\/+$/,"")}/flow-litellm/`}function $o(){let e=on();if(!le__default.existsSync(e))return {status:"missing"};let t=le__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 Js(e){let t=on();le__default.mkdirSync(oe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function rd(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 ml(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 nd(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 lw=3600,sn=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function _o(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 cw(e){return aw.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:lw})}function Gs(e,t={}){let r=$o();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new sn;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?ml(r.settings):null,s=r.status==="ok"?nd(r.settings):null,i=t.jwtOverride??cw(e),a=td(e.customUrl),l=rd(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function zs(e){Js(e.merged);}function od(){let e=$o();return e.status!=="ok"?false:ml(e.settings)!==null}Ce();Ne();function uw(){let e=Su();if(!le__default.existsSync(e))return {};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {}}}var fl=null;function dw(){return fl===null&&(fl=uw()),fl}function Ar(){return !!dw().ENABLE_EXPERIMENTAL_BETAS}F();function gw(){return de.filter(e=>e.platforms[process.platform]?.status==="supported")}function id(e){let t=gw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Xs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=oe__default.join(Te__default.homedir(),".claude","settings.json"),r=le__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??Ss),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"}},hw={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},de=Ar()?[Xs,hw]:[Xs];Ce();R();var bw=b("moduleState");function Ys(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"modules.json")}var xw={retries:5,minTimeout:50};async function ad(e,t){le__default.mkdirSync(oe__default.dirname(e),{recursive:true});let r=await Sw.lock(e+".lock",{realpath:false,retries:xw});try{return await t()}finally{await r();}}function ld(){let e=Ys();if(!le__default.existsSync(e))return [];try{let t=JSON.parse(le__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(bw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),le__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return le__default.rmSync(e,{force:true}),[]}}function an(){return ld()}function cd(e){let t=Ys();le__default.mkdirSync(oe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};le__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function ot(e){return an().find(t=>t.alias===e)??null}async function bt(e){let t=Ys();await ad(t,async()=>{let r=ld(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,cd(r);});}async function ln(){let e=Ys();le__default.existsSync(e)||await ad(e,async()=>{le__default.existsSync(e)||cd([]);});}var Ew=promisify(execFile);function Rr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Ft(e){let t=process.platform==="win32"?"where":"which";try{return await Ew(t,[e]),!0}catch{return false}}function tr(){return process.platform==="win32"?"npm.cmd":"npm"}var ud=promisify(execFile),Ln=class{type="npm";async isAvailable(){return Ft("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Rr(t,"npm");if(!r)return null;try{let{stdout:n}=await ud(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=Rr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await ud(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 Zs=promisify(execFile),Aw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Qs=class{type="homebrew";async isAvailable(){return Ft("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Rr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Rr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Zs("brew",["tap",o.tap]),await Zs("brew",["trust",o.tap])),await Zs("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 Zs("brew",["list","--versions",t]),n=r.trim().match(Aw);return n?n[2]:null}catch{return null}}};var Dn=promisify(execFile),pd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function md(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"bin")}var ei=class{type="curl";async isAvailable(){return Ft("curl")}async install(t){let r=Date.now(),n=Rr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=oe__default.join(md(),oe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Dn(n,["--version"]),s=o.match(pd);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=oe__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Dn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{le__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return le__default.chmodSync(s,448),await Dn("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{le__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=md(),i=oe__default.join(s,oe__default.basename(n.binaryName)),a=false;try{if(le__default.mkdirSync(s,{recursive:!0}),a=!0,await Dn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return le__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}le__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Dn(i,["--version"]),c=u.match(pd);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{le__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=oe__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Dn("curl",["-L","--fail","-o",n,r]);let o=le__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=le__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{le__default.unlinkSync(n);}catch{}}}};R();var fd="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(fd=e.version);}catch{}var he=fd;var Me=b("moduleInstaller");function Kt(e){switch(e){case "npm":return new Ln;case "homebrew":return new Qs;case "curl":return new ei}}async function Mo(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 _r(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 Mo(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 Mo(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 Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Kt(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 Mo(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:he,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 bt({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 Ow(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Mo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Ow(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await te(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return 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 ti(e,t){let r=Date.now(),n=ot(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=Kt(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:he,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 bt({...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 ri=b("flowAiObsSetup");async function ni(e,t){try{if(!await new Ln().isAvailable().catch(()=>!1))return ri.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await _r(Xs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ri.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ri.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ri.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function gd(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 Uw=b("useAuthSetup");function hd(){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,g]=useState(null),y=useRef(0),f=useRef(false),{setCredentials:h,setJustAuthenticated:v}=nt(),_=()=>{m("fields"),g(null),t(""),r.current=null,n.current=null,o.current=null;},D=()=>{P(E.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});},C=async H=>{f.current=true;let Y={...r.current,customUrl:n.current??void 0};try{H&&zs(H),await Er(Y);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),f.current=false;return}let{clientSecret:A,...j}=Y;h(j),v(true),D(),await ni(n.current,o.current).catch(J=>Uw.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),oi({starterKit:j.starterKit});},$=async()=>C(),O=async H=>C(H),U=H=>{try{let Y={...r.current,customUrl:n.current??void 0};return Gs(Y,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(Y){return Y instanceof sn?(m("malformedConfirm"),null):(l(Y instanceof Error?Y.message:"Failed to read settings.json"),m("fields"),null)}},se=()=>{let H=U(true);H&&(g(H),O(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let Y;try{Y=_o(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Y,m("customUrl");},V=H=>{n.current=H,m("email");},re=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Ot(H),c(true),l(null),y.current+=1;try{await Qr(r.current);let Y=U(!1);Y&&(g(Y),m("preview"));}catch(Y){let A=Y instanceof Error?Y.message:"Authentication failed";l(A),Hu(E.CLI_AUTH_FAILED,{error_code:gd(Y),attempt:y.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:f,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:re,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:se}}F();N();function yd(){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:g,planPersistOverwrite:y}=hd(),[f,h]=useState("confirm"),[v,_]=useState(""),D=useRef(""),[C,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(h("confirm"),D.current="",_(""),$(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?g():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?y():U.escape&&u();return}if(o==="customUrl"){if(f==="confirm")O==="y"||O==="Y"?h("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)D.current="",_(""),h("confirm");else if(U.return){let se=D.current.trim();se.length>0&&xn.test(se)?($(false),d(se)):se.length>0&&$(true);}else U.backspace||U.delete?(D.current=D.current.slice(0,-1),_(D.current)):O&&!U.ctrl&&!U.meta&&(D.current=D.current+O,_(D.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:[yr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&f==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&f==="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:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:vn}),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:[yr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Yu,{onConfirm:m})]}):o==="preview"&&s?jsx(Zu,{plan:s}):o==="malformedConfirm"?jsx(Qu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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(qu,{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 ",w(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Un(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Kw,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",he]})})]})}var xd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ae=Ar()?xd:xd.slice(0,3);function Hw(e){return ae.findIndex(t=>t.id===e)}function yl(e,t,r){let n=Hw(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 Ed={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Pd({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?`${Ed[r]} (${e})`:Ed[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Xe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Cd(){let e=S(i=>i.focus),t=Xe(i=>i.query),r=Xe(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 kd=Object.keys(Sr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...Sr[e]})),Ad=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...mu[e]}));function Rd(){let e=S(n=>n.catalogFilters),t=kd.every(n=>e.types.has(n.type)),r=Ad.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"]})]}),kd.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"]})]}),Ad.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 $d({type:e}){let{label:t,color:r}=Sr[e];return jsx(Text,{color:r,children:t})}F();function Ld({origin:e}){return e===ho?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ii=Xw.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($d,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ld,{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 ",Dt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Nn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Ud({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Nn,{message:t});let n=Math.max(0,r-Math.floor(tt/2)),o=Math.min(e.length,n+tt);o===e.length&&(n=Math.max(0,o-tt));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(ii,{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 Fd({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 Kd({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 g of p.items)n.push({kind:"item",item:g,itemIndex:o,key:`i-${p.scope}-${g.name}-${g.marketplace??""}`}),o++;}if(o===0)return jsx(Nn,{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(tt/2)),u=Math.min(n.length,l+tt);u===n.length&&(l=Math.max(0,u-tt));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(Fd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ii,{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 nS={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function oS({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Cd,{}),jsx(Rd,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:nS[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Kd,{groups:n,emptyMessage:r}):jsx(Ud,{items:e,emptyMessage:r})]})}function Hd({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(oS,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var aS={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 ai(){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:[aS[e],t?" | Ctrl+D: debug log":""]})})}N();function Vd({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"," ",w(e)]})}):null}function li({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(am,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Lr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var zd=20;function ci(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*zd),s="\u2588".repeat(o)+"\u2591".repeat(zd-o),i=`${Lr(e)} / ${Lr(t)}`;return {bar:s,percent:n,label:i}}function ui({received:e,total:t}){let{bar:r,percent:n,label:o}=ci(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 st({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 Cl=Object.entries(Lt),Zd=[...Cl.map(([,e])=>e.actionLabel),"Cancel"],Qd=Object.fromEntries(Cl.map(([,e])=>[e.actionLabel,e.description]));function ep(e){let t=Cl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var vS=b("provider.registry"),IS=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()+IS}),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"&&vS.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 ES={user:"global",project:"project",local:"local"};function fi(e){return e?ES[e]:"global"}var qe=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},Dr=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};Uo();kl();R();var CS=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);CS.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()]}};Ne();var DS={retries:5,minTimeout:50};async function Al(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Sw.lock(e+".lock",{realpath:false,retries:DS});try{return await t()}finally{await r();}}var hi=class{filePath;constructor(t){this.filePath=t??wu();}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 Al(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 Al(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Al(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));});}};$l();var ye=new gi,nr=new hi,WS=["flow-harness"];function JS(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?WS:e.split(",").map(t=>t.trim()).filter(Boolean)}ye.register(new Wn);for(let e of JS())ye.register(new Wn(e));var pp=false;async function mp(){if(pp)return;pp=true;let e=await nr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(_l(),dp));for(let r of e)ye.register(new t(r.id,r.name,r.source));}Or();function fp(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 zS=b("api:actions"),gp=2;async function or(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>($l(),sp));return new t(e).fetchItems()}return ye.fetchAll()}async function hp(){return ye.fetchAllWithErrors()}async function Gn(e,t){No(e);try{return await Fn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await jn(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 XS(e,t){try{let n=(await rp(`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){zS.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function yp(e,t,r){No(e);try{let n=await XS(e,r),o=fp(n),s=await Fn(`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:g,value:y}=await d.read();if(g)break;if(p+=y.byteLength,u&&p>l*gp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*gp}`);m.push(y),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 jn(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 Ht().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}}Ne();Ne();async function wp(e,t){let r=oe.resolve(t);await Vt.mkdir(r,{recursive:true});let n=oe.join(oe.dirname(r),`${randomUUID()}.zip`);try{await Vt.writeFile(n,e);let o=await YS.Open.file(n),s=oe.normalize(r+oe.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=oe.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(oe.resolve(oe.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 Vt.unlink(n);}catch{}}}async function Ml(e){await Vt.rm(e,{recursive:true,force:true});}async function sr(){let e=hu();await Vt.mkdir(oe.dirname(e),{recursive:true});try{await Vt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Sw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Ne();F();R();var tb=b("marketplace-registry");function rb(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 bp(e){let t=wo(e);if(!le__default.existsSync(t))return null;try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return null}}function nb(e){let t=bp(e);if(t)return t;let r=rb(e),n=wo(e);return le__default.mkdirSync(oe__default.dirname(n),{recursive:true}),Ol(r,e),r}function Ol(e,t){let r=wo(t),n=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(n,r);}function ob(e){let t=e||Ue,r=zr(),n={};try{le__default.existsSync(r)&&(n=JSON.parse(le__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:Ma(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,r);}async function Ll(e,t){let r=Ma(e),n=oe__default.relative(r,wo(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){tb.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function xp(e,t,r){it(e.name),ob(r);let n=_a(e.name,r);le__default.mkdirSync(oe__default.dirname(n),{recursive:true});try{le__default.lstatSync(n),le__default.rmSync(n,{recursive:!0,force:!0});}catch{}le__default.cpSync(t,n,{recursive:true,dereference:true});let o=nb(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}),Ol(o,r)),await Ll(r,`chore: register ${e.name}@${e.version}`);}async function Ul(e,t){it(e);let r=_a(e,t);try{le__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=bp(t);if(!n){await Ll(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Ol(n,t),await Ll(t,`chore: unregister ${e}`);}N();R();var ib=b("mcpConfigReader"),ab=500,lb=512;function cb(){return oe__default.join(Te__default.homedir(),".claude.json")}function ub(){return oe__default.join(process.cwd(),".mcp.json")}function Ip(e){if(!le__default.existsSync(e))return null;try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return ib.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nl(e){if(!Bo(e))return {};let t=e.mcpServers;return Bo(t)?t:{}}function Bl(e,t){return Object.keys(e).slice(0,ab).map(n=>({name:w(n.slice(0,lb)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Pp(){let e=[],t=cb(),r=Ip(t);if(Bo(r)){let a=r,l=Nl(a);e.push(...Bl(l,"user"));let u=process.cwd();if(Bo(a.projects)){let c=a.projects[u];if(Bo(c)){let d=Nl(c);e.push(...Bl(d,"local"));}}}let n=ub(),o=Ip(n),s=Nl(o);e.push(...Bl(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();var ke=b("storage");async function pb(e,t,r){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Q().interfaceType});}catch(n){ke.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function mb(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:Q().interfaceType}).catch(o=>ke.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Hl(){return oe__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function Cp(){return oe__default.join(Te__default.homedir(),".claude","plugins")}function Fo(e){let t;try{t=le__default.realpathSync(e);}catch{t=oe__default.resolve(e);}let r=oe__default.resolve(Cp()),n=oe__default.resolve(oe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+oe__default.sep),s=t.startsWith(n+oe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function kp(e="user"){return e==="local"?oe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?oe__default.join(process.cwd(),".claude","settings.json"):oe__default.join(Te__default.homedir(),".claude","settings.json")}function Pe(){let e=Hl();if(!le__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Vl(){let e=Hl();try{let t=await le__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function fb(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ap(e,t){try{le__default.mkdirSync(oe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,e);}catch(r){throw fb(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){Ap(Hl(),e);}function zn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function gb(e,t){let r=oe__default.join(e,".claude-plugin"),n=oe__default.join(r,"plugin.json");if(le__default.existsSync(n))try{return JSON.parse(le__default.readFileSync(n,"utf-8"))}catch{return null}let o=oe__default.join(r,"marketplace.json");if(le__default.existsSync(o))try{let s=JSON.parse(le__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function jo(e="user"){let t=kp(e);if(!le__default.existsSync(t))return {};try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return {}}}function Si(e,t="user"){Ap(kp(t),e);}function hb(e,t){let{name:r,marketplace:n}=zn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>zn(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 yb(e,t){let{name:r,marketplace:n}=zn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>zn(i).name===r)[0],o?{key:o,name:r}:null}function Fl(e="user"){return jo(e).enabledPlugins??{}}function jl(e,t="user"){let r=jo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Si(r,t);}function Ko(e,t,r="user"){let n=jo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Si(n,r);}function wb(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 me(){let e=Pe(),t=Fl(),r=Fl("project"),n=Fl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=zn(u),p=c.map(y=>y.scope==="managed"?{...y,scope:"user"}:y);return wb(p).map(y=>{let f=gb(y.installPath,d),v=(o[y.scope]??t)[u];return {name:d,marketplace:m,version:y.version&&y.version!=="unknown"?y.version:void 0,installedAt:y.installedAt,installPath:y.installPath,scope:y.scope,providerId:y.providerId,type:y.type,description:f?.description,author:f?.author,status:v===false?"disabled":"enabled"}})}),i=Pp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Tp(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Ho(e,t){ke.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=Pe(),o=yb(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(m=>m.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);ke.debug(`[${i}] Resolved key: ${s}, scope: ${t}`);let u=oe__default.dirname(l.installPath),c=a.filter(m=>m.scope!==t);if(c.some(m=>oe__default.dirname(m.installPath)===u)?ke.debug(`[${i}] Directory still used by another scope, keeping: ${u}`):(Fo(l.installPath),Fo(u),ke.debug(`[${i}] Removing directory: ${u}`),le__default.rmSync(u,{recursive:!0,force:!0})),c.length===0){let{[s]:m,...p}=n.plugins;at({...n,plugins:p}),jl(s,t),await Ul(i,Tp(s));}else n.plugins[s]=c,at(n),jl(s,t);}else {ke.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Fo(c.installPath);let d=oe__default.dirname(c.installPath);Fo(d),ke.debug(`[${i}] Removing directory: ${d}`),le__default.rmSync(d,{recursive:!0,force:!0}),jl(s,c.scope);}await Ul(i,Tp(s));let{[s]:l,...u}=n.plugins;at({...n,plugins:u});}await pb(i,a[0].origin??"internal",a[0].type??"skill"),ke.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Vo(e,t,r){ke.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=Pe(),{key:s,name:i}=hb(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}`),Ko(s,t==="enabled",l),mb(i,t,u),ke.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Sb=/^\d+$/;function bb(e){let t=oe__default.join(e,".in_use"),r;try{r=le__default.readdirSync(t);}catch{return false}for(let n of r){if(!Sb.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var xb=20;function Rp(e,t=0){if(t>xb)return 0;let r=0,n;try{n=le__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=oe__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=Rp(s,t+1);else if(o.isFile())try{r+=le__default.statSync(s).size;}catch{}}}return r}function vb(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=zn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.version&&a.add(l.version);r.set(s,a);}return r}function $p(){let e=Pe(),t=[];for(let r of wr){let n=vb(e,r),o=oe__default.join(Cp(),"cache",r),s;try{s=le__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=oe__default.join(o,a),u=n.get(a)??new Set,c;try{c=le__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=oe__default.join(l,m);bb(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:Rp(p)});}}}return t}async function _p(e){let t=await sr(),r=[],n=[];try{for(let s of e)try{Fo(s.path),le__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:Q().interfaceType}).catch(s=>ke.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}Ne();function Wl(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,Wl(r)]))}function Wo(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(Wl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Wl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Wo(s,o):r[n]=o;}return r}R();var Jl=b("bundleContent"),bi="${CLAUDE_PLUGIN_ROOT}/hooks/";function Ib(e){return e.split(bi).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Gl(e){return typeof e=="string"?Ib(e):Array.isArray(e)?e.map(Gl):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Gl(r)])):e}function Eb(e,t){let r=oe__default.join(e,"rules");if(!le__default.existsSync(r))return 0;let n=le__default.readdirSync(r).filter(s=>s.endsWith(".md")&&le__default.lstatSync(oe__default.join(r,s)).isFile());if(n.length===0)return 0;let o=Tn(t);le__default.mkdirSync(o,{recursive:true});for(let s of n)le__default.copyFileSync(oe__default.join(r,s),oe__default.join(o,s));return n.length}function Pb(e,t){let r=oe__default.join(e,"hooks","hooks.json");if(!le__default.existsSync(r))return 0;let n;try{n=JSON.parse(le__default.readFileSync(r,"utf-8"));}catch(g){return Jl.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(g)}`),0}let o=n.hooks;if(!o||typeof o!="object"||Array.isArray(o))return 0;let s=oe__default.join(e,"hooks"),i=Da(t),a=new Set,l=g=>{if(typeof g=="string"&&g.includes(bi)){let y=g.slice(g.indexOf(bi)+bi.length),f=/^([^"'\s]+)/.exec(y);f&&a.add(f[1]);}else Array.isArray(g)?g.forEach(l):g!==null&&typeof g=="object"&&Object.values(g).forEach(l);};l(o);let u=0;if(a.size>0){le__default.mkdirSync(i,{recursive:true});for(let g of a){let y=oe__default.join(s,g);le__default.existsSync(y)&&(le__default.copyFileSync(y,oe__default.join(i,g)),u++);}}let c=Gl(o),d=jo(t),m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Wo(m,c);return Si({...d,hooks:p},t),u}function xi(e,t){let r=Eb(e,t),n=Pb(e,t);r>0&&Jl.debug(`Copied ${r} rule file(s) to ${Tn(t)}`),n>0&&Jl.debug(`Copied ${n} hook script(s) to ${Da(t)}`);}F();R();var Tb=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Cb=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function it(e){if(!Tb.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function kb(e){if(!Cb.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 Nr=b("installer");function Ab(e,t,r){let n=`${e}@${r||Ue}`,s=Pe().plugins[n];if(s&&!t)throw new qe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function Rb(e,t,r){r&&await Ml(t);try{Nr.debug(`[${t}] Extracting archive...`),await wp(e,t);}catch(n){throw await Ml(t),n}}function $b(e,t,r,n,o,s="claude-code",i){let a=Pe(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],at(a),Ko(e,true,n);}async function _b(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:Q().interfaceType});}catch(i){Nr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Mb(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:Q().interfaceType});}catch(o){Nr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ke(e,t={}){let r=Date.now(),n=null;try{Nr.debug(`[${e}] Acquiring lock...`),n=await sr();let{pluginKey:o,alreadyInstalled:s}=Ab(e,t.force,t.source),{source:i}=t;Nr.debug(`[${e}] Fetching manifest...`);let a=await Gn(e,i);it(a.name),kb(a.version),Nr.debug(`[${e}] Downloading archive...`);let l=await yp(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=gu(a.name,a.version,t.source);await Rb(l,d,!!s&&!!t.force),await xi(d,u),$b(o,d,a.version,u,"internal",t.providerId,c),await xp(a,d,t.source);let m=Date.now()-r;Nr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await _b(a.name,a.version,m,fi(u),"internal",c),p}catch(o){throw await Mb(e,o,"internal",t.type??"skill"),Nr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Ce();_n();R();var Lb=b("commands:helpers");async function q(){let e=await te();if(!e)return I("Not authenticated. Run: flow auth login"),false;e.customUrl&&Ot(e.customUrl);try{await Nt();}catch(t){return Lb.debug(`Token validation failed: ${String(t)}`),I("Session expired. Run: flow auth login"),false}return true}async function z(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Xn(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim());});})}var Db="\x1B[A",Ob="\x1B[B";function Mp(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function Ub(e,t){return e.map((r,n)=>Mp(r,n===t)).join(`
110
+ `),this.warned=!0;}Ms().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ms(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return Ms().path}static hasExistingData(){try{let t=new Qa({projectName:el});return le.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Qa({projectName:el});le.rmSync(t.path,{force:!0});}catch{}Ls=null;}};});async function tl(){if(ze.hasExistingData())return new ze;switch(process.platform){case "darwin":return await kn.isAvailable()?new kn:new ze;case "linux":return await vr.isAvailable()?new vr:await vr.ensureInstalled()?new vr:new ze;case "win32":return await An.isAvailable()?new An:new ze;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var _u=W(()=>{"use strict";Wa();za();Za();vo();});var Mu=W(()=>{"use strict";Aa();Ha();_u();Wa();za();Za();vo();});async function Ir(){return Us||(Us=tl()),Us}function Ns(){Us=null;}async function te(){let t=await(await Ir()).getSecret(er,rl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Er(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 Lu.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Ir()).setSecret(er,rl,JSON.stringify(e));}async function Du(){let e=await Ir();await e.deleteSecret(er,rl),await e.deleteSecret(er,nl),await e.deleteSecret(er,ol);}async function Ou(){return (await Ir()).getStoragePath()}async function Uu(e){await(await Ir()).setSecret(er,nl,JSON.stringify(e));}async function Bs(){let t=await(await Ir()).getSecret(er,nl);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Fs(e){await(await Ir()).setSecret(er,ol,JSON.stringify(e));}async function Rn(){let t=await(await Ir()).getSecret(er,ol);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Pr(){let e=await Bs();return e?new Date(e.expiresAt)>new Date:false}function Ot(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/`,Lu.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Lu,er,rl,nl,ol,Us,Ce=W(()=>{"use strict";Mu();R();Lu=b("config:credentials"),er="flow-plugins-cli",rl="credentials",nl="token-cache",ol="user-info",Us=null;});function $n(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 js=W(()=>{"use strict";});function Oy(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 sl(e){if(Nu.some(r=>r.test(e)))return true;let t=Oy(e);return !!(t&&Nu.some(r=>r.test(t)))}function Uy(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ut(e,t){let r=Uy(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&&sl(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Nu,Zr=W(()=>{"use strict";Nu=[/^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 Fy(e){if(!Qt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function jy(e){if(e instanceof HTTPError){let t=e.response.status;il.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&&Bu[r]?new Error(Bu[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?(il.debug(`Non-HTTP error during authentication: ${e.message}`),e):(il.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qr(e){let t=Ut("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Fy(e.tenant);let r;try{r=await cp.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await jy(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Er(e),await Uu({accessToken:r.access_token,expiresAt:n});let o=$n(r.access_token);await Fs({sub:o.sub,name:o.name,email:o.email});}var il,Bu,Ks=W(()=>{"use strict";Ce();js();Zr();R();F();il=b("api:auth");Bu={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 Pr()){let n=await Bs();if(n)return n.accessToken}Fu.debug("Token expired or missing, re-authenticating...");let t=await te();if(!t)throw new Error("Not authenticated. Run: flow auth login");ze.clearFallbackFile(),Ns(),await Qr(t);let r=await Bs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Fu.debug("Token refreshed successfully"),r.accessToken}var Fu,_n=W(()=>{"use strict";Ce();Ks();vo();R();Fu=b("lib:tokenProvider");});function Ht(){return cp.create({prefix:Ut("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 te();r?.tenant&&Qt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Uo=W(()=>{"use strict";Zr();Ce();_n();F();});function tp(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 Fn(e,t,r){let n=Ht(),o=tp({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function rp(e,t={}){let r=Ht(),n=tp(t);return n?r.head(e,n):r.head(e)}async function jn(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 kl=W(()=>{"use strict";Uo();});function No(e){if(!e||!US.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Kn(e){return NS.test(e)}function Hn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Rl(e){if(!BS.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 Vn(e,t){let r=Hn(e);Rl(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(!FS.test(t)&&!jS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var US,NS,BS,FS,jS,Or=W(()=>{"use strict";US=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;NS=/^[^@]+@[^@]+$/;BS=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;FS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,jS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var sp={};pu(sp,{FlowApiAdapter:()=>Wn});var KS,Wn,$l=W(()=>{"use strict";Uo();kl();R();Or();KS=b("catalog.flow-api"),Wn=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 Fn("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 jn(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){No(t);try{return await Fn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await jn(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 Ht().head("v1/plugins/catalog"),KS.debug("ping ok"),!0}catch{return !1}}};});function VS(){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 ap(){return ip??=VS(),ip}var ip,lp=W(()=>{"use strict";});var dp={};pu(dp,{GitRepoAdapter:()=>Jn});function up(e,t){if(!WS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var WS,Jn,_l=W(()=>{"use strict";lp();Zr();WS=/^[a-zA-Z0-9_.-]+$/;Jn=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(sl(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return up(a,"owner"),up(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 cp.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 cp.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 ap();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(Ca),origins:new Set(ka)},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(Ca)},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(ka)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ce();_n();js();F();Zr();R();var Hs=b("api:metrics");function ju(){return Ut("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ku(e,t,r){return cp.post(e,{json:t,headers:r})}async function Hy(e){let t=await Rn();if(t)return t;let r=$n(e),n={sub:r.sub,name:r.name,email:r.email};return await Fs(n),n}async function P(e,t){let r=await Nt(),n=await Hy(r),o=await te();if(!Qt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ta,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Ku(ju(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Hs.debug(`Metrics event sent: ${e}`);}catch(i){throw Hs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Hu(e,t,r){try{let n=r&&Qt.test(r)?r:"unknown",o={action:e,booster:Ta,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Ku(ju(),o,{FlowTenant:n}),Hs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Hs.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 Vy={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},St={...Vy};function Vu(e){let t=Date.now();St={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function en(e){St.currentStep=e,St.stepStart=Date.now();}function Q(){return {...St}}function Tr(){return St.sessionStart===0?0:Date.now()-St.sessionStart}function tn(){return St.stepStart===0?0:Date.now()-St.stepStart}function Wu(){St.tuiSessionStart=Date.now();}function Ju(){return St.tuiSessionStart===0?0:Date.now()-St.tuiSessionStart}R();var Wy=3e3,Jy=b("abandonment");async function Vs(e){let{currentStep:t,sessionStart:r}=Q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Tr()};try{await Promise.race([P(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Wy))]);}catch(o){Jy.warn(`Abandonment event failed: ${String(o)}`);}}function Gu(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var Gy=3e3,zy=b("session-end");async function Eo(e,t,r){let n=Ju(),s=[P(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Vs(e));try{await Gu(Promise.all(s).then(()=>{}),Gy);}catch(i){zy.warn(`Session end event failed: ${String(i)}`);}}var Zy=2e3;function Xu(){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),Eo("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Zy);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var rw=16;function qu({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(rw)}),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 Yu({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:En}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}F();function Zu({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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 Qu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[yr," \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 nt=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})}));Ks();F();function on(){return oe__default.join(Te__default.homedir(),".claude","settings.json")}function td(e){return `${(e&&e.trim().length>0?e.trim():Ss).replace(/\/+$/,"")}/flow-litellm/`}function $o(){let e=on();if(!le__default.existsSync(e))return {status:"missing"};let t=le__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 Js(e){let t=on();le__default.mkdirSync(oe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function rd(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 ml(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 nd(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 cw=3600,sn=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function _o(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 uw(e){return lw.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:cw})}function Gs(e,t={}){let r=$o();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new sn;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?ml(r.settings):null,s=r.status==="ok"?nd(r.settings):null,i=t.jwtOverride??uw(e),a=td(e.customUrl),l=rd(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function zs(e){Js(e.merged);}function od(){let e=$o();return e.status!=="ok"?false:ml(e.settings)!==null}Ce();Ne();function dw(){let e=Su();if(!le__default.existsSync(e))return {};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {}}}var fl=null;function pw(){return fl===null&&(fl=dw()),fl}function Ar(){return !!pw().ENABLE_EXPERIMENTAL_BETAS}F();function hw(){return de.filter(e=>e.platforms[process.platform]?.status==="supported")}function id(e){let t=hw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Xs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=oe__default.join(Te__default.homedir(),".claude","settings.json"),r=le__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??Ss),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"}},yw={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},de=Ar()?[Xs,yw]:[Xs];Ce();R();var xw=b("moduleState");function Ys(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"modules.json")}var vw={retries:5,minTimeout:50};async function ad(e,t){le__default.mkdirSync(oe__default.dirname(e),{recursive:true});let r=await bw.lock(e+".lock",{realpath:false,retries:vw});try{return await t()}finally{await r();}}function ld(){let e=Ys();if(!le__default.existsSync(e))return [];try{let t=JSON.parse(le__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(xw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),le__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return le__default.rmSync(e,{force:true}),[]}}function an(){return ld()}function cd(e){let t=Ys();le__default.mkdirSync(oe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};le__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,t);}function ot(e){return an().find(t=>t.alias===e)??null}async function bt(e){let t=Ys();await ad(t,async()=>{let r=ld(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,cd(r);});}async function ln(){let e=Ys();le__default.existsSync(e)||await ad(e,async()=>{le__default.existsSync(e)||cd([]);});}var Pw=promisify(execFile);function Rr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Ft(e){let t=process.platform==="win32"?"where":"which";try{return await Pw(t,[e]),!0}catch{return false}}function tr(){return process.platform==="win32"?"npm.cmd":"npm"}var ud=promisify(execFile),Ln=class{type="npm";async isAvailable(){return Ft("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Rr(t,"npm");if(!r)return null;try{let{stdout:n}=await ud(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=Rr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await ud(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 Zs=promisify(execFile),Rw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Qs=class{type="homebrew";async isAvailable(){return Ft("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Rr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=Rr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Zs("brew",["tap",o.tap]),await Zs("brew",["trust",o.tap])),await Zs("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 Zs("brew",["list","--versions",t]),n=r.trim().match(Rw);return n?n[2]:null}catch{return null}}};var Dn=promisify(execFile),pd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function md(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"bin")}var ei=class{type="curl";async isAvailable(){return Ft("curl")}async install(t){let r=Date.now(),n=Rr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=oe__default.join(md(),oe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Dn(n,["--version"]),s=o.match(pd);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=oe__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Dn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{le__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return le__default.chmodSync(s,448),await Dn("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{le__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=md(),i=oe__default.join(s,oe__default.basename(n.binaryName)),a=false;try{if(le__default.mkdirSync(s,{recursive:!0}),a=!0,await Dn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return le__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}le__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Dn(i,["--version"]),c=u.match(pd);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{le__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=oe__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Dn("curl",["-L","--fail","-o",n,r]);let o=le__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=le__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{le__default.unlinkSync(n);}catch{}}}};R();var fd="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(fd=e.version);}catch{}var he=fd;var Me=b("moduleInstaller");function Kt(e){switch(e){case "npm":return new Ln;case "homebrew":return new Qs;case "curl":return new ei}}async function Mo(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 _r(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 Mo(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 Mo(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 Mo(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Kt(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 Mo(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:he,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 bt({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 Uw(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Mo(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Uw(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await te(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return 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 ti(e,t){let r=Date.now(),n=ot(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=Kt(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:he,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 bt({...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 ri=b("flowAiObsSetup");async function ni(e,t){try{if(!await new Ln().isAvailable().catch(()=>!1))return ri.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await _r(Xs,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ri.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ri.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ri.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function gd(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 Nw=b("useAuthSetup");function hd(){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,g]=useState(null),y=useRef(0),f=useRef(false),{setCredentials:h,setJustAuthenticated:v}=nt(),_=()=>{m("fields"),g(null),t(""),r.current=null,n.current=null,o.current=null;},D=()=>{P(E.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});},C=async H=>{f.current=true;let Y={...r.current,customUrl:n.current??void 0};try{H&&zs(H),await Er(Y);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),_(),f.current=false;return}let{clientSecret:A,...j}=Y;h(j),v(true),D(),await ni(n.current,o.current).catch(J=>Nw.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),oi({starterKit:j.starterKit});},$=async()=>C(),O=async H=>C(H),U=H=>{try{let Y={...r.current,customUrl:n.current??void 0};return Gs(Y,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(Y){return Y instanceof sn?(m("malformedConfirm"),null):(l(Y instanceof Error?Y.message:"Failed to read settings.json"),m("fields"),null)}},se=()=>{let H=U(true);H&&(g(H),O(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let Y;try{Y=_o(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=Y,m("customUrl");},V=H=>{n.current=H,m("email");},re=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Ot(H),c(true),l(null),y.current+=1;try{await Qr(r.current);let Y=U(!1);Y&&(g(Y),m("preview"));}catch(Y){let A=Y instanceof Error?Y.message:"Authentication failed";l(A),Hu(E.CLI_AUTH_FAILED,{error_code:gd(Y),attempt:y.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:f,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:re,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:se}}F();N();function yd(){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:g,planPersistOverwrite:y}=hd(),[f,h]=useState("confirm"),[v,_]=useState(""),D=useRef(""),[C,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(h("confirm"),D.current="",_(""),$(false));},[o]),useInput((O,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?g():O==="q"&&u();return}if(o==="malformedConfirm"){U.return?y():U.escape&&u();return}if(o==="customUrl"){if(f==="confirm")O==="y"||O==="Y"?h("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)D.current="",_(""),h("confirm");else if(U.return){let se=D.current.trim();se.length>0&&xn.test(se)?($(false),d(se)):se.length>0&&$(true);}else U.backspace||U.delete?(D.current=D.current.slice(0,-1),_(D.current)):O&&!U.ctrl&&!U.meta&&(D.current=D.current+O,_(D.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:[yr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&f==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&f==="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:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:vn}),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:[yr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Yu,{onConfirm:m})]}):o==="preview"&&s?jsx(Zu,{plan:s}):o==="malformedConfirm"?jsx(Qu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[yr," \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(qu,{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 ",w(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Un(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Hw,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",he]})})]})}var xd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ae=Ar()?xd:xd.slice(0,3);function Vw(e){return ae.findIndex(t=>t.id===e)}function yl(e,t,r){let n=Vw(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 Ed={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Pd({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?`${Ed[r]} (${e})`:Ed[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Xe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Cd(){let e=S(i=>i.focus),t=Xe(i=>i.query),r=Xe(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 kd=Object.keys(Sr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...Sr[e]})),Ad=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...mu[e]}));function Rd(){let e=S(n=>n.catalogFilters),t=kd.every(n=>e.types.has(n.type)),r=Ad.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"]})]}),kd.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"]})]}),Ad.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 $d({type:e}){let{label:t,color:r}=Sr[e];return jsx(Text,{color:r,children:t})}F();function Ld({origin:e}){return e===ho?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ii=qw.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($d,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ld,{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 ",Dt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Nn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}F();function Ud({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Nn,{message:t});let n=Math.max(0,r-Math.floor(tt/2)),o=Math.min(e.length,n+tt);o===e.length&&(n=Math.max(0,o-tt));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(ii,{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 Fd({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 Kd({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 g of p.items)n.push({kind:"item",item:g,itemIndex:o,key:`i-${p.scope}-${g.name}-${g.marketplace??""}`}),o++;}if(o===0)return jsx(Nn,{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(tt/2)),u=Math.min(n.length,l+tt);u===n.length&&(l=Math.max(0,u-tt));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(Fd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ii,{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 oS={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function sS({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Cd,{}),jsx(Rd,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:oS[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Kd,{groups:n,emptyMessage:r}):jsx(Ud,{items:e,emptyMessage:r})]})}function Hd({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(sS,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var lS={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 ai(){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:[lS[e],t?" | Ctrl+D: debug log":""]})})}N();function Vd({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"," ",w(e)]})}):null}function li({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(lm,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Lr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var zd=20;function ci(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*zd),s="\u2588".repeat(o)+"\u2591".repeat(zd-o),i=`${Lr(e)} / ${Lr(t)}`;return {bar:s,percent:n,label:i}}function ui({received:e,total:t}){let{bar:r,percent:n,label:o}=ci(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 st({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 Cl=Object.entries(Lt),Zd=[...Cl.map(([,e])=>e.actionLabel),"Cancel"],Qd=Object.fromEntries(Cl.map(([,e])=>[e.actionLabel,e.description]));function ep(e){let t=Cl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var IS=b("provider.registry"),ES=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()+ES}),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"&&IS.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 PS={user:"global",project:"project",local:"local"};function fi(e){return e?PS[e]:"global"}var qe=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},Dr=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};Uo();kl();R();var kS=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);kS.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()]}};Ne();var OS={retries:5,minTimeout:50};async function Al(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bw.lock(e+".lock",{realpath:false,retries:OS});try{return await t()}finally{await r();}}var hi=class{filePath;constructor(t){this.filePath=t??wu();}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 Al(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 Al(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Al(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));});}};$l();var ye=new gi,nr=new hi,JS=["flow-harness"];function GS(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?JS:e.split(",").map(t=>t.trim()).filter(Boolean)}ye.register(new Wn);for(let e of GS())ye.register(new Wn(e));var pp=false;async function mp(){if(pp)return;pp=true;let e=await nr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(_l(),dp));for(let r of e)ye.register(new t(r.id,r.name,r.source));}Or();function fp(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 XS=b("api:actions"),gp=2;async function or(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>($l(),sp));return new t(e).fetchItems()}return ye.fetchAll()}async function hp(){return ye.fetchAllWithErrors()}async function Gn(e,t){No(e);try{return await Fn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await jn(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 qS(e,t){try{let n=(await rp(`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){XS.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function yp(e,t,r){No(e);try{let n=await qS(e,r),o=fp(n),s=await Fn(`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:g,value:y}=await d.read();if(g)break;if(p+=y.byteLength,u&&p>l*gp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*gp}`);m.push(y),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 jn(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 Ht().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}}Ne();Ne();async function wp(e,t){let r=oe.resolve(t);await Vt.mkdir(r,{recursive:true});let n=oe.join(oe.dirname(r),`${randomUUID()}.zip`);try{await Vt.writeFile(n,e);let o=await ZS.Open.file(n),s=oe.normalize(r+oe.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=oe.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(oe.resolve(oe.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 Vt.unlink(n);}catch{}}}async function Ml(e){await Vt.rm(e,{recursive:true,force:true});}async function sr(){let e=hu();await Vt.mkdir(oe.dirname(e),{recursive:true});try{await Vt.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}})}Ne();F();R();var rb=b("marketplace-registry");function nb(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 bp(e){let t=wo(e);if(!le__default.existsSync(t))return null;try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return null}}function ob(e){let t=bp(e);if(t)return t;let r=nb(e),n=wo(e);return le__default.mkdirSync(oe__default.dirname(n),{recursive:true}),Ol(r,e),r}function Ol(e,t){let r=wo(t),n=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(n,r);}function sb(e){let t=e||Ue,r=zr(),n={};try{le__default.existsSync(r)&&(n=JSON.parse(le__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:Ma(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;le__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,r);}async function Ll(e,t){let r=Ma(e),n=oe__default.relative(r,wo(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){rb.debug(`Could not commit marketplace clone changes (non-fatal): ${String(o)}`);}}async function xp(e,t,r){it(e.name),sb(r);let n=_a(e.name,r);le__default.mkdirSync(oe__default.dirname(n),{recursive:true});try{le__default.lstatSync(n),le__default.rmSync(n,{recursive:!0,force:!0});}catch{}le__default.cpSync(t,n,{recursive:true,dereference:true});let o=ob(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}),Ol(o,r)),await Ll(r,`chore: register ${e.name}@${e.version}`);}async function Ul(e,t){it(e);let r=_a(e,t);try{le__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=bp(t);if(!n){await Ll(t,`chore: unregister ${e}`);return}let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Ol(n,t),await Ll(t,`chore: unregister ${e}`);}N();R();var ab=b("mcpConfigReader"),lb=500,cb=512;function ub(){return oe__default.join(Te__default.homedir(),".claude.json")}function db(){return oe__default.join(process.cwd(),".mcp.json")}function Ip(e){if(!le__default.existsSync(e))return null;try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return ab.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Bo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nl(e){if(!Bo(e))return {};let t=e.mcpServers;return Bo(t)?t:{}}function Bl(e,t){return Object.keys(e).slice(0,lb).map(n=>({name:w(n.slice(0,cb)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Pp(){let e=[],t=ub(),r=Ip(t);if(Bo(r)){let a=r,l=Nl(a);e.push(...Bl(l,"user"));let u=process.cwd();if(Bo(a.projects)){let c=a.projects[u];if(Bo(c)){let d=Nl(c);e.push(...Bl(d,"local"));}}}let n=db(),o=Ip(n),s=Nl(o);e.push(...Bl(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();var ke=b("storage");async function mb(e,t,r){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Q().interfaceType});}catch(n){ke.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function fb(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:Q().interfaceType}).catch(o=>ke.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Hl(){return oe__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function Cp(){return oe__default.join(Te__default.homedir(),".claude","plugins")}function Fo(e){let t;try{t=le__default.realpathSync(e);}catch{t=oe__default.resolve(e);}let r=oe__default.resolve(Cp()),n=oe__default.resolve(oe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+oe__default.sep),s=t.startsWith(n+oe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function kp(e="user"){return e==="local"?oe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?oe__default.join(process.cwd(),".claude","settings.json"):oe__default.join(Te__default.homedir(),".claude","settings.json")}function Pe(){let e=Hl();if(!le__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(le__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Vl(){let e=Hl();try{let t=await le__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function gb(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ap(e,t){try{le__default.mkdirSync(oe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;le__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(r,e);}catch(r){throw gb(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){Ap(Hl(),e);}function zn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function hb(e,t){let r=oe__default.join(e,".claude-plugin"),n=oe__default.join(r,"plugin.json");if(le__default.existsSync(n))try{return JSON.parse(le__default.readFileSync(n,"utf-8"))}catch{return null}let o=oe__default.join(r,"marketplace.json");if(le__default.existsSync(o))try{let s=JSON.parse(le__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function jo(e="user"){let t=kp(e);if(!le__default.existsSync(t))return {};try{return JSON.parse(le__default.readFileSync(t,"utf-8"))}catch{return {}}}function Si(e,t="user"){Ap(kp(t),e);}function yb(e,t){let{name:r,marketplace:n}=zn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>zn(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 wb(e,t){let{name:r,marketplace:n}=zn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>zn(i).name===r)[0],o?{key:o,name:r}:null}function Fl(e="user"){return jo(e).enabledPlugins??{}}function jl(e,t="user"){let r=jo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Si(r,t);}function Ko(e,t,r="user"){let n=jo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Si(n,r);}function Sb(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 me(){let e=Pe(),t=Fl(),r=Fl("project"),n=Fl("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=zn(u),p=c.map(y=>y.scope==="managed"?{...y,scope:"user"}:y);return Sb(p).map(y=>{let f=hb(y.installPath,d),v=(o[y.scope]??t)[u];return {name:d,marketplace:m,version:y.version&&y.version!=="unknown"?y.version:void 0,installedAt:y.installedAt,installPath:y.installPath,scope:y.scope,providerId:y.providerId,type:y.type,description:f?.description,author:f?.author,status:v===false?"disabled":"enabled"}})}),i=Pp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Tp(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function Ho(e,t){ke.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=Pe(),o=wb(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(m=>m.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);ke.debug(`[${i}] Resolved key: ${s}, scope: ${t}`);let u=oe__default.dirname(l.installPath),c=a.filter(m=>m.scope!==t);if(c.some(m=>oe__default.dirname(m.installPath)===u)?ke.debug(`[${i}] Directory still used by another scope, keeping: ${u}`):(Fo(l.installPath),Fo(u),ke.debug(`[${i}] Removing directory: ${u}`),le__default.rmSync(u,{recursive:!0,force:!0})),c.length===0){let{[s]:m,...p}=n.plugins;at({...n,plugins:p}),jl(s,t),await Ul(i,Tp(s));}else n.plugins[s]=c,at(n),jl(s,t);}else {ke.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Fo(c.installPath);let d=oe__default.dirname(c.installPath);Fo(d),ke.debug(`[${i}] Removing directory: ${d}`),le__default.rmSync(d,{recursive:!0,force:!0}),jl(s,c.scope);}await Ul(i,Tp(s));let{[s]:l,...u}=n.plugins;at({...n,plugins:u});}await mb(i,a[0].origin??"internal",a[0].type??"skill"),ke.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Vo(e,t,r){ke.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=Pe(),{key:s,name:i}=yb(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}`),Ko(s,t==="enabled",l),fb(i,t,u),ke.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var bb=/^\d+$/;function xb(e){let t=oe__default.join(e,".in_use"),r;try{r=le__default.readdirSync(t);}catch{return false}for(let n of r){if(!bb.test(n))continue;let o=Number(n);try{return process.kill(o,0),!0}catch{}}return false}var vb=20;function Rp(e,t=0){if(t>vb)return 0;let r=0,n;try{n=le__default.readdirSync(e,{withFileTypes:!0});}catch{return 0}for(let o of n){let s=oe__default.join(e,o.name);if(!o.isSymbolicLink()){if(o.isDirectory())r+=Rp(s,t+1);else if(o.isFile())try{r+=le__default.statSync(s).size;}catch{}}}return r}function Ib(e,t){let r=new Map;for(let[n,o]of Object.entries(e.plugins)){let{name:s,marketplace:i}=zn(n);if(i!==t)continue;let a=r.get(s)??new Set;for(let l of o)l.version&&a.add(l.version);r.set(s,a);}return r}function $p(){let e=Pe(),t=[];for(let r of wr){let n=Ib(e,r),o=oe__default.join(Cp(),"cache",r),s;try{s=le__default.readdirSync(o,{withFileTypes:!0});}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=i.name,l=oe__default.join(o,a),u=n.get(a)??new Set,c;try{c=le__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=oe__default.join(l,m);xb(p)||t.push({marketplace:r,pluginName:a,version:m,path:p,sizeBytes:Rp(p)});}}}return t}async function _p(e){let t=await sr(),r=[],n=[];try{for(let s of e)try{Fo(s.path),le__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:Q().interfaceType}).catch(s=>ke.warn(`Failed to send prune metrics: ${String(s)}`)),{removed:r,failed:n,freedBytes:o}}Ne();function Wl(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,Wl(r)]))}function Wo(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(Wl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Wl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Wo(s,o):r[n]=o;}return r}R();var Jl=b("bundleContent"),bi="${CLAUDE_PLUGIN_ROOT}/hooks/";function Eb(e){return e.split(bi).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Gl(e){return typeof e=="string"?Eb(e):Array.isArray(e)?e.map(Gl):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Gl(r)])):e}function Pb(e,t){let r=oe__default.join(e,"rules");if(!le__default.existsSync(r))return 0;let n=le__default.readdirSync(r).filter(s=>s.endsWith(".md")&&le__default.lstatSync(oe__default.join(r,s)).isFile());if(n.length===0)return 0;let o=Tn(t);le__default.mkdirSync(o,{recursive:true});for(let s of n)le__default.copyFileSync(oe__default.join(r,s),oe__default.join(o,s));return n.length}function Tb(e,t){let r=oe__default.join(e,"hooks","hooks.json");if(!le__default.existsSync(r))return 0;let n;try{n=JSON.parse(le__default.readFileSync(r,"utf-8"));}catch(g){return Jl.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(g)}`),0}let o=n.hooks;if(!o||typeof o!="object"||Array.isArray(o))return 0;let s=oe__default.join(e,"hooks"),i=Da(t),a=new Set,l=g=>{if(typeof g=="string"&&g.includes(bi)){let y=g.slice(g.indexOf(bi)+bi.length),f=/^([^"'\s]+)/.exec(y);f&&a.add(f[1]);}else Array.isArray(g)?g.forEach(l):g!==null&&typeof g=="object"&&Object.values(g).forEach(l);};l(o);let u=0;if(a.size>0){le__default.mkdirSync(i,{recursive:true});for(let g of a){let y=oe__default.join(s,g);le__default.existsSync(y)&&(le__default.copyFileSync(y,oe__default.join(i,g)),u++);}}let c=Gl(o),d=jo(t),m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Wo(m,c);return Si({...d,hooks:p},t),u}function xi(e,t){let r=Pb(e,t),n=Tb(e,t);r>0&&Jl.debug(`Copied ${r} rule file(s) to ${Tn(t)}`),n>0&&Jl.debug(`Copied ${n} hook script(s) to ${Da(t)}`);}F();R();var Cb=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,kb=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function it(e){if(!Cb.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Ab(e){if(!kb.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 Nr=b("installer");function Rb(e,t,r){let n=`${e}@${r||Ue}`,s=Pe().plugins[n];if(s&&!t)throw new qe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function $b(e,t,r){r&&await Ml(t);try{Nr.debug(`[${t}] Extracting archive...`),await wp(e,t);}catch(n){throw await Ml(t),n}}function _b(e,t,r,n,o,s="claude-code",i){let a=Pe(),l={scope:n,...n==="user"?{}:{projectPath:process.cwd()},installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],at(a),Ko(e,true,n);}async function Mb(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:Q().interfaceType});}catch(i){Nr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Lb(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:Q().interfaceType});}catch(o){Nr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Ke(e,t={}){let r=Date.now(),n=null;try{Nr.debug(`[${e}] Acquiring lock...`),n=await sr();let{pluginKey:o,alreadyInstalled:s}=Rb(e,t.force,t.source),{source:i}=t;Nr.debug(`[${e}] Fetching manifest...`);let a=await Gn(e,i);it(a.name),Ab(a.version),Nr.debug(`[${e}] Downloading archive...`);let l=await yp(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=gu(a.name,a.version,t.source);await $b(l,d,!!s&&!!t.force),await xi(d,u),_b(o,d,a.version,u,"internal",t.providerId,c),await xp(a,d,t.source);let m=Date.now()-r;Nr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await Mb(a.name,a.version,m,fi(u),"internal",c),p}catch(o){throw await Lb(e,o,"internal",t.type??"skill"),Nr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Ce();_n();R();var Db=b("commands:helpers");async function q(){let e=await te();if(!e)return I("Not authenticated. Run: flow auth login"),false;e.customUrl&&Ot(e.customUrl);try{await Nt();}catch(t){return Db.debug(`Token validation failed: ${String(t)}`),I("Session expired. Run: flow auth login"),false}return true}async function z(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Xn(e){let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim());});})}var Ob="\x1B[A",Ub="\x1B[B";function Mp(e,t){let r=t?T.cyan("\u276F"):" ",n=t?T.cyan(e.label):e.label,o=e.description?T.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function Nb(e,t){return e.map((r,n)=>Mp(r,n===t)).join(`
111
111
  `)}async function vi(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(`${w(e)}
112
- `),process.stdout.write(Ub(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
112
+ `),process.stdout.write(Nb(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
113
113
  `){l(),process.stdout.write(`
114
- `),r(t[o].value);return}if(s===Db){o=(o-1+t.length)%t.length,a(),s="";return}if(s===Ob){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${Mp(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
115
- `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}Or();var Yn=b("claudeProxy"),Ql="claude ",Lp="flow ",ql=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},qn=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";}},Nb=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Bb=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Fb={"--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}$/},jb=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Kb=/^(flow|claude)\s+auth\s+login(\s|$)/,Dp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Op(e){return Dp.test(e.trim())}function Hb(e){return Dp.exec(e.trim())?.[2]??""}async function Up(e){let t=Hb(e);Rl(t);let r=Date.now();Yn.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 ec(n)?new Yl:n}}function Vb(e){Np(e);let t=e.slice(Ql.length);if(!Nb.test(t))throw new qn(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";}},Yl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Np(e){if(!e||!/^claude /.test(e))throw new ql(e)}function Wb(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Bb.test(r))throw new qn(`Unexpected flag: ${r}`);let n=Fb[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new qn(`Flag ${r} requires a value`);if(!n.test(o))throw new qn(`Unsafe value for flag ${r}`);t++;}}}async function Le(e){Np(e);let t=e.slice(Ql.length).split(/\s+/).filter(Boolean);Wb(t);let r=Jb(t);Yn.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 Yn.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 ec(o)?new Ii:o}}function Jb(e){return e.length>=3?e[2]:e.join(" ")}function ec(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Gb(e){return e.startsWith(Lp)?Ql+e.slice(Lp.length):e}function zb(e){return jb.test(e)||Kb.test(e)}function Xb(e){let t=0;for(;t<e.length&&zb(e[t]);)t++;return e.slice(t)}var qb=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Yb(e,t){return !t||e.includes("--scope")||!qb.test(e)?e:`${e} --scope ${t}`}async function Jo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Xb(r).map(i=>Gb(i)).map(i=>Yb(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Vb(i);Yn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Le(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Le(o[i]),s.exitCode!==0)return s;return s}async function Ei(e,t,r){let n=Hn(e),o=t?.trim();if(!o&&(o=(await Xn(`Plugin "${n}" could not be installed.
116
- If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=yi(o),r?.(),Yn.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"}`);Yn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ec(s)?new Ii:s}}Or();F();Ne();R();var rx=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 Et(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:rx},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 Pt(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 fn(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 ox(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function sx(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ix(e){return typeof e=="object"&&e!==null&&e.source==="github"}function gn(e,t){let r=e.source;if(ox(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(sx(r))return {cloneUrl:r.url,subPath:"."};if(ix(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 lt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Tt=b("claude-code.adapter");function lx(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=zr();if(!le__default.existsSync(s))return r;try{let i=JSON.parse(le__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 Jp(e,t){let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(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=lx(e.catalogId,r?.source),i=t.scope??"user",a;o?a=La(s,e.name,"external"):a=join(Xr(i==="user"?"global":"project"),e.name);let l=null;try{it(e.name),l=await Et(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(le__default.existsSync(a)&&le__default.rmSync(a,{recursive:!0,force:!0}),le__default.mkdirSync(dirname(a),{recursive:!0}),le__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Vl(),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(g=>g.scope!==i),m],at(d),Ko(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Tt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Pt(l).catch(()=>{});}}async function tc(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:Q().interfaceType});}catch(o){Tt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Hp(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:Q().interfaceType});}catch(n){Tt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var cx={async install(e,t){if(e.origin===bn&&!e.installCommand&&!Kn(e.name))return Jp(e,t);if(e.origin===bn&&e.installCommand){let r=e.type??"skill",n=await Jo(e.installCommand,t.scope);return n.exitCode===0?(await tc(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Hp(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Kn(e.name)){let r=e.type??"skill",n=Vn(e.name,t.scope);Tt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Le(n);if(o.exitCode===0)return await tc(e.name,o.duration_ms,r,t.scope),{success:true};Tt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ei(e.name,t.marketplaceSource,()=>{});let s=await Le(n);return s.exitCode===0?(await tc(e.name,s.duration_ms,r,t.scope),{success:true}):(await Hp(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 Ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Tt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Ho(e,t);},getInstallPath(e,t){return ""}};function Vp(e){return {async install(t,r){if(t.origin===bn&&!t.installCommand&&!Kn(t.name))return Jp(t,r);if(!t.installCommand)try{let o=await Ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Tt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Tt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Jo(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=Pe(),o=`${t}@${Ue}`;if(n.plugins[o]){await Ho(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 ux(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function dx(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function rc(e,t,r,n){let o=await Vl(),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],at(o);}var px={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=ux(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Es(r);le__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)le__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));le__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await rc(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(s).catch(()=>{});}},async uninstall(e,t){let r=Es(t),n=lt(e);if(le__default.existsSync(r))for(let a of le__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))le__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Pe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;at({...s,plugins:l});}else at({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Es(t),`${lt(e)}.md`)}},mx={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=dx(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=Tn(r);le__default.mkdirSync(l,{recursive:!0});for(let u of a)le__default.copyFileSync(u,join(l,basename(u)));return await rc(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return Tn(t)}},fx={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!le__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(le__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=$o();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=Wo(m,u);return Js({...d,hooks:p}),await rc(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(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 fn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:cx,skill:Vp("skill"),mcp:Vp("mcp"),agent:px,hook:fx,rule:mx}};function Ti(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var hx=new Set(["gh"]),yx=Ti(hx,"use: gh copilot mcp remove <name>"),Ci=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await fn("gh",["--version"])?fn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:yx}};Ne();var wx=new Set(["opencode"]),Sx=Ti(wx,"use: opencode config remove mcp <name>");function bx(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
117
- `)}function Gp(){return {async install(e,t){try{it(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Et(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Is(t.scope??"user"),a=join(s,".opencode","plugins");if(le__default.existsSync(a)){let l=le__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/"};le__default.mkdirSync(i,{recursive:!0}),le__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);le__default.existsSync(l)&&le__default.rmSync(l,{recursive:!0,force:!0}),le__default.mkdirSync(l,{recursive:!0}),le__default.cpSync(s,l,{recursive:!0}),le__default.mkdirSync(i,{recursive:!0}),le__default.writeFileSync(join(i,`${e.name}.js`),bx(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 Pt(o).catch(()=>{});}},async uninstall(e,t){it(e);let r=Is(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);le__default.existsSync(n)&&le__default.rmSync(n,{force:true}),le__default.existsSync(o)&&le__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Is(t),`${e}.js`)}}}var ki=class{id="opencode";name="OpenCode";async isAvailable(){return fn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Sx,skill:Gp(),bundle:Gp()}};var Jt=new mi;Jt.register(new Pi);Ar()&&(Jt.register(new Ci),Jt.register(new ki));function zp({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(()=>{Jt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(f=>{f==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(f=>{if(f==="Cancel"){a(false);return}let h=l.find(v=>v.name===f);h?(d(h.id),a(false),s(true)):a(false);},[l]),g=useCallback(f=>{let h=ep(f);h?r(h,c):s(false);},[r,c]),y=useCallback(()=>{s(false);},[]);if(i){let f=[...l.map(h=>h.name),"Cancel"];return jsx(st,{itemName:`${e} \u2014 Choose provider`,actions:f,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(st,{itemName:`${e} \u2014 Choose scope`,actions:Zd,descriptions:Qd,onAction:g,onClose:y},"scope"):jsx(st,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function qp({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(g=>g.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(g=>g.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((g,y)=>{y.upArrow?a(f=>Math.max(0,f-1)):y.downArrow?a(f=>Math.min(d.length-1,f+1)):y.return?d[i]==="Confirm Install"?n():o():y.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(g=>{g==="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(g=>{let y=w(g.name??g.flowId),f=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:y}),jsxs(Text,{dimColor:true,children:["(",f,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((g,y)=>jsx(Box,{children:jsxs(Text,{bold:y===i,color:y===i?"cyan":void 0,children:[y===i?"\u203A ":" ",g]})},g))})]}):jsx(st,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function $i({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 Qp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=$i({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&&w(o),p=m?`Update to v${m}`:"Update";return jsx(st,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:f=>{f==="Uninstall"?c():f===d?i(t):f.startsWith("Update")?a?.():l();},onClose:l})}function rm({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=$i({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(st,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var eo=b("bundle:installer"),nm=/already exists/i;async function kx(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Op(t)){let r=await Up(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(nm.test(n))return;throw new Error(n)}}else {let r=await Jo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(nm.test(n))return;throw new Error(n)}}}async function Ax(e,t){try{await P(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){eo.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Rx(e,t,r){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){eo.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function om(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){eo.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function $x(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){eo.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Li(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 Ax(i,o.length);let l=[],u=0,c=o.length;for(let[p,g]of o.entries()){let y=g.name??g.flowId,f=g.type??"unknown";if(!g.type){eo.warn(`Artifact "${y}" has no type \u2014 treated as failed`),l.push({name:y,type:f,reason:"unknown artifact type"}),await om(i,y,f,"unknown artifact type"),r?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await kx(g),u++,await Rx(i,y,f),r?.({index:p+1,total:c,artifact:g,success:!0});}catch(h){let v=h instanceof Error?h.message:String(h);eo.error(`Failed to install artifact "${y}": ${v}`),l.push({name:y,type:f,reason:v}),await om(i,y,f,v),r?.({index:p+1,total:c,artifact:g,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await $x(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function lm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Li(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(am,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",w(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(am,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var be=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:me()})}));N();function cm({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 ",Dt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function um({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",g=[{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 ${Dt(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:g.map((y,f)=>{let h=f===o;return jsxs(Box,{children:[jsx(Text,{color:h?"cyan":void 0,children:h?"\u203A ":" "}),jsx(Text,{bold:h,color:y.danger?"yellow":void 0,dimColor:!h,children:y.label})]},y.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function dm(e){return e.adapter.removable!==false?4:2}F();N();function pm({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 ",w(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:w(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",w(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",w(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:w(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 ",w(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",w(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",w(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 fm({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 gm({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(O=>Math.max(0,O-1));return}$.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(pm,{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(tt/2)),p=Math.min(a.length,m+tt);p===a.length&&(m=Math.max(0,p-tt));let g=a.slice(m,p),y=m,f=a.length-p,h=s.length>0&&m<s.length,v=p>s.length,_=g.filter(C=>r.has(`${C.name}@${o}`)),D=g.filter(C=>!r.has(`${C.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:y>0?`\u2191 ${y} more above`:" "})}),h&&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(C=>jsx(fm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:h?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"]}),D.map(C=>jsx(fm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2193 ${f} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}_l();var Nx=/^https?:\/\/.+/;function Bx(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Fx(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Sm(e){let t=S(f=>f.showNotification),r=S(f=>f.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");},[]),g=useCallback(()=>{o("idle");},[]),y=useCallback(async()=>{let f=m.current,h=d.current;if(!Nx.test(f)){c("URL must start with http:// or https://");return}c(null),o("adding");let v=randomUUID(),_=new Jn(v,h,f);try{await _.fetchItems(),await nr.add({id:v,name:h,source:f}),ye.register(new Jn(v,h,f)),r(),e(),t(`Catalog "${h}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(D){let C=Bx(D)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Fx(D)?D.message:D instanceof Error?`Could not reach catalog URL: ${D.message}`:"Failed to validate catalog URL";t(C,"error"),o("add-url");}},[e,t,r]);return useInput((f,h)=>{if(h.escape){o("idle");return}if(h.return){d.current.trim().length>0&&o("add-url");return}if(h.backspace||h.delete){d.current=d.current.slice(0,-1),i(d.current);return}f&&!h.ctrl&&!h.meta&&(d.current=d.current+f,i(d.current));},{isActive:n==="add-name"}),useInput((f,h)=>{if(h.escape){o("add-name");return}if(h.return){y();return}if(h.backspace||h.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}f&&!h.ctrl&&!h.meta&&(m.current=m.current+f,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:g}}function bm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await nr.remove(o),ye.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 vm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=be(A=>A.installedItems),[o,s]=useState(()=>ye.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[g,y]=useState("main"),f=useRef(o);useEffect(()=>{f.current=o;},[o]),useEffect(()=>{g==="browse"&&!o[i-1]&&y("main");},[g,o,i]);let h=useCallback(()=>{(async()=>{let A=ye.listAdapters(),j=await nr.read(),J=new Map(j.map(Oe=>[Oe.id,Oe]));s(A.map(Oe=>({adapter:Oe,stored:J.get(Oe.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),h();},[t,h]),useEffect(()=>{if(i===0){p(null);return}let A=f.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 v=Sm(h),_=useCallback(()=>{h(),a(0),u("list"),p(null),y("main");},[h]),{handleRemove:D}=bm(_),C=useCallback(async A=>{y("removing"),await D(A);},[D]),$=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}),h();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[h,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await nr.updateField(A.stored.id,{autoUpdate:!j}),h();},[h]),U=useCallback(()=>y("browse"),[]),se=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{$(j);},...J?[()=>{O(j);},()=>{C(j.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,C]),k=useCallback(()=>y("main"),[]),V=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),re=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);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?v.startAdd():(u("detail"),d(0)));},{isActive:g==="main"&&v.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],Oe=J?dm(J)-1:0;d(ws=>Math.min(ws+1,Oe));return}j.return&&se(c);},{isActive:g==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.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:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.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(v.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:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(Oe=>Oe.marketplace===A.adapter.name).map(Oe=>`${Oe.name}@${j}`));return jsx(gm,{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,Y=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(cm,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(um,{entry:H,detailData:m,installedCount:Y,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:V,onToggleAutoUpdate:re,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 Im(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 Em(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Pm(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 Wx=new Set(ae.filter(e=>e.focus!=="list").map(e=>e.focus));function rs(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}=Xe.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 Tm({listLength:e}){let t=S(y=>y.focus),r=S(y=>y.selectedIndex),n=S(y=>y.actionMenuOpen),o=S(y=>y.setFocus),s=S(y=>y.setActionMenuOpen),i=Xe(y=>y.query),a=Xe(y=>y.setQuery),l=Xe(y=>y.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:y,setCursorPosition:f}=Xe.getState();f(y.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let y=setTimeout(()=>d(i),300);return ()=>clearTimeout(y)},[i]),useInput((y,f)=>{let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(yl(y,f,{activeTab:h}));},{isActive:t==="tabs"}),useInput((y,f)=>{if(!f.leftArrow&&!f.rightArrow)return;let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(yl("",f,{activeTab:h}));},{isActive:Wx.has(t)}),useInput((y,f)=>{let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(Im(y,f,{activeTab:h,selectedIndex:v},u.current));},{isActive:t==="list"}),useInput((y,f)=>{rs(Em(y,f));},{isActive:t==="actionMenu"}),useInput((y,f)=>{let h=Pm(y,f,Xe.getState().query),v=h.queryUpdate;if(rs(h.actions),v==="reset")l(),d("");else if(v!==null){let{query:_,cursorPosition:D,setCursorPosition:C}=Xe.getState();if("backspace"in v)D>0&&(a(_.slice(0,D-1)+_.slice(D)),C(D-1));else if("append"in v)a(_.slice(0,D)+v.append+_.slice(D)),C(D+v.append.length);else if("cursorMove"in v){let $=D+v.cursorMove;$>=0&&$<=_.length&&C($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(y=>{let{setSelectedIndex:f,selectedIndex:h}=S.getState();y===0?f(0):h>=y&&f(y-1);},[]),g=useCallback(y=>{if(!c)return u.current=y.length,y;let f=c.toLowerCase(),h=y.filter(v=>v.name.toLowerCase().includes(f)||v.description?.toLowerCase().includes(f));return u.current=h.length,h},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:g}}function km(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=nt(a=>a.justAuthenticated),o=nt(a=>a.credentials),s=nt(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 Ve(e,t,r=false){return r?true:!ac.valid(e)||!ac.valid(t)?false:ac.gt(t,e)}F();R();var lr=b("updater");async function Jx(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:Q().interfaceType});}catch(i){lr.warn(`Failed to send update metrics: ${String(i)}`);}}function Gx(e){let t=Pe();for(let r of wr){let n=`${e}@${r}`,o=t.plugins[n];if(o&&o.length>0)return {pluginKey:n,entry:o[0]}}return null}async function Ni(e,t={}){let r=Date.now(),n=null;try{lr.debug(`[${e}] Acquiring lock...`),n=await sr();let o=Gx(e);if(!o)throw lr.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);lr.debug(`[${e}] Fetching manifest...`);let d=(await Gn(e,t.source??u)).version;if(!a||!Ve(a,d,t.force))throw l&&await xi(l,i.scope),lr.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Dr(e,a??"unknown");lr.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await Ke(e,{force:!0,skipMetrics:!0,source:t.source??u}),p=Date.now()-r;return await Jx(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),lr.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){lr.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await sr();let p=Pe();throw p.plugins[s]&&(p.plugins[s][0].version=a,p.plugins[s][0].installPath=l,at(p),lr.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Or();R();var Bi=b("dispatcher");async function zx(e,t,r,n,o){let s=Hn(e);return Bi.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}...`),Bi.debug(`[${e}] Retrying install after marketplace add`),Le(t)}async function Am(e,t,r,n){let o=Vn(e,n),s=Hn(e);r?.onStatus?.(`Installing ${s}...`),Bi.debug(`[${e}] Attempting install: ${o}`);let i=await Le(o);if(i.exitCode===0)return i;Bi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return zx(e,o,a,t,r)}async function Rm(e,t,r){let n=e.type??"bundle",o=await Jt.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 $m(){let e=be(i=>i.installedItems),t=be(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Rm(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=me().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Jt.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 Vo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Ni(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var ji=b("mcp");function ns(e,t){e.silent?_e({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):I(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Mm(e,t){e.silent?ne({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(X(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&x(t.stdout));}function Xx(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 lc(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 Lm(e,t,r){if(!await q())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return ns(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}ji.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Xx(e,t,r.transport,r.scope);if(!r.force){let s=w(e),i=w(n);if(!await z(`Install external MCP "${s}"?
114
+ `),r(t[o].value);return}if(s===Ob){o=(o-1+t.length)%t.length,a(),s="";return}if(s===Ub){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${Mp(t[c],c===o)}`),c<t.length-1&&process.stdout.write(`
115
+ `);}function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",i),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",i);})}Or();var Yn=b("claudeProxy"),Ql="claude ",Lp="flow ",ql=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},qn=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";}},Bb=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Fb=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,jb={"--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}$/},Kb=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Hb=/^(flow|claude)\s+auth\s+login(\s|$)/,Dp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Op(e){return Dp.test(e.trim())}function Vb(e){return Dp.exec(e.trim())?.[2]??""}async function Up(e){let t=Vb(e);Rl(t);let r=Date.now();Yn.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 ec(n)?new Yl:n}}function Wb(e){Np(e);let t=e.slice(Ql.length);if(!Bb.test(t))throw new qn(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";}},Yl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Np(e){if(!e||!/^claude /.test(e))throw new ql(e)}function Jb(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Fb.test(r))throw new qn(`Unexpected flag: ${r}`);let n=jb[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new qn(`Flag ${r} requires a value`);if(!n.test(o))throw new qn(`Unsafe value for flag ${r}`);t++;}}}async function Le(e){Np(e);let t=e.slice(Ql.length).split(/\s+/).filter(Boolean);Jb(t);let r=Gb(t);Yn.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 Yn.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 ec(o)?new Ii:o}}function Gb(e){return e.length>=3?e[2]:e.join(" ")}function ec(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function zb(e){return e.startsWith(Lp)?Ql+e.slice(Lp.length):e}function Xb(e){return Kb.test(e)||Hb.test(e)}function qb(e){let t=0;for(;t<e.length&&Xb(e[t]);)t++;return e.slice(t)}var Yb=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Zb(e,t){return !t||e.includes("--scope")||!Yb.test(e)?e:`${e} --scope ${t}`}async function Jo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=qb(r).map(i=>zb(i)).map(i=>Zb(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Wb(i);Yn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Le(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Le(o[i]),s.exitCode!==0)return s;return s}async function Ei(e,t,r){let n=Hn(e),o=t?.trim();if(!o&&(o=(await Xn(`Plugin "${n}" could not be installed.
116
+ If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=yi(o),r?.(),Yn.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"}`);Yn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ec(s)?new Ii:s}}Or();F();Ne();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 Et(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(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 Pt(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}async function fn(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 sx(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function ix(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ax(e){return typeof e=="object"&&e!==null&&e.source==="github"}function gn(e,t){let r=e.source;if(sx(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(ix(r))return {cloneUrl:r.url,subPath:"."};if(ax(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 lt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Tt=b("claude-code.adapter");function cx(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=zr();if(!le__default.existsSync(s))return r;try{let i=JSON.parse(le__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 Gp(e,t){let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(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=cx(e.catalogId,r?.source),i=t.scope??"user",a;o?a=La(s,e.name,"external"):a=join(Xr(i==="user"?"global":"project"),e.name);let l=null;try{it(e.name),l=await Et(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(le__default.existsSync(a)&&le__default.rmSync(a,{recursive:!0,force:!0}),le__default.mkdirSync(dirname(a),{recursive:!0}),le__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Vl(),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(g=>g.scope!==i),m],at(d),Ko(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Tt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Pt(l).catch(()=>{});}}async function tc(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:Q().interfaceType});}catch(o){Tt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Hp(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:Q().interfaceType});}catch(n){Tt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Vp={async install(e,t){if(e.origin===bn&&!e.installCommand&&!Kn(e.name))return Gp(e,t);if(e.origin===bn&&e.installCommand){let r=e.type??"skill",n=await Jo(e.installCommand,t.scope);return n.exitCode===0?(await tc(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Hp(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Kn(e.name)){let r=e.type??"skill",n=Vn(e.name,t.scope);Tt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Le(n);if(o.exitCode===0)return await tc(e.name,o.duration_ms,r,t.scope),{success:true};Tt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ei(e.name,t.marketplaceSource,()=>{});let s=await Le(n);return s.exitCode===0?(await tc(e.name,s.duration_ms,r,t.scope),{success:true}):(await Hp(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 Ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Tt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Ho(e,t);},getInstallPath(e,t){return ""}};function Wp(e){return {async install(t,r){if(t.origin===bn&&!t.installCommand&&!Kn(t.name))return Gp(t,r);if(!t.installCommand)try{let o=await Ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Tt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Tt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Jo(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=Pe(),o=`${t}@${Ue}`;if(n.plugins[o]){await Ho(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 ux(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function dx(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!le__default.existsSync(t))continue;let r=le__default.readdirSync(t).filter(n=>n.endsWith(".md")&&le__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function rc(e,t,r,n){let o=await Vl(),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],at(o);}var px={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=ux(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Es(r);le__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)le__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));le__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await rc(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(s).catch(()=>{});}},async uninstall(e,t){let r=Es(t),n=lt(e);if(le__default.existsSync(r))for(let a of le__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))le__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Pe(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;at({...s,plugins:l});}else at({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Es(t),`${lt(e)}.md`)}},mx={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=dx(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=Tn(r);le__default.mkdirSync(l,{recursive:!0});for(let u of a)le__default.copyFileSync(u,join(l,basename(u)));return await rc(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return Tn(t)}},fx={async install(e,t){let r=t.scope??"user",n=e.catalogId?ye.getAdapter(e.catalogId):void 0,o=gn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{it(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!le__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(le__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=$o();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=Wo(m,u);return Js({...d,hooks:p}),await rc(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Pt(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 fn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Vp,plugin:Vp,skill:Wp("skill"),mcp:Wp("mcp"),agent:px,hook:fx,rule:mx}};function Ti(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var hx=new Set(["gh"]),yx=Ti(hx,"use: gh copilot mcp remove <name>"),Ci=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await fn("gh",["--version"])?fn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:yx}};Ne();var wx=new Set(["opencode"]),Sx=Ti(wx,"use: opencode config remove mcp <name>");function bx(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
117
+ `)}function zp(){return {async install(e,t){try{it(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ye.getAdapter(e.catalogId):void 0,n=gn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Et(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Is(t.scope??"user"),a=join(s,".opencode","plugins");if(le__default.existsSync(a)){let l=le__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/"};le__default.mkdirSync(i,{recursive:!0}),le__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);le__default.existsSync(l)&&le__default.rmSync(l,{recursive:!0,force:!0}),le__default.mkdirSync(l,{recursive:!0}),le__default.cpSync(s,l,{recursive:!0}),le__default.mkdirSync(i,{recursive:!0}),le__default.writeFileSync(join(i,`${e.name}.js`),bx(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 Pt(o).catch(()=>{});}},async uninstall(e,t){it(e);let r=Is(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);le__default.existsSync(n)&&le__default.rmSync(n,{force:true}),le__default.existsSync(o)&&le__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Is(t),`${e}.js`)}}}var ki=class{id="opencode";name="OpenCode";async isAvailable(){return fn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Sx,skill:zp(),bundle:zp()}};var Jt=new mi;Jt.register(new Pi);Ar()&&(Jt.register(new Ci),Jt.register(new ki));function Xp({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(()=>{Jt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(f=>{f==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(f=>{if(f==="Cancel"){a(false);return}let h=l.find(v=>v.name===f);h?(d(h.id),a(false),s(true)):a(false);},[l]),g=useCallback(f=>{let h=ep(f);h?r(h,c):s(false);},[r,c]),y=useCallback(()=>{s(false);},[]);if(i){let f=[...l.map(h=>h.name),"Cancel"];return jsx(st,{itemName:`${e} \u2014 Choose provider`,actions:f,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(st,{itemName:`${e} \u2014 Choose scope`,actions:Zd,descriptions:Qd,onAction:g,onClose:y},"scope"):jsx(st,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function Yp({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(g=>g.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(g=>g.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((g,y)=>{y.upArrow?a(f=>Math.max(0,f-1)):y.downArrow?a(f=>Math.min(d.length-1,f+1)):y.return?d[i]==="Confirm Install"?n():o():y.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(g=>{g==="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(g=>{let y=w(g.name??g.flowId),f=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:y}),jsxs(Text,{dimColor:true,children:["(",f,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((g,y)=>jsx(Box,{children:jsxs(Text,{bold:y===i,color:y===i?"cyan":void 0,children:[y===i?"\u203A ":" ",g]})},g))})]}):jsx(st,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function $i({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 em({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=$i({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&&w(o),p=m?`Update to v${m}`:"Update";return jsx(st,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:f=>{f==="Uninstall"?c():f===d?i(t):f.startsWith("Update")?a?.():l();},onClose:l})}function nm({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=$i({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(st,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var eo=b("bundle:installer"),om=/already exists/i;async function kx(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Op(t)){let r=await Up(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(om.test(n))return;throw new Error(n)}}else {let r=await Jo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(om.test(n))return;throw new Error(n)}}}async function Ax(e,t){try{await P(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){eo.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Rx(e,t,r){try{await P(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){eo.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){eo.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function $x(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){eo.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Li(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 Ax(i,o.length);let l=[],u=0,c=o.length;for(let[p,g]of o.entries()){let y=g.name??g.flowId,f=g.type??"unknown";if(!g.type){eo.warn(`Artifact "${y}" has no type \u2014 treated as failed`),l.push({name:y,type:f,reason:"unknown artifact type"}),await sm(i,y,f,"unknown artifact type"),r?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await kx(g),u++,await Rx(i,y,f),r?.({index:p+1,total:c,artifact:g,success:!0});}catch(h){let v=h instanceof Error?h.message:String(h);eo.error(`Failed to install artifact "${y}": ${v}`),l.push({name:y,type:f,reason:v}),await sm(i,y,f,v),r?.({index:p+1,total:c,artifact:g,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await $x(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function cm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Li(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(lm,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",w(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(lm,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var be=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:me()})}));N();function um({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 ",Dt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function dm({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",g=[{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 ${Dt(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:g.map((y,f)=>{let h=f===o;return jsxs(Box,{children:[jsx(Text,{color:h?"cyan":void 0,children:h?"\u203A ":" "}),jsx(Text,{bold:h,color:y.danger?"yellow":void 0,dimColor:!h,children:y.label})]},y.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function pm(e){return e.adapter.removable!==false?4:2}F();N();function mm({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 ",w(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:w(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",w(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",w(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:w(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 ",w(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",w(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",w(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 gm({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 hm({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(C=>r.has(`${C.name}@${o}`)),i=t.filter(C=>!r.has(`${C.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((C,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(O=>Math.max(0,O-1));return}$.downArrow&&u(O=>Math.min(a.length-1,O+1));},{isActive:c===null}),c!==null)return jsx(mm,{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(tt/2)),p=Math.min(a.length,m+tt);p===a.length&&(m=Math.max(0,p-tt));let g=a.slice(m,p),y=m,f=a.length-p,h=s.length>0&&m<s.length,v=p>s.length,_=g.filter(C=>r.has(`${C.name}@${o}`)),D=g.filter(C=>!r.has(`${C.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:y>0?`\u2191 ${y} more above`:" "})}),h&&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(C=>jsx(gm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:h?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"]}),D.map(C=>jsx(gm,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2193 ${f} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}_l();var Nx=/^https?:\/\/.+/;function Bx(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Fx(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function bm(e){let t=S(f=>f.showNotification),r=S(f=>f.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");},[]),g=useCallback(()=>{o("idle");},[]),y=useCallback(async()=>{let f=m.current,h=d.current;if(!Nx.test(f)){c("URL must start with http:// or https://");return}c(null),o("adding");let v=randomUUID(),_=new Jn(v,h,f);try{await _.fetchItems(),await nr.add({id:v,name:h,source:f}),ye.register(new Jn(v,h,f)),r(),e(),t(`Catalog "${h}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(D){let C=Bx(D)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Fx(D)?D.message:D instanceof Error?`Could not reach catalog URL: ${D.message}`:"Failed to validate catalog URL";t(C,"error"),o("add-url");}},[e,t,r]);return useInput((f,h)=>{if(h.escape){o("idle");return}if(h.return){d.current.trim().length>0&&o("add-url");return}if(h.backspace||h.delete){d.current=d.current.slice(0,-1),i(d.current);return}f&&!h.ctrl&&!h.meta&&(d.current=d.current+f,i(d.current));},{isActive:n==="add-name"}),useInput((f,h)=>{if(h.escape){o("add-name");return}if(h.return){y();return}if(h.backspace||h.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}f&&!h.ctrl&&!h.meta&&(m.current=m.current+f,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:g}}function xm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await nr.remove(o),ye.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 Im(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=be(A=>A.installedItems),[o,s]=useState(()=>ye.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[g,y]=useState("main"),f=useRef(o);useEffect(()=>{f.current=o;},[o]),useEffect(()=>{g==="browse"&&!o[i-1]&&y("main");},[g,o,i]);let h=useCallback(()=>{(async()=>{let A=ye.listAdapters(),j=await nr.read(),J=new Map(j.map(Oe=>[Oe.id,Oe]));s(A.map(Oe=>({adapter:Oe,stored:J.get(Oe.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),h();},[t,h]),useEffect(()=>{if(i===0){p(null);return}let A=f.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 v=bm(h),_=useCallback(()=>{h(),a(0),u("list"),p(null),y("main");},[h]),{handleRemove:D}=xm(_),C=useCallback(async A=>{y("removing"),await D(A);},[D]),$=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}),h();}r("Marketplace updated","success");}catch(j){r(j instanceof Error?j.message:"Update failed","error");}},[h,r]),O=useCallback(async A=>{if(!A.stored)return;let j=A.stored.autoUpdate!==false;await nr.updateField(A.stored.id,{autoUpdate:!j}),h();},[h]),U=useCallback(()=>y("browse"),[]),se=useCallback(A=>{let j=o[i-1];if(!j)return;let J=j.adapter.removable!==false;[U,()=>{$(j);},...J?[()=>{O(j);},()=>{C(j.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,C]),k=useCallback(()=>y("main"),[]),V=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),re=useCallback(()=>{let A=o[i-1];A&&O(A);},[o,i,O]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);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?v.startAdd():(u("detail"),d(0)));},{isActive:g==="main"&&v.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],Oe=J?pm(J)-1:0;d(ws=>Math.min(ws+1,Oe));return}j.return&&se(c);},{isActive:g==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.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:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.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(v.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:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let j=A.adapter.id??"default",J=new Set(n.filter(Oe=>Oe.marketplace===A.adapter.name).map(Oe=>`${Oe.name}@${j}`));return jsx(hm,{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,Y=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(um,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(dm,{entry:H,detailData:m,installedCount:Y,focusPanel:l,actionIndex:c,onBrowse:U,onUpdate:V,onToggleAutoUpdate:re,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 Em(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 Pm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Tm(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 Wx=new Set(ae.filter(e=>e.focus!=="list").map(e=>e.focus));function rs(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}=Xe.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 Cm({listLength:e}){let t=S(y=>y.focus),r=S(y=>y.selectedIndex),n=S(y=>y.actionMenuOpen),o=S(y=>y.setFocus),s=S(y=>y.setActionMenuOpen),i=Xe(y=>y.query),a=Xe(y=>y.setQuery),l=Xe(y=>y.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:y,setCursorPosition:f}=Xe.getState();f(y.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let y=setTimeout(()=>d(i),300);return ()=>clearTimeout(y)},[i]),useInput((y,f)=>{let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(yl(y,f,{activeTab:h}));},{isActive:t==="tabs"}),useInput((y,f)=>{if(!f.leftArrow&&!f.rightArrow)return;let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(yl("",f,{activeTab:h}));},{isActive:Wx.has(t)}),useInput((y,f)=>{let{activeTab:h,selectedIndex:v,actionMenuOpen:_}=S.getState();rs(Em(y,f,{activeTab:h,selectedIndex:v},u.current));},{isActive:t==="list"}),useInput((y,f)=>{rs(Pm(y,f));},{isActive:t==="actionMenu"}),useInput((y,f)=>{let h=Tm(y,f,Xe.getState().query),v=h.queryUpdate;if(rs(h.actions),v==="reset")l(),d("");else if(v!==null){let{query:_,cursorPosition:D,setCursorPosition:C}=Xe.getState();if("backspace"in v)D>0&&(a(_.slice(0,D-1)+_.slice(D)),C(D-1));else if("append"in v)a(_.slice(0,D)+v.append+_.slice(D)),C(D+v.append.length);else if("cursorMove"in v){let $=D+v.cursorMove;$>=0&&$<=_.length&&C($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(y=>{let{setSelectedIndex:f,selectedIndex:h}=S.getState();y===0?f(0):h>=y&&f(y-1);},[]),g=useCallback(y=>{if(!c)return u.current=y.length,y;let f=c.toLowerCase(),h=y.filter(v=>v.name.toLowerCase().includes(f)||v.description?.toLowerCase().includes(f));return u.current=h.length,h},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:g}}function Am(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=nt(a=>a.justAuthenticated),o=nt(a=>a.credentials),s=nt(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 Ve(e,t,r=false){return r?true:!ac.valid(e)||!ac.valid(t)?false:ac.gt(t,e)}F();R();var lr=b("updater");async function Jx(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:Q().interfaceType});}catch(i){lr.warn(`Failed to send update metrics: ${String(i)}`);}}function Gx(e){let t=Pe();for(let r of wr){let n=`${e}@${r}`,o=t.plugins[n];if(o&&o.length>0)return {pluginKey:n,entry:o[0]}}return null}async function Ni(e,t={}){let r=Date.now(),n=null;try{lr.debug(`[${e}] Acquiring lock...`),n=await sr();let o=Gx(e);if(!o)throw lr.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);lr.debug(`[${e}] Fetching manifest...`);let d=(await Gn(e,t.source??u)).version;if(!a||!Ve(a,d,t.force))throw l&&await xi(l,i.scope),lr.debug(`[${e}] Already up to date (v${a??"n/a"})`),new Dr(e,a??"unknown");lr.info(`[${e}] Updating v${a} \u2192 v${d}...`),await n(),n=null;try{let m=await Ke(e,{force:!0,skipMetrics:!0,source:t.source??u}),p=Date.now()-r;return await Jx(m.name,a,m.version,p,i.origin??"internal",i.type??"skill"),lr.debug(`[${e}] Updated successfully in ${p}ms`),{name:m.name,previousVersion:a,newVersion:m.version,path:m.path,duration_ms:p}}catch(m){lr.warn(`[${e}] Install failed, rolling back to v${a}...`),n=await sr();let p=Pe();throw p.plugins[s]&&(p.plugins[s][0].version=a,p.plugins[s][0].installPath=l,at(p),lr.info(`[${e}] Rollback completed, restored to v${a}`)),m}}finally{n&&await n();}}Or();R();var Bi=b("dispatcher");async function zx(e,t,r,n,o){let s=Hn(e);return Bi.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}...`),Bi.debug(`[${e}] Retrying install after marketplace add`),Le(t)}async function Rm(e,t,r,n){let o=Vn(e,n),s=Hn(e);r?.onStatus?.(`Installing ${s}...`),Bi.debug(`[${e}] Attempting install: ${o}`);let i=await Le(o);if(i.exitCode===0)return i;Bi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return zx(e,o,a,t,r)}async function $m(e,t,r){let n=e.type??"bundle",o=await Jt.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 _m(){let e=be(i=>i.installedItems),t=be(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await $m(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=me().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Jt.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 Vo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Ni(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var ji=b("mcp");function ns(e,t){e.silent?_e({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):I(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Lm(e,t){e.silent?ne({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(X(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&x(t.stdout));}function Xx(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 lc(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 Dm(e,t,r){if(!await q())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return ns(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}ji.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Xx(e,t,r.transport,r.scope);if(!r.force){let s=w(e),i=w(n);if(!await z(`Install external MCP "${s}"?
118
118
  This will run: ${i}
119
- [y/N] `))return ji.debug(`[${e}] Installation cancelled by user`),x("Operation cancelled."),0}let o=r.silent?void 0:aa({text:`Adding MCP "${w(e)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(ns(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&x(`stdout: ${s.stdout}`),1):(Mm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),ns(r,{name:e,action:"add",message:ee(s)}),1}}async function Dm(e,t){if(!await q())return 1;ji.debug(`[${e}] Starting MCP remove`);let r=lc(e,t.scope);if(!t.force){let o=w(e),s=w(r);if(!await z(`Remove MCP "${o}"?
119
+ [y/N] `))return ji.debug(`[${e}] Installation cancelled by user`),x("Operation cancelled."),0}let o=r.silent?void 0:aa({text:`Adding MCP "${w(e)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(ns(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&x(`stdout: ${s.stdout}`),1):(Lm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),ns(r,{name:e,action:"add",message:ee(s)}),1}}async function Om(e,t){if(!await q())return 1;ji.debug(`[${e}] Starting MCP remove`);let r=lc(e,t.scope);if(!t.force){let o=w(e),s=w(r);if(!await z(`Remove MCP "${o}"?
120
120
  This will run: ${s}
121
- [y/N] `))return ji.debug(`[${e}] Removal cancelled by user`),x("Operation cancelled."),0}let n=t.silent?void 0:aa({text:`Removing MCP "${w(e)}"...`}).start();try{let o=await Le(r);return n?.stop(),o.exitCode!==0?(ns(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&x(`stdout: ${o.stdout}`),1):(Mm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),ns(t,{name:e,action:"remove",message:ee(o)}),1}}R();function Om({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=b("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=$m(),g=async(C,$,O)=>{l(true,C),n();try{await $(),o(r.length),s(O,"success");}catch(U){let se=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${se}`),s(se,"error");}finally{l(false);}};return {handleInstall:(C,$)=>{e&&t&&(a.current=0,g(`Installing ${e.name}...`,()=>c(t,{scope:C,...$!==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:C=>{e&&g(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let $=e.status==="enabled";g($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(O){if(O instanceof Dr)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:C=>{if(C.length===0)return;let $=C.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let U=[];for(let V of C)U.push(await p(V.name).then(()=>({status:"fulfilled",value:void 0}),re=>({status:"rejected",reason:re})));let se=U.filter(V=>V.status==="fulfilled").length,k=U.map((V,re)=>V.status==="rejected"?C[re].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:C=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let $=lc(e.name,C),O=await Le($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");be.getState().loadFromDisk();},"\u2713 MCP removed");}}}Uo();R();var os=b("api:bundle"),so=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},ss=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Zx=/^[a-zA-Z0-9_-]{1,128}$/;async function Nm(e,t){if(e instanceof HTTPError){let r=e.response.status;throw os.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new so(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new ss:new Error(`Server error (${r}) \u2014 please try again later.`)}throw os.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Bm(e){if(!Zx.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);os.debug(`Fetching bundle by flowId "${e}"`);try{return await Ht().get(`v1/use-cases/${t}`).json()}catch(r){return Nm(r,e)}}async function Ki(e){let t=encodeURIComponent(e);os.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Ht().get(`v1/use-cases/by-name/${t}`).json(),os.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Nm(n,e)}if(r.length===0)throw new so(e);return r[0]}R();var Qx=b("tui:bundle-flow");function Fm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Qx.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Bm(d):Ki(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(),be.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var is=["local","project","user"],ev=new Set(["--transport","--scope","-s"]);function jm(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(ev.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function yn(e,t){return t?`${e}::${t}`:e}function cc(e){return e===Ue?ho:bn}function Km(e){return {name:w(e.name),version:e.version?w(e.version):e.version,description:e.description?w(e.description):e.description,authorName:e.author?.name?w(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??ho,flowId:e.flowId}}function uc(e,t){let r=cc(e.marketplace);return {name:w(e.name),version:e.version?w(e.version):e.version,description:e.description?w(e.description):e.description,authorName:e.author?.name?w(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 Hm(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 is.filter(r=>t.has(r)).map(r=>({scope:r,label:Lt[r].label,pathHint:Lt[r].pathHint,items:t.get(r)??[]}))}function Vm(e){let t=r=>{if(!r)return 1/0;let n=is.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Wm({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(g=>yn(g.name,g.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[t]),a=useMemo(()=>{let g=new Map(e.map(f=>[yn(f.name,f.author?.name),f])),y=new Map(e.map(f=>[f.name,f]));return t.map(f=>{let h=g.get(yn(f.name,f.author?.name))??y.get(f.name),v=h?.version,_=!!v&&!!f.version&&Ve(f.version,v);return {...f,updateAvailable:_,catalogItem:h}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(g=>{if(s.has(yn(g.name,g.author?.name)))return false;if(g.type==="mcp"){let y=g.installCommand?jm(g.installCommand)?.toLowerCase():null;if(i.has(g.name.toLowerCase())||y&&i.has(y))return false}return true}).map(g=>Km(g)):r==="updates"?a.filter(g=>g.updateAvailable).map(g=>uc(g,g.catalogItem)):a.map(g=>uc(g,g.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(g=>{let y=g.type??"bundle";if(!n.types.has(y))return false;let f=g.origin??"internal";return n.origins.has(f)}),[l,n]),c=useMemo(()=>{let{types:g}=n;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.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 g=new Map(e.map(f=>[yn(f.name,f.author?.name),f])),y=new Map(e.map(f=>[f.name,f]));return f=>f?g.get(yn(f.name,f.authorName))??y.get(f.name)??null:null},[e]),p=useMemo(()=>a.filter(g=>g.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function dc(){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 hp();if(t(d),m.length>0){let p=m.map(g=>g.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 Jm(){return {items:be(t=>t.installedItems)}}R();var sv=b("catalog");function zm(){let e=S(Z=>Z.bundleInstallFlow),t=S(Z=>Z.activeTab),r=S(Z=>Z.notification),n=S(Z=>Z.loading),o=S(Z=>Z.loadingMessage),s=S(Z=>Z.downloadProgress),i=S(Z=>Z.downloadTotal),a=S(Z=>Z.catalogError),l=S(Z=>Z.setCatalogError),u=S(Z=>Z.catalogFilters),c=Xe(Z=>Z.query),{catalog:d,isLoading:m,error:p,refetch:g}=dc(),{items:y}=Jm(),f=be(Z=>Z.loadFromDisk),{items:h,emptyMessage:v,getSelectedCatalogItem:_,outdatedCount:D}=Wm({catalog:d,installedItems:y,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:se}=Tm({listLength:h.length}),k=se(h),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:Vm(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Hm(V):[],[t,V]),K=V[O]??null,H=useMemo(()=>_(K),[_,K]),{notify:Y}=km(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:Oe,handleBatchUpdate:ws,handleMcpConfigUninstall:Gh}=Om({selectedItem:K,selectedCatalogItem:H,items:h,closeMenu:$,clampIndex:U,notify:Y}),{handleBundleInstallStart:zh,handleBundleDetailConfirm:Xh,handleBundleDetailBack:qh,handleBundleInstallComplete:Yh}=Fm({closeMenu:$,notify:Y}),Zh=useCallback(()=>ws(V),[ws,V]);return useEffect(()=>{f();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(sv.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(Un,{}),jsx(Pd,{outdatedCount:D}),t==="marketplaces"&&Ar()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(vm,{})}):jsx(Hd,{filteredItems:V,groups:re,emptyMessage:v,onBatchUpdate:Zh}),(n||m)&&jsxs(Fragment,{children:[jsx(li,{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),g();},onBack:()=>l(null)}),r&&jsx(Vd,{message:r.message,type:r.type}),C&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(lm,{bundle:e.bundle,onComplete:Yh}):jsx(qp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>zh(K.name,K.flowId),onConfirm:Xh,onClose:e?.phase==="detail"?qh:$}):jsx(zp,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(rm,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Gh,onClose:$}):jsx(Qp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:j,onToggleStatus:Z=>J(Z),onUpdate:Oe,onClose:$})),jsx(ai,{})]})}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(be.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 uv=3;function qm(){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(()=>{be.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="",g=false;for(let y=1;y<=uv;y++)try{await Ke(m.name,{onDownloadProgress:(f,h)=>{let v=Date.now();(v-l.current>100||f>=h)&&(l.current=v,o(m.name,f,h));}}),n(m.name,"success"),g=!0;break}catch(f){if(f instanceof qe){n(m.name,"success"),g=true;break}p=f instanceof Error?f.message:"Unknown error";}g||(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:Q().interfaceType}).catch(()=>{}));}let d=tn();en("summary_review"),P(E.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),be.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var as={cursorDelta:0,confirm:false,back:false};function Ym(e,t){return t.upArrow?{...as,cursorDelta:-1}:t.downArrow?{...as,cursorDelta:1}:t.escape?{...as,back:true}:t.return?{...as,confirm:true}:as}var dv={cursorDelta:0,select:false};function Zm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:dv}N();var Qm=Xw.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:w(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:w(t.description)})})]})});var wc=5;function ef({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(li,{message:"Loading Starter Kits..."});if(o)return jsx(di,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Nn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(wc/2)),i=Math.min(t.length,s+wc);i===t.length&&(s=Math.max(0,i-wc));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(Qm,{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 rf=Xw.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:[" ",w(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var xc=8;function nf(){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(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:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:w(e.name)}),jsx(Text,{dimColor:true,children:w(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(rf,{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 bv=["Retry failed","Continue anyway"];function of({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=w(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(am,{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 ",w(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function sf({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(of,{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(of,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:bv.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 af(){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),g=S(k=>k.setScreen),y=S(k=>k.setFocus),f=S(k=>k.focus),h=nt(k=>k.setJustAuthenticated),v=nt(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:D}=qm(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(y("starterKitList"),C.current||(C.current=true,en("bundle_selection"))):y(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,y]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let re=await te();re&&await Er({...re,starterKit:k.slug});}P(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:tn()}).catch(()=>{});let{successCount:V}=M.getState();P(E.CLI_ONBOARDING_COMPLETED,{duration_ms:Tr(),tools_installed_count:V}).catch(()=>{}),h(false),y("verify"),g("verify");},[h,y,g]),O=useCallback(()=>{m(),D();},[m,D]),U=useCallback(()=>{_();},[_]),se=useCallback(()=>{y("verify"),g("verify");},[y,g]);return useInput((k,V)=>{if(V.escape)Vs("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 re=tn();o(t[r]),en("kit_display"),P(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:f==="starterKitList"}),useInput((k,V)=>{let re=Ym(k,V);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await te())?.starterKit!==K.slug&&P(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=tn();en("kit_confirmation"),P(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let Y=tn();en("tool_installation"),P(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Y}).catch(()=>{}),l("installing"),D();}if(re.back){let K=M.getState().selectedStarterKit;K&&P(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:f==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let re=Zm(k,V);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?O():$());},{isActive:f==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Un,{}),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."}),!v&&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(ef,{onRetry:U}),e==="starterKitDetail"&&jsx(nf,{}),(e==="installing"||e==="summary")&&jsx(sf,{onComplete:$,onRetry:O})]}),jsx(ai,{})]})}F();var uf=null;function df(){return uf}async function qi(){let t=an().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=de.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await pf(n);(o||s)&&await bt({...r,installedVersion:o,installMethod:s});}}async function pf(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 Kt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function ao(e){let t=await Promise.all(e.map(r=>Iv(r)));return uf=t,t}async function Iv(e){let t=lf(e.versionCommand);t==="permission-denied"&&(Ev(e.versionCommand[0]),t=lf(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 Kt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ot(e.alias)){let{installedVersion:l,installMethod:u}=await pf(e);await bt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function lf(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 Ev(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=le__default.realpathSync(r),{mode:o}=le__default.statSync(n);le__default.chmodSync(n,o|73);}catch{}}function Cv(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 yf(e,t){let[r,n]=useState(()=>Cv(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(g=>g.module.alias===d?{...g,selectedStrategy:m}:g));},[]);useInput((d,m)=>{let p=i.current,g=a.current,y=m.upArrow||d==="[A",f=m.downArrow||d==="[B";if(y||f)y&&p>0?s(p-1):f&&p<g.length-1&&s(p+1);else if(d===" "){let h=g[p];h&&!h.module.required&&l(h.module.alias);}else if(m.tab){let h=g[p];if(h&&h.availableStrategies.length>1){let v=h.availableStrategies.indexOf(h.selectedStrategy??h.availableStrategies[0]),_=h.availableStrategies[(v+1)%h.availableStrategies.length];n(D=>D.map(C=>C.module.alias===h.module.alias?{...C,selectedStrategy:_}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function Sf({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}=yf(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,g)=>{g.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,g)=>{let y=g===a,f=w(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",f," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:y?"cyan":void 0,children:[y?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",f]}),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:w(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(st,{itemName:m,actions:d,onAction:c,onClose:u})]})}var _v=/^https?:\/\/.+/;function bf({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&&_v.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 Lv(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 If(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(g=>g.alias===d?{...g,...m}:g));},[]),a=useCallback(async()=>{for(let d of e){let m=Lv(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 _r(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 Ef({module:e}){let t=w(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(am,{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:w(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 ",w(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",w(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 kf({confirmedItems:e,customUrl:t}){let r=S(h=>h.setScreen),n=S(h=>h.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=If(e,t),c=o.some(h=>h.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{ln().catch(()=>{}),n("list");let h=me().some(v=>v.name===ge);r(h?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let h=setTimeout(p,1500);return ()=>clearTimeout(h)}},[i,l,c,p]),useInput((h,v)=>{v.return&&p();},{isActive:i});let g=o.filter(h=>h.pendingSetupCommand).length,y=a-g,f=[];return y>0&&f.push(jsxs(Text,{color:"green",children:[y," installed"]},"i")),g>0&&f.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),l>0&&f.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&f.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(h=>jsx(Ef,{module:h},h.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:f.reduce((h,v,_)=>(_>0&&h.push(jsx(Text,{children:" | "},`sep-${_}`)),h.push(v),h),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Rf(){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(id(p)){ln().catch(()=>{}),l("list");let y=me().some(f=>f.name===ge);u(y?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=df();if(p){c(p);return}ao(de).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let g=p.some(y=>y.module.alias==="metrics");t(g?"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(Sf,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(bf,{onConfirm:m}),e==="installation"&&jsx(kf,{confirmedItems:o,customUrl:i})]})}F();R();var Vv=b("ClaudeMdSuggestion"),Wv=[`Install ${ge}`,"Skip for now"],Jv=["Retry","Skip for now"];function Mf(){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 Ke(ge),o("installed");}catch(m){if(m instanceof qe){o("installed");return}Vv.warn(`Failed to install ${ge}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Jv:Wv;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(Un,{}),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(_f,{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(am,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ge,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ge," 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:["/",ge]})]}),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 ",ge]}),jsx(_f,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function _f({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 qv=promisify(execFile),ta="@ciandt-flow/cli";async function Lf(){let e=he;if(ac.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ta};try{let t=await fetch(`https://registry.npmjs.org/${ta}/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:ta}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ta}}}async function ra(e){try{return await qv(tr(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Yv(e){let t=ot(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Kt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await bt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Df(e){let t=await Yv(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 Of(e,t){let r=ot(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Kt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await bt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Uf(e){let r=ot(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 Nf(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...de.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([Lf(),ao(de),Promise.all(de.map(l=>Df(l)))]);if(qi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await ra(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=de.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 Of(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:Uf(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await ln(),t(l=>({...l,outcome:"done"}));}catch{await ln(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function nI({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(am,{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 oI({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 Bf(){let{outcome:e,items:t}=Nf(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=me().some(i=>i.name===ge);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(nI,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(oI,{outcome:e})})]})}Ce();_n();R();Na();var lI={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Ff=10;function jf(){let[e,t]=useState(Ua());useEffect(()=>Iu(()=>{t([...Ua()]);}),[]);let r=e.slice(-Ff);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Ff,") \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:lI[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var pI=b("app"),mI={auth:yd,starterKitSetup:af,moduleSetup:Rf,claudeMdSuggestion:Mf,verify:Bf,main:zm};function Vf(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function oi(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Wf(){P(E.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});}async function Gf(){let e=await te();if(e&&od()&&await Pr()){e.customUrl&&Ot(e.customUrl);let{clientSecret:n,...o}=e;nt.getState().setCredentials(o),Wf(),oi(e);return}if(!e){Vf();return}try{e.customUrl&&Ot(e.customUrl),await Nt();}catch(n){pI.debug(`Token validation failed: ${String(n)}`),Vf();return}Wf();let{clientSecret:t,...r}=e;nt.getState().setCredentials(r),oi(e);}function zf(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=mI[r],{pendingExit:o}=Xu(),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(jf,{}),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();Ks();N();F();R();vo();Ce();async function Mc(e,t={}){let r=Gs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return zs(r),await Er(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=b("auth");function qf(){ze.clearFallbackFile(),Ns();}var fI=3,Xf=3,Yf=` \u2139 The data collected during setup is used solely to improve
121
+ [y/N] `))return ji.debug(`[${e}] Removal cancelled by user`),x("Operation cancelled."),0}let n=t.silent?void 0:aa({text:`Removing MCP "${w(e)}"...`}).start();try{let o=await Le(r);return n?.stop(),o.exitCode!==0?(ns(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&x(`stdout: ${o.stdout}`),1):(Lm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),ns(t,{name:e,action:"remove",message:ee(o)}),1}}R();function Um({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=b("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=_m(),g=async(C,$,O)=>{l(true,C),n();try{await $(),o(r.length),s(O,"success");}catch(U){let se=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${se}`),s(se,"error");}finally{l(false);}};return {handleInstall:(C,$)=>{e&&t&&(a.current=0,g(`Installing ${e.name}...`,()=>c(t,{scope:C,...$!==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:C=>{e&&g(`Uninstalling ${e.name}...`,()=>d(e.name,C),"\u2713 Uninstalled");},handleToggleStatus:C=>{if(!e)return;let $=e.status==="enabled";g($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,C),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let C=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${C}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${C}`,"success");}catch(O){if(O instanceof Dr)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:C=>{if(C.length===0)return;let $=C.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let U=[];for(let V of C)U.push(await p(V.name).then(()=>({status:"fulfilled",value:void 0}),re=>({status:"rejected",reason:re})));let se=U.filter(V=>V.status==="fulfilled").length,k=U.map((V,re)=>V.status==="rejected"?C[re].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:C=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let $=lc(e.name,C),O=await Le($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");be.getState().loadFromDisk();},"\u2713 MCP removed");}}}Uo();R();var os=b("api:bundle"),so=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},ss=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Zx=/^[a-zA-Z0-9_-]{1,128}$/;async function Bm(e,t){if(e instanceof HTTPError){let r=e.response.status;throw os.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new so(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new ss:new Error(`Server error (${r}) \u2014 please try again later.`)}throw os.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Fm(e){if(!Zx.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);os.debug(`Fetching bundle by flowId "${e}"`);try{return await Ht().get(`v1/use-cases/${t}`).json()}catch(r){return Bm(r,e)}}async function Ki(e){let t=encodeURIComponent(e);os.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Ht().get(`v1/use-cases/by-name/${t}`).json(),os.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Bm(n,e)}if(r.length===0)throw new so(e);return r[0]}R();var Qx=b("tui:bundle-flow");function jm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Qx.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Fm(d):Ki(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(),be.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();F();var is=["local","project","user"],ev=new Set(["--transport","--scope","-s"]);function Km(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(ev.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function yn(e,t){return t?`${e}::${t}`:e}function cc(e){return e===Ue?ho:bn}function Hm(e){return {name:w(e.name),version:e.version?w(e.version):e.version,description:e.description?w(e.description):e.description,authorName:e.author?.name?w(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??ho,flowId:e.flowId}}function uc(e,t){let r=cc(e.marketplace);return {name:w(e.name),version:e.version?w(e.version):e.version,description:e.description?w(e.description):e.description,authorName:e.author?.name?w(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 Vm(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 is.filter(r=>t.has(r)).map(r=>({scope:r,label:Lt[r].label,pathHint:Lt[r].pathHint,items:t.get(r)??[]}))}function Wm(e){let t=r=>{if(!r)return 1/0;let n=is.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Jm({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(g=>yn(g.name,g.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[t]),a=useMemo(()=>{let g=new Map(e.map(f=>[yn(f.name,f.author?.name),f])),y=new Map(e.map(f=>[f.name,f]));return t.map(f=>{let h=g.get(yn(f.name,f.author?.name))??y.get(f.name),v=h?.version,_=!!v&&!!f.version&&Ve(f.version,v);return {...f,updateAvailable:_,catalogItem:h}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(g=>{if(s.has(yn(g.name,g.author?.name)))return false;if(g.type==="mcp"){let y=g.installCommand?Km(g.installCommand)?.toLowerCase():null;if(i.has(g.name.toLowerCase())||y&&i.has(y))return false}return true}).map(g=>Hm(g)):r==="updates"?a.filter(g=>g.updateAvailable).map(g=>uc(g,g.catalogItem)):a.map(g=>uc(g,g.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(g=>{let y=g.type??"bundle";if(!n.types.has(y))return false;let f=g.origin??"internal";return n.origins.has(f)}),[l,n]),c=useMemo(()=>{let{types:g}=n;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.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 g=new Map(e.map(f=>[yn(f.name,f.author?.name),f])),y=new Map(e.map(f=>[f.name,f]));return f=>f?g.get(yn(f.name,f.authorName))??y.get(f.name)??null:null},[e]),p=useMemo(()=>a.filter(g=>g.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function dc(){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 hp();if(t(d),m.length>0){let p=m.map(g=>g.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 Gm(){return {items:be(t=>t.installedItems)}}R();var sv=b("catalog");function Xm(){let e=S(Z=>Z.bundleInstallFlow),t=S(Z=>Z.activeTab),r=S(Z=>Z.notification),n=S(Z=>Z.loading),o=S(Z=>Z.loadingMessage),s=S(Z=>Z.downloadProgress),i=S(Z=>Z.downloadTotal),a=S(Z=>Z.catalogError),l=S(Z=>Z.setCatalogError),u=S(Z=>Z.catalogFilters),c=Xe(Z=>Z.query),{catalog:d,isLoading:m,error:p,refetch:g}=dc(),{items:y}=Gm(),f=be(Z=>Z.loadFromDisk),{items:h,emptyMessage:v,getSelectedCatalogItem:_,outdatedCount:D}=Jm({catalog:d,installedItems:y,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:se}=Cm({listLength:h.length}),k=se(h),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:Wm(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Vm(V):[],[t,V]),K=V[O]??null,H=useMemo(()=>_(K),[_,K]),{notify:Y}=Am(),{handleInstall:A,handleUninstall:j,handleToggleStatus:J,handleUpdate:Oe,handleBatchUpdate:ws,handleMcpConfigUninstall:zh}=Um({selectedItem:K,selectedCatalogItem:H,items:h,closeMenu:$,clampIndex:U,notify:Y}),{handleBundleInstallStart:Xh,handleBundleDetailConfirm:qh,handleBundleDetailBack:Yh,handleBundleInstallComplete:Zh}=jm({closeMenu:$,notify:Y}),Qh=useCallback(()=>ws(V),[ws,V]);return useEffect(()=>{f();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(sv.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(Un,{}),jsx(Pd,{outdatedCount:D}),t==="marketplaces"&&Ar()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Im,{})}):jsx(Hd,{filteredItems:V,groups:re,emptyMessage:v,onBatchUpdate:Qh}),(n||m)&&jsxs(Fragment,{children:[jsx(li,{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),g();},onBack:()=>l(null)}),r&&jsx(Vd,{message:r.message,type:r.type}),C&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(cm,{bundle:e.bundle,onComplete:Zh}):jsx(Yp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Xh(K.name,K.flowId),onConfirm:qh,onClose:e?.phase==="detail"?Yh:$}):jsx(Xp,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(nm,{itemName:K.name,itemScope:K.scope??"user",onUninstall:zh,onClose:$}):jsx(em,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:j,onToggleStatus:Z=>J(Z),onUpdate:Oe,onClose:$})),jsx(ai,{})]})}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(be.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 uv=3;function Ym(){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(()=>{be.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="",g=false;for(let y=1;y<=uv;y++)try{await Ke(m.name,{onDownloadProgress:(f,h)=>{let v=Date.now();(v-l.current>100||f>=h)&&(l.current=v,o(m.name,f,h));}}),n(m.name,"success"),g=!0;break}catch(f){if(f instanceof qe){n(m.name,"success"),g=true;break}p=f instanceof Error?f.message:"Unknown error";}g||(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:Q().interfaceType}).catch(()=>{}));}let d=tn();en("summary_review"),P(E.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),be.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var as={cursorDelta:0,confirm:false,back:false};function Zm(e,t){return t.upArrow?{...as,cursorDelta:-1}:t.downArrow?{...as,cursorDelta:1}:t.escape?{...as,back:true}:t.return?{...as,confirm:true}:as}var dv={cursorDelta:0,select:false};function Qm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:dv}N();var ef=qw.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:w(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:w(t.description)})})]})});var wc=5;function tf({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(li,{message:"Loading Starter Kits..."});if(o)return jsx(di,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Nn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(wc/2)),i=Math.min(t.length,s+wc);i===t.length&&(s=Math.max(0,i-wc));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(ef,{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 nf=qw.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:[" ",w(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});N();var xc=8;function of(){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(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:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:w(e.name)}),jsx(Text,{dimColor:true,children:w(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(nf,{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 bv=["Retry failed","Continue anyway"];function sf({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=w(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(lm,{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 ",w(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function af({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(sf,{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(sf,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:bv.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 lf(){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),g=S(k=>k.setScreen),y=S(k=>k.setFocus),f=S(k=>k.focus),h=nt(k=>k.setJustAuthenticated),v=nt(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:D}=Ym(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(y("starterKitList"),C.current||(C.current=true,en("bundle_selection"))):y(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,y]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let re=await te();re&&await Er({...re,starterKit:k.slug});}P(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:tn()}).catch(()=>{});let{successCount:V}=M.getState();P(E.CLI_ONBOARDING_COMPLETED,{duration_ms:Tr(),tools_installed_count:V}).catch(()=>{}),h(false),y("verify"),g("verify");},[h,y,g]),O=useCallback(()=>{m(),D();},[m,D]),U=useCallback(()=>{_();},[_]),se=useCallback(()=>{y("verify"),g("verify");},[y,g]);return useInput((k,V)=>{if(V.escape)Vs("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 re=tn();o(t[r]),en("kit_display"),P(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:f==="starterKitList"}),useInput((k,V)=>{let re=Zm(k,V);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=M.getState().selectedStarterKit;K&&(async()=>(await te())?.starterKit!==K.slug&&P(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=tn();en("kit_confirmation"),P(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let Y=tn();en("tool_installation"),P(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Y}).catch(()=>{}),l("installing"),D();}if(re.back){let K=M.getState().selectedStarterKit;K&&P(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:f==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let re=Qm(k,V);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?O():$());},{isActive:f==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Un,{}),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."}),!v&&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(tf,{onRetry:U}),e==="starterKitDetail"&&jsx(of,{}),(e==="installing"||e==="summary")&&jsx(af,{onComplete:$,onRetry:O})]}),jsx(ai,{})]})}F();var df=null;function pf(){return df}async function qi(){let t=an().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=de.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await mf(n);(o||s)&&await bt({...r,installedVersion:o,installMethod:s});}}async function mf(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 Kt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function ao(e){let t=await Promise.all(e.map(r=>Iv(r)));return df=t,t}async function Iv(e){let t=cf(e.versionCommand);t==="permission-denied"&&(Ev(e.versionCommand[0]),t=cf(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 Kt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ot(e.alias)){let{installedVersion:l,installMethod:u}=await mf(e);await bt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function cf(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 Ev(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=le__default.realpathSync(r),{mode:o}=le__default.statSync(n);le__default.chmodSync(n,o|73);}catch{}}function Cv(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 wf(e,t){let[r,n]=useState(()=>Cv(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(g=>g.module.alias===d?{...g,selectedStrategy:m}:g));},[]);useInput((d,m)=>{let p=i.current,g=a.current,y=m.upArrow||d==="[A",f=m.downArrow||d==="[B";if(y||f)y&&p>0?s(p-1):f&&p<g.length-1&&s(p+1);else if(d===" "){let h=g[p];h&&!h.module.required&&l(h.module.alias);}else if(m.tab){let h=g[p];if(h&&h.availableStrategies.length>1){let v=h.availableStrategies.indexOf(h.selectedStrategy??h.availableStrategies[0]),_=h.availableStrategies[(v+1)%h.availableStrategies.length];n(D=>D.map(C=>C.module.alias===h.module.alias?{...C,selectedStrategy:_}:C));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}N();function bf({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}=wf(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,g)=>{g.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,g)=>{let y=g===a,f=w(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",f," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:y?"cyan":void 0,children:[y?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",f]}),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:w(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(st,{itemName:m,actions:d,onAction:c,onClose:u})]})}var _v=/^https?:\/\/.+/;function xf({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&&_v.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 Lv(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 Ef(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(g=>g.alias===d?{...g,...m}:g));},[]),a=useCallback(async()=>{for(let d of e){let m=Lv(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 _r(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 Pf({module:e}){let t=w(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(lm,{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:w(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 ",w(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",w(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 Af({confirmedItems:e,customUrl:t}){let r=S(h=>h.setScreen),n=S(h=>h.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=Ef(e,t),c=o.some(h=>h.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{ln().catch(()=>{}),n("list");let h=me().some(v=>v.name===ge);r(h?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let h=setTimeout(p,1500);return ()=>clearTimeout(h)}},[i,l,c,p]),useInput((h,v)=>{v.return&&p();},{isActive:i});let g=o.filter(h=>h.pendingSetupCommand).length,y=a-g,f=[];return y>0&&f.push(jsxs(Text,{color:"green",children:[y," installed"]},"i")),g>0&&f.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),l>0&&f.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&f.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(h=>jsx(Pf,{module:h},h.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:f.reduce((h,v,_)=>(_>0&&h.push(jsx(Text,{children:" | "},`sep-${_}`)),h.push(v),h),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function $f(){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(id(p)){ln().catch(()=>{}),l("list");let y=me().some(f=>f.name===ge);u(y?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=pf();if(p){c(p);return}ao(de).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let g=p.some(y=>y.module.alias==="metrics");t(g?"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(bf,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(xf,{onConfirm:m}),e==="installation"&&jsx(Af,{confirmedItems:o,customUrl:i})]})}F();R();var Vv=b("ClaudeMdSuggestion"),Wv=[`Install ${ge}`,"Skip for now"],Jv=["Retry","Skip for now"];function Lf(){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 Ke(ge),o("installed");}catch(m){if(m instanceof qe){o("installed");return}Vv.warn(`Failed to install ${ge}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?Jv:Wv;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(Un,{}),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(Mf,{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(lm,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ge,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ge," 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:["/",ge]})]}),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 ",ge]}),jsx(Mf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Mf({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 qv=promisify(execFile),ta="@ciandt-flow/cli";async function Df(){let e=he;if(ac.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ta};try{let t=await fetch(`https://registry.npmjs.org/${ta}/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:ta}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ta}}}async function ra(e){try{return await qv(tr(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Yv(e){let t=ot(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Kt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await bt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Of(e){let t=await Yv(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 Uf(e,t){let r=ot(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Kt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await bt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Nf(e){let r=ot(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 Bf(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...de.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([Df(),ao(de),Promise.all(de.map(l=>Of(l)))]);if(qi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await ra(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=de.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 Uf(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:Nf(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await ln(),t(l=>({...l,outcome:"done"}));}catch{await ln(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}F();function nI({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(lm,{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 oI({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 Ff(){let{outcome:e,items:t}=Bf(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=me().some(i=>i.name===ge);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(nI,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(oI,{outcome:e})})]})}Ce();_n();R();Na();var lI={debug:"gray",info:"cyan",warn:"yellow",error:"red"},jf=10;function Kf(){let[e,t]=useState(Ua());useEffect(()=>Iu(()=>{t([...Ua()]);}),[]);let r=e.slice(-jf);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",jf,") \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:lI[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var pI=b("app"),mI={auth:yd,starterKitSetup:lf,moduleSetup:$f,claudeMdSuggestion:Lf,verify:Ff,main:Xm};function Wf(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function oi(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Jf(){P(E.CLI_SESSION_STARTED,{cli_version:he,os:process.platform,node_version:process.version,duration_ms:Tr(),interface:"tui"}).catch(()=>{});}async function zf(){let e=await te();if(e&&od()&&await Pr()){e.customUrl&&Ot(e.customUrl);let{clientSecret:n,...o}=e;nt.getState().setCredentials(o),Jf(),oi(e);return}if(!e){Wf();return}try{e.customUrl&&Ot(e.customUrl),await Nt();}catch(n){pI.debug(`Token validation failed: ${String(n)}`),Wf();return}Jf();let{clientSecret:t,...r}=e;nt.getState().setCredentials(r),oi(e);}function Xf(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=mI[r],{pendingExit:o}=Xu(),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(Kf,{}),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();Ks();N();F();R();vo();Ce();async function Mc(e,t={}){let r=Gs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return zs(r),await Er(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=b("auth");function Yf(){ze.clearFallbackFile(),Ns();}var fI=3,qf=3,Zf=` \u2139 The data collected during setup is used solely to improve
122
122
  Flow's internal tools and will not be shared externally.
123
123
  `;function Yt(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
124
124
  `){l(),process.stdout.write(`
125
125
  `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function gI(){let e=on();return process.stdout.write(`
126
126
  `+T.yellow(" \u26A0 ")+`${w(e)} contains invalid JSON.
127
- `),(await Yt(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Zf(e,t,r){try{await Mc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof sn))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${on()} and retry.`,{cause:n});if(!await gI())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Mc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function hI(){if((await Yt(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Yt(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(xn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${vn}. Try again.
127
+ `),(await Yt(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Qf(e,t,r){try{await Mc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof sn))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${on()} and retry.`,{cause:n});if(!await gI())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Mc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function hI(){if((await Yt(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Yt(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(xn.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${vn}. Try again.
128
128
  `));}}async function yI(){let e=(await Yt(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await Yt(T.cyan(" ? ")+"Enter your email address: ")).trim();if(In.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${En}. Try again.
129
- `));}}async function Qf(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await ni(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
129
+ `));}}async function eg(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await ni(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
130
130
  `)):o?process.stdout.write(T.yellow(` \u26A0 Unexpected error. Please contact Flow support.
131
131
  `)):n?process.stdout.write(T.yellow(`
132
132
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
133
133
  `)):process.stdout.write(T.green(` done
134
- `)),{initFailed:n}}async function eg(){for(let e=1;e<=Xf;e++)try{return await wi()}catch{if(e===Xf)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function tg(){let e=await eg();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await Yt(T.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
134
+ `)),{initFailed:n}}async function tg(){for(let e=1;e<=qf;e++)try{return await wi()}catch{if(e===qf)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function rg(){let e=await tg();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await Yt(T.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
135
135
  `+T.cyan(" ? ")+`Starter Kit:
136
136
  `),e.forEach((r,n)=>{process.stdout.write(` ${T.cyan(`${n+1})`)} ${w(r.name)}
137
137
  `);}),process.stdout.write(`
138
138
  `);;){let r=(await Yt(T.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),n=parseInt(r,10)-1;if(!isNaN(n)&&n>=0&&n<e.length)return e[n];process.stderr.write(T.yellow(` \u26A0 Invalid selection. Please try again.
139
- `));}}async function rg(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
139
+ `));}}async function ng(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
140
140
  Starter kit '${w(e.name)}' has no plugins to install.
141
141
  `)),true;process.stdout.write(`
142
142
  Installing ${e.plugins.length} plugins from '${w(e.name)}'...
@@ -144,7 +144,7 @@ This will run: ${s}
144
144
  `)):(r++,process.stdout.write(T.red(` failed
145
145
  `)));}return r===0?process.stdout.write(T.green(` \u2713 Starter kit '${w(e.name)}' selected. ${t}/${n} plugins installed successfully.
146
146
  `)):process.stdout.write(T.yellow(` \u26A0 Starter kit '${w(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
147
- `)),r===0}async function ng(){process.stdout.write(`
147
+ `)),r===0}async function og(){process.stdout.write(`
148
148
  `),process.stdout.write(T.bold(` Personalize your Claude Code
149
149
  `)),process.stdout.write(T.dim(` This plugin helps Claude understand your preferences and work style.
150
150
 
@@ -158,30 +158,30 @@ This will run: ${s}
158
158
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
159
159
  `),process.stdout.write(T.cyan.bold(` /${ge}
160
160
  `)),process.stdout.write(` Claude will guide you through the rest.
161
- `);}async function wI(e){if(qf(),process.stdout.write(`
162
- `+Yf+`
161
+ `);}async function wI(e){if(Yf(),process.stdout.write(`
162
+ `+Zf+`
163
163
  `),e.customUrl!==void 0&&!xn.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${vn}.
164
164
  `)),1;if(e.customEmail!==void 0&&!In.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${En}.
165
165
  `)),1;let t=e.jwt.trim(),r;try{r=_o(t);}catch(o){let s=w(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
166
166
  `)),1}e.customUrl&&Ot(e.customUrl),Rt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Qr(r);}catch(o){let s=w(o instanceof Error?o.message:"unknown error");return Rt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
167
- `)),1}let{initFailed:n}=await Qf(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await eg(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${w(e.starterKit)}' not found.
167
+ `)),1}let{initFailed:n}=await eg(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await tg(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${w(e.starterKit)}' not found.
168
168
  `)),process.stderr.write(` Available starter kits:
169
169
  `);for(let a of s)process.stderr.write(` - ${w(a.slug)} (${w(a.name)})
170
- `);return 1}o=i;}else o=await tg();return await Zf({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await rg(o):process.stdout.write(T.dim(`
170
+ `);return 1}o=i;}else o=await rg();return await Qf({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await ng(o):process.stdout.write(T.dim(`
171
171
  Skipped starter kit installation.
172
- `)),await ng(),Rt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
172
+ `)),await og(),Rt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
173
173
  \u2713 Setup complete. Tenant: ${w(r.tenant)}. JWT written to ${on()}.
174
174
 
175
175
  `)),n&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
176
176
  `)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=w(o instanceof Error?o.message:"unknown error");return Rt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(T.red(` \u2717 Starter kit setup failed: ${s}
177
- `)),1}}async function SI(e,t){qf(),Rt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
178
- `),process.stdout.write(Yf+`
177
+ `)),1}}async function SI(e,t){Yf(),Rt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
178
+ `),process.stdout.write(Zf+`
179
179
  `);let r=(await Yt(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Rt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
180
180
  `)),1;let n;try{n=_o(r);}catch(l){let u=w(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
181
181
  `)),1}let o=e??await hI(),s=t??await yI();o&&Ot(o),Rt.debug(`[${n.tenant}] Authenticating tenant`);try{await Qr(n);}catch(l){let u=w(l instanceof Error?l.message:"unknown error");return Rt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
182
- `)),1}let{initFailed:i}=await Qf(o,s),a=await tg();return await Zf({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await rg(a):process.stdout.write(T.dim(`
182
+ `)),1}let{initFailed:i}=await eg(o,s),a=await rg();return await Qf({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await ng(a):process.stdout.write(T.dim(`
183
183
  Skipped starter kit installation.
184
- `)),await ng(),Rt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
184
+ `)),await og(),Rt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
185
185
  \u2713 Setup complete. Tenant: ${w(n.tenant)}. JWT written to ${on()}.
186
186
 
187
187
  `)),i&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
@@ -192,50 +192,50 @@ This will run: ${s}
192
192
  `),130;throw t}}async function bI(){try{return process.stdout.write(`
193
193
  `),(await Yt(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
194
194
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
195
- `),130;throw e}}async function og(e){if(!await te())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
195
+ `),130;throw e}}async function sg(e){if(!await te())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
196
196
  `)),0;if(!e){let t=await bI();if(t!==null)return t}try{return await Du(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
197
197
  `)),0}catch{return process.stderr.write(T.red(` \u2717 Error removing credentials
198
- `)),1}}async function sg(){let e=await te();return e?await Pr()?(process.stdout.write(`
198
+ `)),1}}async function ig(){let e=await te();return e?await Pr()?(process.stdout.write(`
199
199
  `+T.bold(` Authenticated
200
200
  `)),process.stdout.write(T.dim(" Tenant: ")+w(e.tenant)+`
201
201
  `),process.stdout.write(T.dim(" Client ID: ")+w(e.clientId)+`
202
202
  `),process.stdout.write(T.dim(" Starter Kit: ")+w(e.starterKit??"not set")+`
203
203
  `),process.stdout.write(T.dim(" Config: ")+w(await Ou())+`
204
204
  `),process.stdout.write(`
205
- `),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();Ne();F();function ig(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function vI(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 ag(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 oa(e=process.env){let t=zr();if(!le__default.existsSync(t))return [];try{let r=JSON.parse(le__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>vI(n,o,e))}catch{return []}}function lg(){let e=zr(),t={fixed:[],skipped:[]};if(!le__default.existsSync(e))return t;let r;try{r=JSON.parse(le__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 wr){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`;le__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,e);}return t}async function II(e){let t=me(),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:Q().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(xr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(br(["","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 EI(e){let t=me(),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&&Ve(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(E.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(xr(o),0):o.length===0?(x("All plugins are up to date."),0):(br(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
205
+ `),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();F();Ne();F();function ag(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function vI(e,t,r=process.env){return ag(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:ag(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 lg(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 oa(e=process.env){let t=zr();if(!le__default.existsSync(t))return [];try{let r=JSON.parse(le__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>vI(n,o,e))}catch{return []}}function cg(){let e=zr(),t={fixed:[],skipped:[]};if(!le__default.existsSync(e))return t;let r;try{r=JSON.parse(le__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 wr){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`;le__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),le__default.renameSync(o,e);}return t}async function II(e){let t=me(),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:Q().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(xr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(br(["","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 EI(e){let t=me(),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&&Ve(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(E.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(xr(o),0):o.length===0?(x("All plugins are up to date."),0):(br(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
206
206
  ${o.length} plugin(s) outdated.
207
207
  `),0)}async function PI(e){let t=me();if(P(E.CLI_CATALOG_VIEWED,{interface:Q().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return x("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return xr(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(oa().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=is.indexOf(i.scope??"user"),u=is.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return br(["Name","Version","Type","Origin","Scope","Status","Auto-Update","Installed at"],s.map(i=>{let a=n.get(i.name),l=a?.type??"bundle",u=a?.origin??cc(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",Sr[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,Dt(i.installedAt??"")]})),process.stdout.write(`
208
208
  ${t.length} plugin(s) installed.
209
- `),0}async function cg(e){if(!await q())return 1;try{return e.available?await II(e):e.outdated?await EI(e):await PI(e)}catch(t){return I(t instanceof Error?t.message:"Failed to list plugins."),1}}Or();N();F();function sa(e){let t=Pe().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 Zt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function ia(e,t,r){return x(`${e} is already installed ${Zt(r)}.`),z(` Move it to ${Lt[t].actionLabel} instead? This uninstalls it from ${Zt(r)} first. [y/N] `)}N();F();R();var Se=b("manage");function la(e,t){return t?me().find(r=>r.name===e&&r.scope===t):me().find(r=>r.name===e)}function TI(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,x(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=aa({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function CI(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=w(e),a=w(Vn(e,r.scope));if(!await z(`${t}Install external plugin "${i}"?
209
+ `),0}async function ug(e){if(!await q())return 1;try{return e.available?await II(e):e.outdated?await EI(e):await PI(e)}catch(t){return I(t instanceof Error?t.message:"Failed to list plugins."),1}}Or();N();F();function sa(e){let t=Pe().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 Zt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function ia(e,t,r){return x(`${e} is already installed ${Zt(r)}.`),z(` Move it to ${Lt[t].actionLabel} instead? This uninstalls it from ${Zt(r)} first. [y/N] `)}N();F();R();var Se=b("manage");function la(e,t){return t?me().find(r=>r.name===e&&r.scope===t):me().find(r=>r.name===e)}function TI(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,x(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=aa({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function CI(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=w(e),a=w(Vn(e,r.scope));if(!await z(`${t}Install external plugin "${i}"?
210
210
  This will run: ${a}
211
- [y/N] `))return Se.debug(`[${e}] Installation cancelled by user`),r.silent||x(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=aa({text:`${t}Installing ${e}...`}).start());}let s=o?TI(t,o):void 0;try{let i=await Am(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}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?ne({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):X(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=ee(i);return r.silent?_e({status:"error",plugin:e,message:a}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function kI(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=sa(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 ${Zt(o)}. Use --force to reinstall.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):x(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${Zt(o)}. Re-run with --force to install here too.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):x(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await ia(e,s,o)?await ds(e,{force:true,scope:o.scope})!==0?(x(`${t}Could not remove ${e} from ${Zt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:aa({text:`${t}Installing ${e}...`}).start()}:(x(`${t}Skipped ${e}.`),{proceed:false})}async function AI(e,t,r){let n=r.silent?void 0:aa({text:`${t}Installing ${e}...`}).start();if(Kn(e))return CI(e,t,r,n);let o=await kI(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await Ke(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=ci(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?ne({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):X(`${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 qe)return r.silent?ne({status:"already_installed",plugin:e,message:s.message}):x(`${t}${s.message}`),{name:e,success:true};let i=ee(s);return r.silent?_e({status:"error",plugin:e,message:i}):I(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function RI(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;x(`
212
- Installation summary: ${t} succeeded, ${r} failed`);}async function $I(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 po(e,t={}){if(!await q())return 1;let r=[],n=await $I(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 AI(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?ne({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}:{}}))}):RI(r)),r.some(o=>!o.success)?1:0}async function ds(e,t){if(!await q())return 1;if(Se.debug(`[${e}] Looking up installed plugin`),!t.force){let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;let n=w(r.name),o=r.version?w(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await z(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return Se.debug(`[${e}] Uninstall cancelled by user`),x("Operation cancelled."),0}try{return Se.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Ho(e,t.scope),Se.info(`[${e}] Uninstalled successfully`),X("Plugin removed successfully"),0}catch(r){return Se.error(`[${e}] Failed to uninstall: ${ee(r)}`),I(ee(r)),1}}async function dg(e,t={}){if(!await q())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return Se.debug(`[${e}] Already enabled, skipping`),x(`${r.name} is already enabled`),0;try{return Se.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Vo(e,"enabled",t.scope),Se.info(`[${e}] Enabled successfully`),X(`${r.name} enabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to enable: ${ee(n)}`),I(ee(n)),1}}async function pg(e,t={}){if(!await q())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return Se.debug(`[${e}] Already disabled, skipping`),x(`${r.name} is already disabled`),0;try{return Se.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Vo(e,"disabled",t.scope),Se.info(`[${e}] Disabled successfully`),X(`${r.name} disabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to disable: ${ee(n)}`),I(ee(n)),1}}async function mg(e,t,r){r.silent||x(`${t}Updating ${e}...`);try{let n=await Ni(e,r);return r.silent?ne({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):X(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Dr)return r.silent?ne({status:"up_to_date",plugin:e,message:n.message}):x(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=ee(n);return r.silent?_e({status:"error",plugin:e,message:o}):I(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function _I(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;x(`
213
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function MI(e,t,r){try{let n=await Gn(e,r.source);Ve(t,n.version,r.force)?x(`Would update ${e}: v${t} \u2192 v${n.version}`):x(`${e} is already up to date (v${t})`);}catch(n){return I(ee(n)),1}return 0}function LI(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function DI(e,t,r){let n=t.get(e.name);return n?e.version&&Ve(e.version,n,r)?(x(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(x(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(x(`Skipping ${e.name}: not found in catalog`),false)}async function OI(e,t){try{let r=await or(t.source),n=LI(r),o=0;for(let s of e)DI(s,n,t.force)&&o++;o===0&&x("All plugins are up to date");}catch(r){return I(ee(r)),1}return 0}async function UI(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await mg(e[n].name,o,t);r.push(s);}return t.silent?ne({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}:{}}))}):_I(r),r.some(n=>!n.success)?1:0}async function fg(e,t={}){if(!await q())return 1;if(e){let o=la(e,t.scope);return o?t.dryRun?MI(e,o.version??"",t):(await mg(e,"",t)).success?0:1:(t.silent?_e({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):I(`Plugin "${e}" is not installed`),1)}let n=me().filter(o=>wr.includes(o.marketplace??""));return n.length===0?(t.silent?ne({status:"empty",message:"No plugins installed"}):x("No plugins installed"),0):t.dryRun?OI(n,t):UI(n,t)}function ug(e){for(let t of e)x(` ${t.pluginName}@${t.version} (${t.marketplace}) \u2014 ${Lr(t.sizeBytes)}`);}async function gg(e={}){if(!await q())return 1;let t=$p();if(t.length===0)return e.silent?ne({status:"empty",message:"No stale plugin versions to prune"}):(x("No stale plugin versions to prune \u2014 everything on disk is either the"),x("currently installed version or still in use by a running session.")),0;let r=t.reduce((o,s)=>o+s.sizeBytes,0);if(e.dryRun)return e.silent?ne({status:"dry-run",candidates:t.map(o=>({plugin:o.pluginName,version:o.version,marketplace:o.marketplace,path:o.path,size_bytes:o.sizeBytes})),total_bytes:r}):(x(`Would remove ${t.length} stale version(s), freeing ${Lr(r)}:`),ug(t)),0;if(!e.force){if(e.silent)return _e({status:"error",message:"--silent requires --force to delete without an interactive confirmation"}),1;if(x(`Found ${t.length} stale version(s), ${Lr(r)} total:`),ug(t),!await z(`Remove these ${t.length} version(s)? [y/N] `))return x("Operation cancelled."),0}let n=await _p(t);if(e.silent)ne({status:"summary",removed:n.removed.length,failed:n.failed.length,freed_bytes:n.freedBytes,details:n.failed.map(o=>({plugin:o.candidate.pluginName,version:o.candidate.version,error:o.error}))});else if(X(`Removed ${n.removed.length} stale version(s), freed ${Lr(n.freedBytes)}`),n.failed.length>0){I(`Failed to remove ${n.failed.length} version(s):`);for(let{candidate:o,error:s}of n.failed)I(` ${o.pluginName}@${o.version}: ${s}`);}return n.failed.length>0?1:0}N();R();var ps=b("cli:bundle");function NI(e){let t=w(e.name??e.flowId),r=w(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function BI(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
211
+ [y/N] `))return Se.debug(`[${e}] Installation cancelled by user`),r.silent||x(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=aa({text:`${t}Installing ${e}...`}).start());}let s=o?TI(t,o):void 0;try{let i=await Rm(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}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?ne({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):X(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=ee(i);return r.silent?_e({status:"error",plugin:e,message:a}):I(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function kI(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=sa(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 ${Zt(o)}. Use --force to reinstall.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):x(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${Zt(o)}. Re-run with --force to install here too.`;return r.silent?ne({status:"already_installed",plugin:e,message:c}):x(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await ia(e,s,o)?await ds(e,{force:true,scope:o.scope})!==0?(x(`${t}Could not remove ${e} from ${Zt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:aa({text:`${t}Installing ${e}...`}).start()}:(x(`${t}Skipped ${e}.`),{proceed:false})}async function AI(e,t,r){let n=r.silent?void 0:aa({text:`${t}Installing ${e}...`}).start();if(Kn(e))return CI(e,t,r,n);let o=await kI(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await Ke(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=ci(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?ne({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):X(`${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 qe)return r.silent?ne({status:"already_installed",plugin:e,message:s.message}):x(`${t}${s.message}`),{name:e,success:true};let i=ee(s);return r.silent?_e({status:"error",plugin:e,message:i}):I(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function RI(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;x(`
212
+ Installation summary: ${t} succeeded, ${r} failed`);}async function $I(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 po(e,t={}){if(!await q())return 1;let r=[],n=await $I(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 AI(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?ne({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}:{}}))}):RI(r)),r.some(o=>!o.success)?1:0}async function ds(e,t){if(!await q())return 1;if(Se.debug(`[${e}] Looking up installed plugin`),!t.force){let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;let n=w(r.name),o=r.version?w(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await z(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return Se.debug(`[${e}] Uninstall cancelled by user`),x("Operation cancelled."),0}try{return Se.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Ho(e,t.scope),Se.info(`[${e}] Uninstalled successfully`),X("Plugin removed successfully"),0}catch(r){return Se.error(`[${e}] Failed to uninstall: ${ee(r)}`),I(ee(r)),1}}async function pg(e,t={}){if(!await q())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return Se.debug(`[${e}] Already enabled, skipping`),x(`${r.name} is already enabled`),0;try{return Se.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Vo(e,"enabled",t.scope),Se.info(`[${e}] Enabled successfully`),X(`${r.name} enabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to enable: ${ee(n)}`),I(ee(n)),1}}async function mg(e,t={}){if(!await q())return 1;Se.debug(`[${e}] Looking up installed plugin`);let r=la(e,t.scope);if(!r)return Se.error(`[${e}] Plugin is not installed`),I(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return Se.debug(`[${e}] Already disabled, skipping`),x(`${r.name} is already disabled`),0;try{return Se.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Vo(e,"disabled",t.scope),Se.info(`[${e}] Disabled successfully`),X(`${r.name} disabled successfully`),0}catch(n){return Se.error(`[${e}] Failed to disable: ${ee(n)}`),I(ee(n)),1}}async function fg(e,t,r){r.silent||x(`${t}Updating ${e}...`);try{let n=await Ni(e,r);return r.silent?ne({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):X(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof Dr)return r.silent?ne({status:"up_to_date",plugin:e,message:n.message}):x(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=ee(n);return r.silent?_e({status:"error",plugin:e,message:o}):I(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function _I(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;x(`
213
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function MI(e,t,r){try{let n=await Gn(e,r.source);Ve(t,n.version,r.force)?x(`Would update ${e}: v${t} \u2192 v${n.version}`):x(`${e} is already up to date (v${t})`);}catch(n){return I(ee(n)),1}return 0}function LI(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function DI(e,t,r){let n=t.get(e.name);return n?e.version&&Ve(e.version,n,r)?(x(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(x(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(x(`Skipping ${e.name}: not found in catalog`),false)}async function OI(e,t){try{let r=await or(t.source),n=LI(r),o=0;for(let s of e)DI(s,n,t.force)&&o++;o===0&&x("All plugins are up to date");}catch(r){return I(ee(r)),1}return 0}async function UI(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await fg(e[n].name,o,t);r.push(s);}return t.silent?ne({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}:{}}))}):_I(r),r.some(n=>!n.success)?1:0}async function gg(e,t={}){if(!await q())return 1;if(e){let o=la(e,t.scope);return o?t.dryRun?MI(e,o.version??"",t):(await fg(e,"",t)).success?0:1:(t.silent?_e({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):I(`Plugin "${e}" is not installed`),1)}let n=me().filter(o=>wr.includes(o.marketplace??""));return n.length===0?(t.silent?ne({status:"empty",message:"No plugins installed"}):x("No plugins installed"),0):t.dryRun?OI(n,t):UI(n,t)}function dg(e){for(let t of e)x(` ${t.pluginName}@${t.version} (${t.marketplace}) \u2014 ${Lr(t.sizeBytes)}`);}async function hg(e={}){if(!await q())return 1;let t=$p();if(t.length===0)return e.silent?ne({status:"empty",message:"No stale plugin versions to prune"}):(x("No stale plugin versions to prune \u2014 everything on disk is either the"),x("currently installed version or still in use by a running session.")),0;let r=t.reduce((o,s)=>o+s.sizeBytes,0);if(e.dryRun)return e.silent?ne({status:"dry-run",candidates:t.map(o=>({plugin:o.pluginName,version:o.version,marketplace:o.marketplace,path:o.path,size_bytes:o.sizeBytes})),total_bytes:r}):(x(`Would remove ${t.length} stale version(s), freeing ${Lr(r)}:`),dg(t)),0;if(!e.force){if(e.silent)return _e({status:"error",message:"--silent requires --force to delete without an interactive confirmation"}),1;if(x(`Found ${t.length} stale version(s), ${Lr(r)} total:`),dg(t),!await z(`Remove these ${t.length} version(s)? [y/N] `))return x("Operation cancelled."),0}let n=await _p(t);if(e.silent)ne({status:"summary",removed:n.removed.length,failed:n.failed.length,freed_bytes:n.freedBytes,details:n.failed.map(o=>({plugin:o.candidate.pluginName,version:o.candidate.version,error:o.error}))});else if(X(`Removed ${n.removed.length} stale version(s), freed ${Lr(n.freedBytes)}`),n.failed.length>0){I(`Failed to remove ${n.failed.length} version(s):`);for(let{candidate:o,error:s}of n.failed)I(` ${o.pluginName}@${o.version}: ${s}`);}return n.failed.length>0?1:0}N();R();var ps=b("cli:bundle");function NI(e){let t=w(e.name??e.flowId),r=w(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function BI(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
214
214
  Bundle: ${w(e)} (${t.length} artifacts)
215
215
  `);for(let o of t)process.stdout.write(`${NI(o)}
216
216
  `);process.stdout.write(`
217
217
  ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
218
218
 
219
- `);}async function hg(e){if(!e.trim())return I("Bundle name cannot be empty."),1;if(!await q())return 1;ps.debug(`Fetching bundle "${e}"`);let r;try{r=await Ki(e);}catch(a){return a instanceof so||a instanceof ss?(I(a.message),1):(I(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(ps.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),BI(r.title,n),o.length===0)return I("No artifacts available for installation in this bundle."),1;if(!await z(`Install ${o.length} artifact(s)? [Y/n] `))return ps.debug("Installation cancelled by user"),0;ps.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Li(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=w(u.name??u.flowId),p=w(u.type??"unknown"),g=c?"\u2713":`\u2717 (${w(d??"failed")})`;a===1&&process.stdout.write(`
219
+ `);}async function yg(e){if(!e.trim())return I("Bundle name cannot be empty."),1;if(!await q())return 1;ps.debug(`Fetching bundle "${e}"`);let r;try{r=await Ki(e);}catch(a){return a instanceof so||a instanceof ss?(I(a.message),1):(I(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(ps.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),BI(r.title,n),o.length===0)return I("No artifacts available for installation in this bundle."),1;if(!await z(`Install ${o.length} artifact(s)? [Y/n] `))return ps.debug("Installation cancelled by user"),0;ps.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Li(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=w(u.name??u.flowId),p=w(u.type??"unknown"),g=c?"\u2713":`\u2717 (${w(d??"failed")})`;a===1&&process.stdout.write(`
220
220
  `),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${g}
221
221
  `),a===l&&process.stdout.write(`
222
- `);}});if(ps.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&X(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");I(`${i.failed} failed: ${w(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>w(l.name??l.flowId)).join(", ");x(`${i.skipped} unavailable: ${a}`);}return 0}Or();N();R();var yg=b("marketplace");function jI(e){return `claude plugin marketplace add ${e}`}async function wg(e,t){if(!await q())return 1;let r;try{r=yi(e);}catch(s){let i=ee(s);return t.silent?_e({status:"error",source:e,message:i}):I(i),1}yg.debug(`[marketplace] Adding marketplace source: ${r}`);let n=jI(r);if(!t.force){let s=w(r),i=w(n);if(!await z(`Add marketplace "${s}"?
222
+ `);}});if(ps.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&X(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");I(`${i.failed} failed: ${w(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>w(l.name??l.flowId)).join(", ");x(`${i.skipped} unavailable: ${a}`);}return 0}Or();N();R();var wg=b("marketplace");function jI(e){return `claude plugin marketplace add ${e}`}async function Sg(e,t){if(!await q())return 1;let r;try{r=yi(e);}catch(s){let i=ee(s);return t.silent?_e({status:"error",source:e,message:i}):I(i),1}wg.debug(`[marketplace] Adding marketplace source: ${r}`);let n=jI(r);if(!t.force){let s=w(r),i=w(n);if(!await z(`Add marketplace "${s}"?
223
223
  This will run: ${i}
224
- [y/N] `))return yg.debug("[marketplace] Operation cancelled by user"),x("Operation cancelled."),0}let o=t.silent?void 0:aa({text:`Adding marketplace "${w(r)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(t.silent?_e({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(I(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&x(`stdout: ${s.stdout}`)),1):(t.silent?ne({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(X(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&x(s.stdout)),0)}catch(s){o?.stop();let i=ee(s);return t.silent?_e({status:"error",source:r,message:i}):I(`Failed to add marketplace "${r}": ${i}`),1}}Ce();N();async function WI(){return await te()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function JI(){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 GI(){return await Pr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function zI(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function XI(){let e=oa();if(e.length!==0){process.stdout.write(`
224
+ [y/N] `))return wg.debug("[marketplace] Operation cancelled by user"),x("Operation cancelled."),0}let o=t.silent?void 0:aa({text:`Adding marketplace "${w(r)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(t.silent?_e({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(I(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&x(`stdout: ${s.stdout}`)),1):(t.silent?ne({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(X(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&x(s.stdout)),0)}catch(s){o?.stop();let i=ee(s);return t.silent?_e({status:"error",source:r,message:i}):I(`Failed to add marketplace "${r}": ${i}`),1}}Ce();N();async function WI(){return await te()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function JI(){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 GI(){return await Pr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function zI(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function XI(){let e=oa();if(e.length!==0){process.stdout.write(`
225
225
  `+T.bold(` Marketplace Auto-Update
226
226
 
227
- `));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=w(t.name).padEnd(20),o=w(ag(t));process.stdout.write(` ${r} ${n} ${T.dim(o)}
227
+ `));for(let t of e){let r=t.enabled?T.green("[ON] "):T.dim("[OFF]"),n=w(t.name).padEnd(20),o=w(lg(t));process.stdout.write(` ${r} ${n} ${T.dim(o)}
228
228
  `);}}}function qI(){process.stdout.write(`
229
229
  `+T.bold(` FlowSetup CLI \u2014 Auto-Update Fix
230
230
 
231
- `));let e=lg();for(let t of e.fixed)process.stdout.write(` ${T.green("[FIXED]")} ${w(t)} \u2014 autoUpdate: true set
231
+ `));let e=cg();for(let t of e.fixed)process.stdout.write(` ${T.green("[FIXED]")} ${w(t)} \u2014 autoUpdate: true set
232
232
  `);for(let{name:t,reason:r}of e.skipped)process.stdout.write(` ${T.dim("[SKIP] ")} ${w(t)} \u2014 ${w(r)}
233
233
  `);return process.stdout.write(`
234
234
  `),e.fixed.length===0?process.stdout.write(T.dim(` Nothing to fix \u2014 all set.
235
235
 
236
236
  `)):process.stdout.write(T.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
237
237
 
238
- `)),0}async function Sg(e={}){if(e.fix)return qI();process.stdout.write(`
238
+ `)),0}async function bg(e={}){if(e.fix)return qI();process.stdout.write(`
239
239
  `+T.bold(` FlowSetup CLI Diagnostics
240
240
 
241
241
  `));let t=[{name:"Credentials",fn:WI},{name:"Prompt Manager",fn:JI},{name:"Valid Token",fn:GI},{name:"Claude Code",fn:zI}],r=true;for(let n of t){let o=await n.fn(),s,i=T.green;o.passed?s=T.green("[OK] "):(s=T.red("[FAIL]"),i=T.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${w(o.message)}`;process.stdout.write(a+`
@@ -244,26 +244,26 @@ This will run: ${i}
244
244
 
245
245
  `)),0):(process.stdout.write(T.red(` \u2717 Some checks failed \u2014 verify your configuration
246
246
 
247
- `)),1)}Ce();Zr();F();async function bg(e){let t=await te(),r=Ut("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 cp.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}_n();js();Ce();N();R();var ZI=b("commands:usage"),ca=20,xg="EMAIL",vg="MONTHLY CONSUMPTION (USD)",Ig="STATUS";function QI(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*ca),n=ca-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function Eg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function eE(e){let t=e.toLowerCase(),r=w(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function tE(e){let t=Dt(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 rE(e){try{let t=await Rn();if(t?.email)return w(t.email);let r=$n(e);return w(r.email??"")}catch(t){return ZI.debug(`JWT email decode failed: ${String(t)}`),""}}async function Pg(e){if(!await q())return 1;let r;try{r=await Nt();}catch(f){return I(`Authentication error: ${ee(f)}`),1}let n;try{n=await bg(r);}catch(f){return I(`Failed to fetch usage data: ${ee(f)}`),1}if(e.json)return xr(n),0;let o=await rE(r)||w(n.user_id),s=Eg(n.consumed_usd),i=Eg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(xg.length,o.length+2),c=Math.max(vg.length,ca+2+l.length),d=` ${xg.padEnd(u)} ${vg.padEnd(c)} ${Ig}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(Ig.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,g=`${QI(n.percentage)} ${l.padEnd(c-ca-2)}`,y=` ${T.dim("Resets")} ${tE(n.renewal_date)}`;return process.stdout.write(`
247
+ `)),1)}Ce();Zr();F();async function xg(e){let t=await te(),r=Ut("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 cp.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}_n();js();Ce();N();R();var ZI=b("commands:usage"),ca=20,vg="EMAIL",Ig="MONTHLY CONSUMPTION (USD)",Eg="STATUS";function QI(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*ca),n=ca-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function Pg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function eE(e){let t=e.toLowerCase(),r=w(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function tE(e){let t=Dt(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 rE(e){try{let t=await Rn();if(t?.email)return w(t.email);let r=$n(e);return w(r.email??"")}catch(t){return ZI.debug(`JWT email decode failed: ${String(t)}`),""}}async function Tg(e){if(!await q())return 1;let r;try{r=await Nt();}catch(f){return I(`Authentication error: ${ee(f)}`),1}let n;try{n=await xg(r);}catch(f){return I(`Failed to fetch usage data: ${ee(f)}`),1}if(e.json)return xr(n),0;let o=await rE(r)||w(n.user_id),s=Pg(n.consumed_usd),i=Pg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(vg.length,o.length+2),c=Math.max(Ig.length,ca+2+l.length),d=` ${vg.padEnd(u)} ${Ig.padEnd(c)} ${Eg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(Eg.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,g=`${QI(n.percentage)} ${l.padEnd(c-ca-2)}`,y=` ${T.dim("Resets")} ${tE(n.renewal_date)}`;return process.stdout.write(`
248
248
  `),process.stdout.write(T.dim(d)+`
249
249
  `),process.stdout.write(T.dim(m)+`
250
250
  `),process.stdout.write(` ${p} ${g} ${eE(n.status)}
251
251
  `),process.stdout.write(y+`
252
252
  `),process.stdout.write(`
253
- `),0}var sE=["github.com","www.github.com"],iE=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,aE=/^([^@]+)@(.+)$/;function lE(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Dc(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 cE(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=Dc(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Dc(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ua(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(lE(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:")&&sE.includes(r.hostname))return cE(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(iE);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(aE);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=Dc(m));}return d}}return {type:"git",url:t}}function da(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 Tg(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 Uc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Ag(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function fE(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Oc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ms(e){try{let t=await readFile(e,"utf-8"),{data:r}=Tg(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 Rg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Oc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Uc.has(a.name)).map(a=>Rg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function fa(e,t){let r=[],n=new Set;if(t&&!fE(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Oc(o)){let i=await ms(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 Oc(u)){let c=await ms(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Rg(o);for(let a of i){let l=await ms(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function $g(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}Ne();var Dg=1,bE={retries:5,minTimeout:50};async function Og(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Sw.lock(e+".lock",{realpath:false,retries:bE});try{return await t()}finally{await r();}}function _g(){return {version:Dg,skills:{}}}async function ga(e){let t=So(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Dg?_g():n}catch{return _g()}}function xE(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Ug(e,t){let r=So(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:xE(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
254
- `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Ng(e,t,r){let n=So(r);await Og(n,async()=>{let o=await ga(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Ug(o,r);});}async function Bg(e,t){let r=So(t);await Og(r,async()=>{let n=await ga(t);e in n.skills&&(delete n.skills[e],await Ug(n,t));});}Ne();R();var Fg=b("skillInstaller");async function AE(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:Q().interfaceType});}catch(o){Fg.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function RE(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:Q().interfaceType});}catch(r){Fg.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function $E(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(Uc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function _E(e,t,r){let n=lt(e.name),o=Xr(t),s=join(o,n);if(!Ag(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 $E(e.path,s);let a=da(r)??r.url;return await Ng(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 jg(e,t){let r=ua(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 Et(r.url,r.ref),o=n;let s=await fa(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?$g(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await _E(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await AE(c.name,t.scope,u,p):await RE(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 Pt(n).catch(()=>{});}}Ne();N();R();var UE=b("skills");async function NE(e){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Q().interfaceType});}catch(t){UE.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function BE(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${w(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function FE(e){let t=ua(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return I("Invalid local path."),1;n=t.localPath;}else x(`Fetching skills from ${w(e)}...`),r=await Et(t.url,t.ref),n=r;let o=await fa(n,t.subpath);if(o.length===0)return x("No skills found in this source."),0;let i=da(t)??w(e);x(`Found ${o.length} skill(s) in ${i}:
253
+ `),0}var sE=["github.com","www.github.com"],iE=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,aE=/^([^@]+)@(.+)$/;function lE(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Dc(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 cE(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=Dc(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Dc(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ua(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(lE(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:")&&sE.includes(r.hostname))return cE(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(iE);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(aE);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=Dc(m));}return d}}return {type:"git",url:t}}function da(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 Cg(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 Uc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Rg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function fE(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Oc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ms(e){try{let t=await readFile(e,"utf-8"),{data:r}=Cg(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 $g(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Oc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Uc.has(a.name)).map(a=>$g(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function fa(e,t){let r=[],n=new Set;if(t&&!fE(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Oc(o)){let i=await ms(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 Oc(u)){let c=await ms(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await $g(o);for(let a of i){let l=await ms(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function _g(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}Ne();var Og=1,bE={retries:5,minTimeout:50};async function Ug(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bw.lock(e+".lock",{realpath:false,retries:bE});try{return await t()}finally{await r();}}function Mg(){return {version:Og,skills:{}}}async function ga(e){let t=So(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Og?Mg():n}catch{return Mg()}}function xE(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Ng(e,t){let r=So(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:xE(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
254
+ `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Bg(e,t,r){let n=So(r);await Ug(n,async()=>{let o=await ga(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Ng(o,r);});}async function Fg(e,t){let r=So(t);await Ug(r,async()=>{let n=await ga(t);e in n.skills&&(delete n.skills[e],await Ng(n,t));});}Ne();R();var jg=b("skillInstaller");async function AE(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:Q().interfaceType});}catch(o){jg.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function RE(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:Q().interfaceType});}catch(r){jg.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function $E(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(Uc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function _E(e,t,r){let n=lt(e.name),o=Xr(t),s=join(o,n);if(!Rg(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await $E(e.path,s);let a=da(r)??r.url;return await Bg(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 Kg(e,t){let r=ua(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 Et(r.url,r.ref),o=n;let s=await fa(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?_g(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await _E(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await AE(c.name,t.scope,u,p):await RE(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 Pt(n).catch(()=>{});}}Ne();N();R();var UE=b("skills");async function NE(e){try{await P(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Q().interfaceType});}catch(t){UE.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function BE(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${w(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function FE(e){let t=ua(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return I("Invalid local path."),1;n=t.localPath;}else x(`Fetching skills from ${w(e)}...`),r=await Et(t.url,t.ref),n=r;let o=await fa(n,t.subpath);if(o.length===0)return x("No skills found in this source."),0;let i=da(t)??w(e);x(`Found ${o.length} skill(s) in ${i}:
255
255
  `);for(let a of o){let l=w(a.name),u=w(a.description);process.stdout.write(` ${T.bold(l)} ${T.dim(u)}
256
256
  `);}return process.stdout.write(`
257
257
  `),0}catch(n){return n instanceof Br?I(n.message):I(n instanceof Error?n.message:String(n)),1}finally{r&&await Pt(r).catch(()=>{});}}function jE(e){for(let r of e.results){let n=w(r.skill);if(r.success){let o=relative(process.cwd(),r.path);X(`${n} installed ${T.dim(`\u2192 ${o}/`)}`);}else I(`${n}: ${w(r.error??"unknown error")}`);}process.stdout.write(`
258
- `);let t=e.source;e.installed>0&&x(`Installed ${e.installed} of ${e.discovered} skill(s) from ${w(t)}`),e.failed>0&&I(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?x("No skills found in this source."):e.results.length===0&&e.discovered>0&&x(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Hg(e,t){if(t.list)return FE(e);let r=t.global?"global":"project";try{let n=await jg(e,{scope:r,skillFilter:t.skill,yes:t.yes});return jE(n),n.failed>0?1:0}catch(n){return n instanceof Br?I(n.message):I(n instanceof Error?n.message:String(n)),1}}async function Vg(e){let t=Xr(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 ms(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 Wg(e){let t=e.global?"global":"project",r=await Vg(t),n=await ga(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[lt(i.name)]?.source}));return xr(s),0}if(r.length===0)return x(`No skills installed (${t==="global"?"global":"project"} scope).`),0;x(`${t==="global"?"Global":"Project"} skills (${r.length}):
258
+ `);let t=e.source;e.installed>0&&x(`Installed ${e.installed} of ${e.discovered} skill(s) from ${w(t)}`),e.failed>0&&I(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?x("No skills found in this source."):e.results.length===0&&e.discovered>0&&x(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Vg(e,t){if(t.list)return FE(e);let r=t.global?"global":"project";try{let n=await Kg(e,{scope:r,skillFilter:t.skill,yes:t.yes});return jE(n),n.failed>0?1:0}catch(n){return n instanceof Br?I(n.message):I(n instanceof Error?n.message:String(n)),1}}async function Wg(e){let t=Xr(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 ms(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 Jg(e){let t=e.global?"global":"project",r=await Wg(t),n=await ga(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[lt(i.name)]?.source}));return xr(s),0}if(r.length===0)return x(`No skills installed (${t==="global"?"global":"project"} scope).`),0;x(`${t==="global"?"Global":"Project"} skills (${r.length}):
259
259
  `);for(let s of r){let i=n.skills[lt(s.name)]?.source,a=w(s.name),l=w(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?T.dim(` (${i})`):"";process.stdout.write(` ${T.bold(a)}${c}
260
260
  `),process.stdout.write(` ${T.dim(u)}
261
261
 
262
- `);}return 0}async function Jg(e,t){let r=t.global?"global":"project";if(!e){let i=await Vg(r);if(i.length===0)return x("No skills installed."),0;x("Installed skills:");for(let a of i)process.stdout.write(` - ${w(a.name)}
262
+ `);}return 0}async function Gg(e,t){let r=t.global?"global":"project";if(!e){let i=await Wg(r);if(i.length===0)return x("No skills installed."),0;x("Installed skills:");for(let a of i)process.stdout.write(` - ${w(a.name)}
263
263
  `);return process.stdout.write(`
264
- `),x("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=Xr(r),s=join(o,n);try{await stat(s);}catch{return I(`Skill "${w(e)}" is not installed.`),1}if(!t.force&&!await BE(`Remove skill "${w(n)}"?`))return x("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Bg(n,r),await NE(n),X(`Skill "${w(n)}" removed.`),0}catch(i){return I(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();F();var ha=b("transfer"),Bc=1;function KE(e){return e.marketplace&&e.marketplace!==Ue?`${e.name}@${e.marketplace}`:e.name}function HE(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&x(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),x(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Xg(e){let t=oe__default.resolve(e.output);try{let r=me(),n={version:Bc,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 le__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),X(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=ee(r);return ha.error(`Export failed: ${n}`),I(`Failed to export plugins: ${n}`),1}}async function qg(e,t={}){if(!await q())return 1;let r;try{let a=le__default.readFileSync(oe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return I(`Failed to read import file "${e}": ${ee(a)}`),1}if(r.version!==Bc)return I(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Bc}`),1;if(!Array.isArray(r.plugins))return I('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return x("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}]`;ha.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(ha.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&x(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(me().map(l=>l.name));HE(n,a);}if(t.dryRun)return x("Dry-run mode: no plugins were installed"),0;if(n.length===0){x(`
264
+ `),x("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=Xr(r),s=join(o,n);try{await stat(s);}catch{return I(`Skill "${w(e)}" is not installed.`),1}if(!t.force&&!await BE(`Remove skill "${w(n)}"?`))return x("Cancelled."),0;try{return await rm(s,{recursive:!0,force:!0}),await Fg(n,r),await NE(n),X(`Skill "${w(n)}" removed.`),0}catch(i){return I(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();F();var ha=b("transfer"),Bc=1;function KE(e){return e.marketplace&&e.marketplace!==Ue?`${e.name}@${e.marketplace}`:e.name}function HE(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&x(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),x(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function qg(e){let t=oe__default.resolve(e.output);try{let r=me(),n={version:Bc,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 le__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),X(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=ee(r);return ha.error(`Export failed: ${n}`),I(`Failed to export plugins: ${n}`),1}}async function Yg(e,t={}){if(!await q())return 1;let r;try{let a=le__default.readFileSync(oe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return I(`Failed to read import file "${e}": ${ee(a)}`),1}if(r.version!==Bc)return I(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Bc}`),1;if(!Array.isArray(r.plugins))return I('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return x("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}]`;ha.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(ha.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&x(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(me().map(l=>l.name));HE(n,a);}if(t.dryRun)return x("Dry-run mode: no plugins were installed"),0;if(n.length===0){x(`
265
265
  Import summary: 0 installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}x(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=KE(a);ha.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await po([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}x(`
266
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function L(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var WE=b("moduleProxy");function JE(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Yg(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=>{WE.warn(`Failed to emit proxy executed event: ${String(s)}`);}),L(o);}async function Qg(e,t){let r=de.find(o=>o.alias===e);if(!r){I(`Unknown module alias: '${e}'`),L(1);return}if(!await Ft(r.binaryName)){I(`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(()=>{}),L(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Kt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){I(`No supported installation method available for '${e}' on this platform.`),L(1);return}if(await JE("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 _r(r,"inline",s);if(!a.success){I(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),L(1);return}await Yg(r,t);}else x(`To install manually, run: flow modules install ${e}`),await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),L(1);return}await Yg(r,t);}N();var qE=promisify(execFile);async function YE(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await qE(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/${he}`,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 ZE(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ve(t,r)?"outdated":"installed"}async function Fc(){let e=await Promise.all(de.map(async t=>{let[r,n]=await Promise.all([Ft(t.binaryName),YE(t)]),s=ot(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=ZE(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return br(["Name","Alias","Version","Status","Platform"],e),0}async function rh(e){let t=de.find(i=>i.alias===e);if(!t)return I(`Unknown module alias: '${e}'`),1;let[r]=await ao([t]);if(r.alreadyInstalled){let i=ot(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return x(`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"?I(`Module ${t.name} is not supported on ${process.platform}.${a}`):I(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=aa({text:`Installing ${t.name}...`}).start(),s;try{s=await _r(t,"on_demand",n);}finally{o.stop();}return s.success?(X(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(I(s.error?.message??"Installation failed"),1)}async function eh(e,t){let r=aa({text:`Updating ${e.name}...`}).start(),n;try{n=await ti(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 nh(e){if(e!==null){let n=de.find(i=>i.alias===e);if(!n)return I(`Unknown module alias: '${e}'`),1;let o=ot(n.alias);return o?.installMethod?await eh(n,o.installedVersion??"unknown")==="error"?1:0:(I(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=an().filter(n=>n.installMethod!==null);if(t.length===0)return x("No installed modules to update."),0;let r=0;for(let n of t){let o=de.find(i=>i.alias===n.alias);if(!o)continue;await eh(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var fs=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
266
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)I(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function L(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var WE=b("moduleProxy");function JE(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Xl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Zg(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=>{WE.warn(`Failed to emit proxy executed event: ${String(s)}`);}),L(o);}async function eh(e,t){let r=de.find(o=>o.alias===e);if(!r){I(`Unknown module alias: '${e}'`),L(1);return}if(!await Ft(r.binaryName)){I(`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(()=>{}),L(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Kt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){I(`No supported installation method available for '${e}' on this platform.`),L(1);return}if(await JE("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 _r(r,"inline",s);if(!a.success){I(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),L(1);return}await Zg(r,t);}else x(`To install manually, run: flow modules install ${e}`),await P(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),L(1);return}await Zg(r,t);}N();var qE=promisify(execFile);async function YE(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await qE(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/${he}`,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 ZE(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ve(t,r)?"outdated":"installed"}async function Fc(){let e=await Promise.all(de.map(async t=>{let[r,n]=await Promise.all([Ft(t.binaryName),YE(t)]),s=ot(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=ZE(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return br(["Name","Alias","Version","Status","Platform"],e),0}async function nh(e){let t=de.find(i=>i.alias===e);if(!t)return I(`Unknown module alias: '${e}'`),1;let[r]=await ao([t]);if(r.alreadyInstalled){let i=ot(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return x(`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"?I(`Module ${t.name} is not supported on ${process.platform}.${a}`):I(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=aa({text:`Installing ${t.name}...`}).start(),s;try{s=await _r(t,"on_demand",n);}finally{o.stop();}return s.success?(X(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(I(s.error?.message??"Installation failed"),1)}async function th(e,t){let r=aa({text:`Updating ${e.name}...`}).start(),n;try{n=await ti(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 oh(e){if(e!==null){let n=de.find(i=>i.alias===e);if(!n)return I(`Unknown module alias: '${e}'`),1;let o=ot(n.alias);return o?.installMethod?await th(n,o.installedVersion??"unknown")==="error"?1:0:(I(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=an().filter(n=>n.installMethod!==null);if(t.length===0)return x("No installed modules to update."),0;let r=0;for(let n of t){let o=de.find(i=>i.alias===n.alias);if(!o)continue;await th(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var fs=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
267
267
  title: "0-current-state \u2014 Index"
268
268
  type: index
269
269
  domain: platform
@@ -554,32 +554,32 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
554
554
  **6. Source code never in monitored folders.**
555
555
  If you create a folder with app or script source code, keep it out of the 5 numbered folders
556
556
  entirely (e.g. \`prototypes/\`).
557
- `},{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 tP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Jc(){return {new:0,unchanged:0,divergent:0,declined:0}}async function sh(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??zc,i=e.confirmCreate??nP,a=[],l=Jc(),u=fs.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"))):x(`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 fs){if(m.path===Wc&&!c)continue;let p=join(t,m.path),g=await Gc({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:y=>s(y)});a.push({path:m.path,status:g.status}),l[g.status]++,g.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 Gc(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?tP(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(rP(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function rP(e){x(`${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 zc(e){return z(` Overwrite ${e} with the updated template? [y/N] `)}async function nP(e){return z(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}function aP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function ih(e,t=e,r=[]){for(let n of readdirSync(e).sort()){let o=join(e,n),s=statSync(o);s.isDirectory()?ih(o,t,r):s.isFile()&&r.push(relative(t,o).split("\\").join("/"));}return r}function ah(e,t){let r=readFileSync(t,"utf8");return {path:e,sha256:aP(r),content:r}}function ya(){return process.env.FLOW_HARNESS_PATH}function lh(e){let t=join(e,"docs","catalog");return ih(t).map(r=>ah(`docs/catalog/${r}`,join(t,r)))}function wa(e){let t=join(e,"plugins"),r=readdirSync(t).filter(o=>statSync(join(t,o)).isDirectory()).sort(),n={};for(let o of r){let s=join(t,o,"docs"),i;try{i=readdirSync(s).filter(a=>a.endsWith(".md")&&statSync(join(s,a)).isFile());}catch{continue}i.length!==0&&(n[o]=i.sort().map(a=>ah(`docs/playbooks/${a}`,join(s,a))));}return n}var Sa=class extends Error{constructor(t){super(`docs-content requires a local flow-harness checkout: ${t}. Set FLOW_HARNESS_PATH to the path of a cit-flow/flow-harness clone, or run "flow setup workspace" first if this project is part of a workspace that declares it.`),this.name="DocsContentSourceUnavailableError";}};function pP(e,t){let r=new Set,n=[];for(let o of e){let s=t[o];if(s)for(let i of s)r.has(i.path)||(r.add(i.path),n.push(i));}return n}function mP(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function fP(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function gP(e,t){if(t==="all")return e;let r=new Map,n=[];for(let s of e){if(!s.path.endsWith(".md")){n.push(s);continue}let i=mP(s.path),a=fP(s.path),l=r.get(i);l||(l=new Map,r.set(i,l)),l.set(a,s);}let o=[];for(let[s,i]of r){let a=i.get(t)??i.get("pt")??i.get("en")??i.get("es");o.push({...a,path:s});}return [...n,...o]}async function ch(e){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??zc,i=ya();if(!i)throw new Sa("FLOW_HARNESS_PATH is not set");let a,l;try{a=lh(i),l=wa(i);}catch(f){throw new Sa(`could not read docs from "${i}" (${f instanceof Error?f.message:String(f)})`)}let u=e.docsLang??"all",c=e.installedBundles.length===0,d=c?[]:pP(e.installedBundles,l),m=gP([...a,...d],u),p=[],g=Jc();for(let f of m){let h=join(t,f.path),v=await Gc({dstPath:h,template:f,force:n,isInteractive:o,confirmOverwrite:_=>s(_)});p.push({path:f.path,status:v.status}),g[v.status]++,v.write&&!r&&(mkdirSync(dirname(h),{recursive:true}),writeFileSync(h,f.content,"utf8"));}let y=g.divergent>0||g.declined>0;return {files:p,counts:g,hasUnresolved:y,skippedPlaybooks:c}}function uh(e){let t=Pe().plugins,r=process.cwd(),n=new Set;for(let[o,s]of Object.entries(t)){let i=o.split("@")[0];if(!i||!e.has(i))continue;s.some(l=>l.scope==="user"||l.projectPath===r)&&n.add(i);}return [...n].sort()}N();R();Ce();Zr();R();var Yc=b("lib:otelMetrics"),yP="flow-plugins-cli",wP="1.0.0",SP=5e3;function bP(){return Ut("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function xP(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 vP(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:yP,version:wP},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>xP(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Zc(e,t={}){try{let[r,n]=await Promise.all([Rn(),te()]),o=r?.email,s=n?.tenant;if(!o||!s){Yc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=vP(e,t);await cp.post(bP(),{json:i,timeout:SP,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Yc.debug(`OTel metric sent: ${e}`);}catch(r){Yc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Qc=b("cli:init"),PP={new:{label:"new",color:T.green},unchanged:{label:"unchanged",color:T.dim},divergent:{label:"kept (differs from template)",color:T.yellow},declined:{label:"pending (declined)",color:T.yellow}};function TP(e){process.stdout.write(`
557
+ `},{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 tP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Jc(){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??zc,i=e.confirmCreate??nP,a=[],l=Jc(),u=fs.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"))):x(`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 fs){if(m.path===Wc&&!c)continue;let p=join(t,m.path),g=await Gc({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:y=>s(y)});a.push({path:m.path,status:g.status}),l[g.status]++,g.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 Gc(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?tP(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(rP(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function rP(e){x(`${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 zc(e){return z(` Overwrite ${e} with the updated template? [y/N] `)}async function nP(e){return z(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}function aP(e){return createHash("sha256").update(e,"utf8").digest("hex")}function ah(e,t=e,r=[]){for(let n of readdirSync(e).sort()){let o=join(e,n),s=statSync(o);s.isDirectory()?ah(o,t,r):s.isFile()&&r.push(relative(t,o).split("\\").join("/"));}return r}function lh(e,t){let r=readFileSync(t,"utf8");return {path:e,sha256:aP(r),content:r}}function ya(){return process.env.FLOW_HARNESS_PATH}function ch(e){let t=join(e,"docs","catalog");return ah(t).map(r=>lh(`docs/catalog/${r}`,join(t,r)))}function wa(e){let t=join(e,"plugins"),r=readdirSync(t).filter(o=>statSync(join(t,o)).isDirectory()).sort(),n={};for(let o of r){let s=join(t,o,"docs"),i;try{i=readdirSync(s).filter(a=>a.endsWith(".md")&&statSync(join(s,a)).isFile());}catch{continue}i.length!==0&&(n[o]=i.sort().map(a=>lh(`docs/playbooks/${a}`,join(s,a))));}return n}var Sa=class extends Error{constructor(t){super(`docs-content requires a local flow-harness checkout: ${t}. Set FLOW_HARNESS_PATH to the path of a cit-flow/flow-harness clone, or run "flow setup workspace" first if this project is part of a workspace that declares it.`),this.name="DocsContentSourceUnavailableError";}};function pP(e,t){let r=new Set,n=[];for(let o of e){let s=t[o];if(s)for(let i of s)r.has(i.path)||(r.add(i.path),n.push(i));}return n}function mP(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function fP(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function gP(e,t){if(t==="all")return e;let r=new Map,n=[];for(let s of e){if(!s.path.endsWith(".md")){n.push(s);continue}let i=mP(s.path),a=fP(s.path),l=r.get(i);l||(l=new Map,r.set(i,l)),l.set(a,s);}let o=[];for(let[s,i]of r){let a=i.get(t)??i.get("pt")??i.get("en")??i.get("es");o.push({...a,path:s});}return [...n,...o]}async function uh(e){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??zc,i=ya();if(!i)throw new Sa("FLOW_HARNESS_PATH is not set");let a,l;try{a=ch(i),l=wa(i);}catch(f){throw new Sa(`could not read docs from "${i}" (${f instanceof Error?f.message:String(f)})`)}let u=e.docsLang??"all",c=e.installedBundles.length===0,d=c?[]:pP(e.installedBundles,l),m=gP([...a,...d],u),p=[],g=Jc();for(let f of m){let h=join(t,f.path),v=await Gc({dstPath:h,template:f,force:n,isInteractive:o,confirmOverwrite:_=>s(_)});p.push({path:f.path,status:v.status}),g[v.status]++,v.write&&!r&&(mkdirSync(dirname(h),{recursive:true}),writeFileSync(h,f.content,"utf8"));}let y=g.divergent>0||g.declined>0;return {files:p,counts:g,hasUnresolved:y,skippedPlaybooks:c}}function dh(e){let t=Pe().plugins,r=process.cwd(),n=new Set;for(let[o,s]of Object.entries(t)){let i=o.split("@")[0];if(!i||!e.has(i))continue;s.some(l=>l.scope==="user"||l.projectPath===r)&&n.add(i);}return [...n].sort()}N();R();Ce();Zr();R();var Yc=b("lib:otelMetrics"),yP="flow-plugins-cli",wP="1.0.0",SP=5e3;function bP(){return Ut("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function xP(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 vP(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:yP,version:wP},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>xP(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Zc(e,t={}){try{let[r,n]=await Promise.all([Rn(),te()]),o=r?.email,s=n?.tenant;if(!o||!s){Yc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=vP(e,t);await cp.post(bP(),{json:i,timeout:SP,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Yc.debug(`OTel metric sent: ${e}`);}catch(r){Yc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Qc=b("cli:init"),PP={new:{label:"new",color:T.green},unchanged:{label:"unchanged",color:T.dim},divergent:{label:"kept (differs from template)",color:T.yellow},declined:{label:"pending (declined)",color:T.yellow}};function TP(e){process.stdout.write(`
558
558
  `+T.bold(` flow setup strategy
559
559
  `)),process.stdout.write(T.dim(` Target: ${e}
560
560
 
561
561
  `)),process.stdout.write(T.dim(` Files evaluated:
562
562
  `));for(let t of fs)process.stdout.write(T.dim(` \xB7 ${t.path}
563
563
  `));process.stdout.write(`
564
- `);}function CP(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)}`);}),Zc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function dh(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)}`);}),Zc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function kP(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function AP(){return z(" Continue anyway? [y/N] ")}async function RP(){return x(`docs/catalog/ is the skill/agent/command catalog (~2.6MB); docs/playbooks/ is the
564
+ `);}function CP(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)}`);}),Zc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function ph(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)}`);}),Zc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function kP(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function AP(){return z(" Continue anyway? [y/N] ")}async function RP(){return x(`docs/catalog/ is the skill/agent/command catalog (~2.6MB); docs/playbooks/ is the
565
565
  runbook + sub-runbook docs for your installed bundles, in every language they ship
566
566
  in (.md/.en.md/.es.md). This is the same content flow-playbooks-app renders \u2014 skip
567
- it if you don't run that app.`),z(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function $P(){return vi(" Which language?",[{value:"all",label:"All variants",description:"every .md/.en.md/.es.md kept as-is"},{value:"pt",label:"pt (default)",description:"the base, unsuffixed .md files only"},{value:"en",label:"en",description:".en.md only"},{value:"es",label:"es",description:".es.md only"}])}async function ba(e){if(Qc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await q())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmContinueWithoutGit??AP;if(!await kP(t)){let h=`${t} is not a git repository. Strategy docs are meant to be version-controlled \u2014 consider running "git init" first.`;if(!r)return e.json?_e({error:h,exitCode:1}):I(`${h} Re-run interactively to confirm, or run "git init" first.`),1;if(x(h),!await n())return 1}e.json||TP(t);let o=Date.now(),s;try{s=await sh({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(h){throw dh(h instanceof Error?h.message:String(h),Date.now()-o),h}let i,a=e.confirmDocsContent??RP,l=e.selectDocsLang??$P,u=!!e.docsContent,c=e.docsLang??"all";if(!u&&r&&(u=await a(),u&&(c=await l())),u)try{let h=ya();if(!h)throw new Error("docs-content requires a local flow-harness checkout: FLOW_HARNESS_PATH is not set. Set it to the path of a cit-flow/flow-harness clone and re-run.");let v=new Set(Object.keys(wa(h))),_=uh(v);i=await ch({targetDir:t,dryRun:e.dryRun,force:e.force,installedBundles:_,docsLang:c});}catch(h){throw dh(h instanceof Error?h.message:String(h),Date.now()-o),h}let d=s.hasUnresolved||i?.hasUnresolved?2:0;if(CP(s.counts,!!e.dryRun,d,Date.now()-o),e.json)return ne({dryRun:!!e.dryRun,counts:s.counts,files:s.files,docsContent:i?{counts:i.counts,files:i.files,skippedPlaybooks:i.skippedPlaybooks}:void 0,exitCode:d}),d;let m=e.dryRun?T.dim("[dry-run] "):"";process.stdout.write(T.bold(` Result:
567
+ it if you don't run that app.`),z(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function $P(){return vi(" Which language?",[{value:"all",label:"All variants",description:"every .md/.en.md/.es.md kept as-is"},{value:"pt",label:"pt (default)",description:"the base, unsuffixed .md files only"},{value:"en",label:"en",description:".en.md only"},{value:"es",label:"es",description:".es.md only"}])}async function ba(e){if(Qc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await q())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmContinueWithoutGit??AP;if(!await kP(t)){let h=`${t} is not a git repository. Strategy docs are meant to be version-controlled \u2014 consider running "git init" first.`;if(!r)return e.json?_e({error:h,exitCode:1}):I(`${h} Re-run interactively to confirm, or run "git init" first.`),1;if(x(h),!await n())return 1}e.json||TP(t);let o=Date.now(),s;try{s=await ih({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(h){throw ph(h instanceof Error?h.message:String(h),Date.now()-o),h}let i,a=e.confirmDocsContent??RP,l=e.selectDocsLang??$P,u=!!e.docsContent,c=e.docsLang??"all";if(!u&&r&&(u=await a(),u&&(c=await l())),u)try{let h=ya();if(!h)throw new Error("docs-content requires a local flow-harness checkout: FLOW_HARNESS_PATH is not set. Set it to the path of a cit-flow/flow-harness clone and re-run.");let v=new Set(Object.keys(wa(h))),_=dh(v);i=await uh({targetDir:t,dryRun:e.dryRun,force:e.force,installedBundles:_,docsLang:c});}catch(h){throw ph(h instanceof Error?h.message:String(h),Date.now()-o),h}let d=s.hasUnresolved||i?.hasUnresolved?2:0;if(CP(s.counts,!!e.dryRun,d,Date.now()-o),e.json)return ne({dryRun:!!e.dryRun,counts:s.counts,files:s.files,docsContent:i?{counts:i.counts,files:i.files,skippedPlaybooks:i.skippedPlaybooks}:void 0,exitCode:d}),d;let m=e.dryRun?T.dim("[dry-run] "):"";process.stdout.write(T.bold(` Result:
568
568
  `));for(let h of s.files){let{label:v,color:_}=PP[h.status];process.stdout.write(` ${m}${_(v.padEnd(18))} ${h.path}
569
569
  `);}process.stdout.write(`
570
570
  `);let{new:p,unchanged:g,divergent:y,declined:f}=s.counts;if(X(`${p} new, ${g} unchanged, ${y} kept (differs from template)`+(f>0?`, ${f} pending confirmation`:"")),(y>0||f>0)&&x(`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){process.stdout.write(`
571
571
  `+T.bold(` docs/catalog + docs/playbooks:
572
- `)),i.skippedPlaybooks&&x('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let h=i.counts;X(`${h.new} new, ${h.unchanged} unchanged, ${h.divergent} kept (differs from template)`+(h.declined>0?`, ${h.declined} pending confirmation`:"")),(h.divergent>0||h.declined>0)&&x("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return d!==0&&I("flow setup strategy finished with unresolved files \u2014 see above."),d}N();F();var fo=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var eu="repos.yaml",LP="projects";function DP(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 mh(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 OP=/^(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(!OP.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 fh(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??LP)},repos:DP(r.repos,"repos",n),warnings:n}}function Ea(e,t){let r=join(e,eu),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function gh(e){let t=join(e,".gitignore"),r=eu;if(!existsSync(t)){writeFileSync(t,`${r}
572
+ `)),i.skippedPlaybooks&&x('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let h=i.counts;X(`${h.new} new, ${h.unchanged} unchanged, ${h.divergent} kept (differs from template)`+(h.declined>0?`, ${h.declined} pending confirmation`:"")),(h.divergent>0||h.declined>0)&&x("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return d!==0&&I("flow setup strategy finished with unresolved files \u2014 see above."),d}N();F();var fo=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var eu="repos.yaml",LP="projects";function DP(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 fh(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 OP=/^(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(!OP.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 gh(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??LP)},repos:DP(r.repos,"repos",n),warnings:n}}function Ea(e,t){let r=join(e,eu),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function hh(e){let t=join(e,".gitignore"),r=eu;if(!existsSync(t)){writeFileSync(t,`${r}
573
573
  `,"utf8");return}let n=readFileSync(t,"utf8");n.split(`
574
574
  `).some(s=>s.trim()===r)||appendFileSync(t,`${n.endsWith(`
575
575
  `)?"":`
576
576
  `}${r}
577
- `,"utf8");}function hh(e,t){let r=join(e,".gitignore"),n=`${t}/`;if(!existsSync(r)){writeFileSync(r,`${n}
577
+ `,"utf8");}function yh(e,t){let r=join(e,".gitignore"),n=`${t}/`;if(!existsSync(r)){writeFileSync(r,`${n}
578
578
  `,"utf8");return}let o=readFileSync(r,"utf8");o.split(`
579
579
  `).some(i=>i.trim()===n)||appendFileSync(r,`${o.endsWith(`
580
580
  `)?"":`
581
581
  `}${n}
582
- `,"utf8");}function yh(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
582
+ `,"utf8");}function wh(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
583
583
  `).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.
584
584
  `,a=s.map(l=>`# ${l}/ \u2014 repos cloned via flow setup workspace, not part of this repo's own docs.
585
585
  ${l}/`).join(`
@@ -588,21 +588,21 @@ ${l}/`).join(`
588
588
  ${a}
589
589
  `,"utf8"):writeFileSync(r,`${i}
590
590
  ${a}
591
- `,"utf8");}var ph="## Off-Limits \u2014 Workspace Repos";function wh(e,t,r){if(!r)return "declined";let n=join(e,"CLAUDE.md");if(!existsSync(n))return "no-claude-md";let o=readFileSync(n,"utf8");if(o.includes(ph))return "already-present";let s=`
592
- ${ph}
591
+ `,"utf8");}var mh="## Off-Limits \u2014 Workspace Repos";function Sh(e,t,r){if(!r)return "declined";let n=join(e,"CLAUDE.md");if(!existsSync(n))return "no-claude-md";let o=readFileSync(n,"utf8");if(o.includes(mh))return "already-present";let s=`
592
+ ${mh}
593
593
 
594
594
  \`${t.repos_dir}/\` contains repos cloned via \`flow setup workspace\` \u2014 not part of this repo's own documentation or code. It is excluded from Claude Code's context via \`.claudeignore\`.
595
595
 
596
596
  > Off-limits: do not read, index, link, or reference files inside this folder in any context.
597
597
  `;return appendFileSync(n,`${o.endsWith(`
598
598
  `)?"":`
599
- `}${s}`,"utf8"),"appended"}var Sh="projects";function UP(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 bh(){for(;;){let e=await Xn(" Repo URL \u2014 SSH or HTTPS (leave empty and press ENTER to finish): ");if(!e)return null;let t=UP(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.
600
- `);continue}let r=await Xn(` Group/category for '${t}' (optional, default: general): `),n=tu(e);return {name:t,remote:n,group:r||"general"}}}async function xh(){if(!await z("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Xn(` Folder for work repos (default: ${Sh}): `),r=[];for(;;){let n=await bh();if(!n)break;r.push(n);}return r.length===0?null:{workspace:{repos_dir:t||Sh},repos:r,warnings:[]}}async function vh(e){let{valid:t,invalid:r}=Ia(e);process.stdout.write(` Current repos in repos.yaml (${e.length}):
599
+ `}${s}`,"utf8"),"appended"}var bh="projects";function UP(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 xh(){for(;;){let e=await Xn(" Repo URL \u2014 SSH or HTTPS (leave empty and press ENTER to finish): ");if(!e)return null;let t=UP(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.
600
+ `);continue}let r=await Xn(` Group/category for '${t}' (optional, default: general): `),n=tu(e);return {name:t,remote:n,group:r||"general"}}}async function vh(){if(!await z("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Xn(` Folder for work repos (default: ${bh}): `),r=[];for(;;){let n=await xh();if(!n)break;r.push(n);}return r.length===0?null:{workspace:{repos_dir:t||bh},repos:r,warnings:[]}}async function Ih(e){let{valid:t,invalid:r}=Ia(e);process.stdout.write(` Current repos in repos.yaml (${e.length}):
601
601
  `);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}
602
- `);}let n=t,o=false;if(r.length>0&&(await z(` Remove the ${r.length} invalid entr${r.length===1?"y":"ies"} listed above? [y/N] `)?o=true:n=e),await z(" Add more repos to repos.yaml? [y/N] "))for(;;){let i=await bh();if(!i)break;n=[...n,i],o=true;}return {repos:n,changed:o}}R();var Ih=b("workspace:repos"),Eh=6e4;async function FP(e){try{return (await simpleGit(e).status()).current}catch{return null}}function Ph(){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 Th=["GIT_TERMINAL_PROMPT"];async function jP(e){await simpleGit(e,{timeout:{block:Eh},allowEnvironment:Th}).env(Ph()).pull(["--ff-only"]);}async function KP(e,t){await simpleGit({timeout:{block:Eh},allowEnvironment:Th}).env(Ph()).clone(e,t);}async function Ch(e,t){let r=join(t,e.name),n=join(r,".git");if(existsSync(n)){let o=await FP(r);if(o==="main"||o==="master")try{return await jP(r),{name:e.name,outcome:"updated",path:r}}catch(s){return Ih.warn(`[${e.name}] pull failed (branch diverged?): ${String(s)}`),{name:e.name,outcome:"skipped",path:r}}return {name:e.name,outcome:"skipped",path:r}}try{return mkdirSync(t,{recursive:!0}),await KP(e.remote,r),{name:e.name,outcome:"cloned",path:r}}catch(o){let s=o instanceof Error?o.message:String(o);return Ih.error(`[${e.name}] clone failed: ${s}`),{name:e.name,outcome:"failed",error:s}}}function kh(e,t){return !existsSync(join(t,e.name,".git"))}function Ah(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var WP=promisify(execFile),Rh=5e3;async function $h(){try{let{stdout:e,stderr:t}=await WP("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${Rh/1e3}`],{timeout:Rh+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function _h(e){let t=Math.max(1,cpus().length);return Math.max(1,Math.min(t,4,e))}async function Mh(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}function su(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Dh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=fh(t);if(n){if(r){let f=await vh(n.repos);f.changed?(n={...n,repos:f.repos},Ea(t,n)):n={...n,repos:f.repos};}}else {if(!r)return su();let f=await xh();if(!f)return su();Ea(t,f),gh(t),n=f;}let{repos:o,converted:s}=mh(n.repos);s.length>0&&(n={...n,repos:o},Ea(t,n)),yh(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=Ia(n.repos),u=[...n.warnings,...l.map(f=>`${f.entry.name||"(unnamed)"}: ${f.reason} \u2014 skipped`),...s.map(f=>`${f.before.name}: remote is HTTPS \u2014 converted to SSH (${f.after.remote}) and saved to repos.yaml`)];if(a.some(f=>kh(f,i))&&!await $h())return su({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let d=_h(a.length),m=await Mh(a,d,async(f,h)=>{e.onRepoProgress?.({name:f.name,index:h,total:a.length,status:"start"});let v=await Ch(f,i);return e.onRepoProgress?.({name:f.name,index:h,total:a.length,status:v.outcome,path:v.path}),v}),p=new Set(a.map(f=>f.name)),g=Ah(i,p),y=0;if(e.prune&&g.length>0)for(let f of g)rmSync(join(i,f),{recursive:true,force:true}),y++;return hh(t,n.workspace.repos_dir),{repos:m,orphans:e.prune?[]:g,prunedCount:y,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}R();var zP=["local","project","user"],Uh=[{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"}],iu=Uh.map(e=>e.name);function XP(e){return e.filter(t=>!iu.includes(t))}function qP(){x(`The following ${fo.length} runbook bundles will be installed:`);for(let e of fo)process.stdout.write(` - ${e}
603
- `);}async function YP(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of Uh)await z(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function ZP(){return vi(" Install scope:",zP.map(e=>({value:e,label:Lt[e].actionLabel,description:Lt[e].description})))}var ys=Symbol("skip");async function Oh(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=sa(e);if(a){if(a.scope===n)return o||x(`${t}${e} is already installed ${Zt(a)}. Use --force to reinstall.`),ys;if(o||!s)return o||x(`${t}Skipping ${e} \u2014 already installed ${Zt(a)}. Re-run with --force to install here too.`),ys;if(!await ia(e,n,a))return x(`${t}Skipped ${e}.`),ys;let u=await ds(e,{force:true,scope:a.scope});if(u!==0)return x(`${t}Could not remove ${e} from ${Zt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||x(`${t}Installing ${e}...`),po([e],{scope:n,silent:o,force:i})}async function au(e={}){if(!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=XP(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${iu.join(", ")}`;return e.silent?ne({error:a}):I(a),1}}e.silent||qP();let r=e.scope;if(!r&&!e.silent&&t)try{r=await ZP();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
604
- `),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<fo.length;a++){let l=fo[a],u=`[${a+1}/${fo.length}] `,c=await Oh(l,u,o);c!==ys&&s.push(c);}let i=e.extraPlugins?iu.filter(a=>e.extraPlugins.includes(a)):await YP(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await Oh(l,u,o);c!==ys&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
605
- `),130;throw i}return s.some(i=>i!==0)?1:0}var QP=b("cli:setup-workspace");function Nh(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function eT(){x("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:
602
+ `);}let n=t,o=false;if(r.length>0&&(await z(` Remove the ${r.length} invalid entr${r.length===1?"y":"ies"} listed above? [y/N] `)?o=true:n=e),await z(" Add more repos to repos.yaml? [y/N] "))for(;;){let i=await xh();if(!i)break;n=[...n,i],o=true;}return {repos:n,changed:o}}R();var Eh=b("workspace:repos"),Ph=6e4;async function FP(e){try{return (await simpleGit(e).status()).current}catch{return null}}function Th(){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 Ch=["GIT_TERMINAL_PROMPT"];async function jP(e){await simpleGit(e,{timeout:{block:Ph},allowEnvironment:Ch}).env(Th()).pull(["--ff-only"]);}async function KP(e,t){await simpleGit({timeout:{block:Ph},allowEnvironment:Ch}).env(Th()).clone(e,t);}async function kh(e,t){let r=join(t,e.name),n=join(r,".git");if(existsSync(n)){let o=await FP(r);if(o==="main"||o==="master")try{return await jP(r),{name:e.name,outcome:"updated",path:r}}catch(s){return Eh.warn(`[${e.name}] pull failed (branch diverged?): ${String(s)}`),{name:e.name,outcome:"skipped",path:r}}return {name:e.name,outcome:"skipped",path:r}}try{return mkdirSync(t,{recursive:!0}),await KP(e.remote,r),{name:e.name,outcome:"cloned",path:r}}catch(o){let s=o instanceof Error?o.message:String(o);return Eh.error(`[${e.name}] clone failed: ${s}`),{name:e.name,outcome:"failed",error:s}}}function Ah(e,t){return !existsSync(join(t,e.name,".git"))}function Rh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var WP=promisify(execFile),$h=5e3;async function _h(){try{let{stdout:e,stderr:t}=await WP("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${$h/1e3}`],{timeout:$h+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Mh(e){let t=Math.max(1,cpus().length);return Math.max(1,Math.min(t,4,e))}async function Lh(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}function su(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Oh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=gh(t);if(n){if(r){let f=await Ih(n.repos);f.changed?(n={...n,repos:f.repos},Ea(t,n)):n={...n,repos:f.repos};}}else {if(!r)return su();let f=await vh();if(!f)return su();Ea(t,f),hh(t),n=f;}let{repos:o,converted:s}=fh(n.repos);s.length>0&&(n={...n,repos:o},Ea(t,n)),wh(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=Ia(n.repos),u=[...n.warnings,...l.map(f=>`${f.entry.name||"(unnamed)"}: ${f.reason} \u2014 skipped`),...s.map(f=>`${f.before.name}: remote is HTTPS \u2014 converted to SSH (${f.after.remote}) and saved to repos.yaml`)];if(a.some(f=>Ah(f,i))&&!await _h())return su({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let d=Mh(a.length),m=await Lh(a,d,async(f,h)=>{e.onRepoProgress?.({name:f.name,index:h,total:a.length,status:"start"});let v=await kh(f,i);return e.onRepoProgress?.({name:f.name,index:h,total:a.length,status:v.outcome,path:v.path}),v}),p=new Set(a.map(f=>f.name)),g=Rh(i,p),y=0;if(e.prune&&g.length>0)for(let f of g)rmSync(join(i,f),{recursive:true,force:true}),y++;return yh(t,n.workspace.repos_dir),{repos:m,orphans:e.prune?[]:g,prunedCount:y,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}R();var zP=["local","project","user"],Nh=[{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"}],iu=Nh.map(e=>e.name);function XP(e){return e.filter(t=>!iu.includes(t))}function qP(){x(`The following ${fo.length} runbook bundles will be installed:`);for(let e of fo)process.stdout.write(` - ${e}
603
+ `);}async function YP(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of Nh)await z(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function ZP(){return vi(" Install scope:",zP.map(e=>({value:e,label:Lt[e].actionLabel,description:Lt[e].description})))}var ys=Symbol("skip");async function Uh(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=sa(e);if(a){if(a.scope===n)return o||x(`${t}${e} is already installed ${Zt(a)}. Use --force to reinstall.`),ys;if(o||!s)return o||x(`${t}Skipping ${e} \u2014 already installed ${Zt(a)}. Re-run with --force to install here too.`),ys;if(!await ia(e,n,a))return x(`${t}Skipped ${e}.`),ys;let u=await ds(e,{force:true,scope:a.scope});if(u!==0)return x(`${t}Could not remove ${e} from ${Zt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||x(`${t}Installing ${e}...`),po([e],{scope:n,silent:o,force:i})}async function au(e={}){if(!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=XP(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${iu.join(", ")}`;return e.silent?ne({error:a}):I(a),1}}e.silent||qP();let r=e.scope;if(!r&&!e.silent&&t)try{r=await ZP();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
604
+ `),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<fo.length;a++){let l=fo[a],u=`[${a+1}/${fo.length}] `,c=await Uh(l,u,o);c!==ys&&s.push(c);}let i=e.extraPlugins?iu.filter(a=>e.extraPlugins.includes(a)):await YP(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await Uh(l,u,o);c!==ys&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
605
+ `),130;throw i}return s.some(i=>i!==0)?1:0}var QP=b("cli:setup-workspace");function Bh(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function eT(){x("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:
606
606
  `),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
607
607
  `),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
608
608
  `),process.stdout.write(` 3. Start the agent: eval "$(ssh-agent -s)"
@@ -611,13 +611,13 @@ ${ph}
611
611
  `),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
612
612
  `),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
613
613
  `);}function tT(e){let t=`[${e.index+1}/${e.total}]`;if(e.status==="start"){process.stdout.write(T.yellow(` ${t} ${e.name}...
614
- `));return}let r=Nh(e.status);if(e.status==="cloned"||e.status==="updated"){let n=e.path?` \u2192 ${e.path}`:"";process.stdout.write(T.green(` ${t} ${e.name}: ${r}${n}
614
+ `));return}let r=Bh(e.status);if(e.status==="cloned"||e.status==="updated"){let n=e.path?` \u2192 ${e.path}`:"";process.stdout.write(T.green(` ${t} ${e.name}: ${r}${n}
615
615
  `));}else e.status==="failed"?process.stdout.write(T.red(` ${t} ${e.name}: ${r}
616
616
  `)):process.stdout.write(T.dim(` ${t} ${e.name}: ${r}
617
- `));}function rT(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,Nh(r.outcome),r.error??""]);br(["","Repo","Outcome","Detail"],t);}async function nT(e,t,r,n){if(r||!n||t.skippedNoManifest||!t.workspaceDirs)return;let{repos_dir:o}=t.workspaceDirs,s=await z(` Add an off-limits note to CLAUDE.md for '${o}/'? [y/N] `),i=wh(e,t.workspaceDirs,s);i==="appended"?x(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?x("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&x("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function lu(e={}){if(QP.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Dh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:tT});if(e.json)return ne({repos:r.repos,orphans:r.orphans,prunedCount:r.prunedCount,skippedNoManifest:r.skippedNoManifest,manifestWarnings:r.manifestWarnings,sshBlocked:r.sshBlocked}),r.sshBlocked||r.repos.some(a=>a.outcome==="failed")?1:0;for(let a of r.manifestWarnings)x(`repos.yaml: ${a}`);if(r.sshBlocked)return eT(),1;if(r.skippedNoManifest)return x("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;rT(r.repos);let n=r.repos.filter(a=>a.outcome==="cloned").length,o=r.repos.filter(a=>a.outcome==="updated").length,s=r.repos.filter(a=>a.outcome==="skipped").length,i=r.repos.filter(a=>a.outcome==="failed").length;return X(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&x(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`),await nT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var oT=[{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:()=>au({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>lu({path:e})}];async function sT(e){return z(` Run ${e}? [y/N] `)}async function Bh(e={}){if(!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??sT,n=!!e.yes||!t;!e.yes&&!t&&x("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of oT){if(!(n||await r(s.label))){x(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var iT=">=2.9.0-beta.28 <2.10.2-beta.49";function aT(e){return ac.valid(e)?ac.satisfies(e,iT,{includePrerelease:true}):false}function jh(e=he){return aT(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.
617
+ `));}function rT(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,Bh(r.outcome),r.error??""]);br(["","Repo","Outcome","Detail"],t);}async function nT(e,t,r,n){if(r||!n||t.skippedNoManifest||!t.workspaceDirs)return;let{repos_dir:o}=t.workspaceDirs,s=await z(` Add an off-limits note to CLAUDE.md for '${o}/'? [y/N] `),i=Sh(e,t.workspaceDirs,s);i==="appended"?x(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?x("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&x("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function lu(e={}){if(QP.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Oh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:tT});if(e.json)return ne({repos:r.repos,orphans:r.orphans,prunedCount:r.prunedCount,skippedNoManifest:r.skippedNoManifest,manifestWarnings:r.manifestWarnings,sshBlocked:r.sshBlocked}),r.sshBlocked||r.repos.some(a=>a.outcome==="failed")?1:0;for(let a of r.manifestWarnings)x(`repos.yaml: ${a}`);if(r.sshBlocked)return eT(),1;if(r.skippedNoManifest)return x("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;rT(r.repos);let n=r.repos.filter(a=>a.outcome==="cloned").length,o=r.repos.filter(a=>a.outcome==="updated").length,s=r.repos.filter(a=>a.outcome==="skipped").length,i=r.repos.filter(a=>a.outcome==="failed").length;return X(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&x(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`),await nT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var oT=[{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:()=>au({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>lu({path:e})}];async function sT(e){return z(` Run ${e}? [y/N] `)}async function Fh(e={}){if(!await q())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??sT,n=!!e.yes||!t;!e.yes&&!t&&x("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of oT){if(!(n||await r(s.label))){x(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var iT=">=2.9.0-beta.28 <2.10.2-beta.49";function aT(e){return ac.valid(e)?ac.satisfies(e,iT,{includePrerelease:true}):false}function Kh(e=he){return aT(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.
618
618
  Run: npm install -g @ciandt-flow/cli@latest
619
619
  Then re-run this command.`}:{blocked:false}}function lT(e){let t=["",T.bold("All commands:"),""];function r(n,o,s){if(n.name()==="help")return;let i=`${o} ${n.name()}`,a=" ".repeat(s),l=n.description()?T.dim(` \u2014 ${n.description()}`):"";t.push(`${a}${T.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("",T.dim("Without arguments, opens the interactive interface (TUI)."),T.dim("Use 'flow <command> --help' for details and examples on each command.")),t.join(`
620
- `)}function Kh(e){let t=new Command;t.enablePositionalOptions(),t.configureHelp({styleTitle:c=>T.bold(c),styleCommandText:c=>T.cyan.bold(c),styleSubcommandText:c=>T.cyan(c),styleOptionTerm:c=>T.yellow(c),styleArgumentTerm:c=>T.green(c),styleDescriptionText:c=>T.dim(c)}),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${he}`,"-V, --version","Display the CLI version").addHelpText("after",()=>lT(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",`
620
+ `)}function Hh(e){let t=new Command;t.enablePositionalOptions(),t.configureHelp({styleTitle:c=>T.bold(c),styleCommandText:c=>T.cyan.bold(c),styleSubcommandText:c=>T.cyan(c),styleOptionTerm:c=>T.yellow(c),styleArgumentTerm:c=>T.green(c),styleDescriptionText:c=>T.dim(c)}),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${he}`,"-V, --version","Display the CLI version").addHelpText("after",()=>lT(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",`
621
621
  Examples:
622
622
  $ flow setup init`).action(async()=>{let c=await Lc();L(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"])).option("--docs-content","Also scaffold docs/catalog (skill/agent/command catalog) and docs/playbooks (runbook docs for your installed bundles). Interactive: asks for confirmation. Non-interactive: never scaffolds it, even with this flag set.",false).addOption(new Option("--docs-lang <lang>","With --docs-content: which language variant to write (default: all \u2014 every .md/.en.md/.es.md kept). Interactive: asked right after you confirm docs-content, no flag needed. A doc missing the chosen language falls back to whatever variant it does have.").choices(["all","pt","en","es"])).addHelpText("after",`
623
623
  Examples:
@@ -656,13 +656,13 @@ Examples:
656
656
  Without --yes and with an interactive terminal, asks [y/N] before each of the
657
657
  3 steps (strategy, harness, workspace) \u2014 declining one skips just that step
658
658
  and moves to the next. Without an interactive terminal, runs all 3 steps
659
- without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await Bh({path:c.path,yes:c.yes});L(d);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
659
+ without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await Fh({path:c.path,yes:c.yes});L(d);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
660
660
  Examples:
661
661
  $ flow plugin list
662
662
  $ flow plugin list --available
663
663
  $ flow plugin list --outdated
664
664
  $ flow plugin list --json
665
- $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await cg(c);L(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
665
+ $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await ug(c);L(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
666
666
  Examples:
667
667
  $ flow plugin install flow-adr-writer
668
668
  $ flow plugin install flow-adr-writer --scope project
@@ -689,7 +689,7 @@ Examples:
689
689
  $ flow plugin update flow-adr-writer --verbose
690
690
  $ flow plugin update flow-adr-writer --silent
691
691
  $ flow plugin update
692
- $ flow plugin update --dry-run`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await fg(c??null,d);L(m);}),n.command("prune").description("Remove cached versions of installed plugins that are no longer needed").option("--dry-run","Show what would be removed without deleting anything").option("--force","Skip interactive confirmation").option("--silent","Output in JSON only").addHelpText("after",`
692
+ $ flow plugin update --dry-run`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await gg(c??null,d);L(m);}),n.command("prune").description("Remove cached versions of installed plugins that are no longer needed").option("--dry-run","Show what would be removed without deleting anything").option("--force","Skip interactive confirmation").option("--silent","Output in JSON only").addHelpText("after",`
693
693
  Examples:
694
694
  $ flow plugin prune
695
695
  $ flow plugin prune --dry-run
@@ -708,36 +708,36 @@ version a live session still has open, even if that version is stale from
708
708
 
709
709
  --silent has no terminal to prompt on, so it does NOT imply --force \u2014 a
710
710
  non-dry-run \`--silent\` without \`--force\` returns an error instead of
711
- deleting files a script didn't explicitly ask to remove.`).action(async c=>{Be("cli",{silent:c.silent});let d=await gg(c);L(d);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
711
+ deleting files a script didn't explicitly ask to remove.`).action(async c=>{Be("cli",{silent:c.silent});let d=await hg(c);L(d);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
712
712
  Examples:
713
713
  $ flow plugin enable flow-adr-writer
714
- $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Be("cli");let m=await dg(c,d);L(m);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
714
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Be("cli");let m=await pg(c,d);L(m);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
715
715
  Examples:
716
716
  $ flow plugin disable flow-adr-writer
717
- $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Be("cli");let m=await pg(c,d);L(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
717
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Be("cli");let m=await mg(c,d);L(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
718
718
  Examples:
719
719
  $ flow plugin export
720
- $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Xg(c);L(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
720
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await qg(c);L(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
721
721
  Examples:
722
722
  $ flow plugin import flow-plugins.json
723
723
  $ flow plugin import flow-plugins.json --scope user
724
724
  $ flow plugin import flow-plugins.json --force
725
725
  $ flow plugin import flow-plugins.json --dry-run
726
- $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await qg(c,d);L(m);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
726
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Yg(c,d);L(m);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
727
727
  Examples:
728
728
  $ flow plugin marketplace add anthropics/claude-code
729
729
  $ flow plugin marketplace add https://github.com/owner/repo
730
730
  $ flow plugin marketplace add anthropics/claude-code --force
731
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await wg(c,d);L(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
731
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await Sg(c,d);L(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
732
732
  Examples:
733
733
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
734
734
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
735
735
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
736
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Be("cli",{verbose:m.verbose,silent:m.silent});let p=await Lm(c,d,m);L(p);}),s.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
736
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Be("cli",{verbose:m.verbose,silent:m.silent});let p=await Dm(c,d,m);L(p);}),s.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
737
737
  Examples:
738
738
  $ flow mcp remove notion
739
739
  $ flow mcp remove notion --scope project
740
- $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await Dm(c,d);L(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
740
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Be("cli",{verbose:d.verbose,silent:d.silent});let m=await Om(c,d);L(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
741
741
  Examples:
742
742
  $ flow auth login
743
743
  $ flow auth login --jwt <token>
@@ -746,41 +746,41 @@ Examples:
746
746
  $ flow auth login --verbose`).action(async c=>{Be("cli",{verbose:c.verbose});let d=await Lc(c);L(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
747
747
  Examples:
748
748
  $ flow auth logout
749
- $ flow auth logout --force`).action(async c=>{let d=await og(c.force);L(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
749
+ $ flow auth logout --force`).action(async c=>{let d=await sg(c.force);L(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
750
750
  Examples:
751
- $ flow auth status`).action(async()=>{let c=await sg();L(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
751
+ $ flow auth status`).action(async()=>{let c=await ig();L(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
752
752
  Examples:
753
753
  $ flow skills add vercel-labs/agent-skills
754
754
  $ flow skills add owner/repo -g
755
755
  $ flow skills add owner/repo --skill pr-review commit
756
756
  $ flow skills add ./local/skills -y
757
- $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Hg(c,d);L(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
757
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Vg(c,d);L(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
758
758
  Examples:
759
759
  $ flow skills list
760
760
  $ flow skills list -g
761
- $ flow skills list --json`).action(async c=>{let d=await Wg(c);L(d);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
761
+ $ flow skills list --json`).action(async c=>{let d=await Jg(c);L(d);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
762
762
  Examples:
763
763
  $ flow skills remove pr-review
764
- $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Jg(c,d);L(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
764
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Gg(c,d);L(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
765
765
  Examples:
766
766
  $ flow bundle install "My React Kit"
767
767
  $ flow bundle install "Squad Setup Bundle"
768
- $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Be("cli",{verbose:d.verbose});let m=await hg(c);L(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").option("--fix","Retroactively set autoUpdate: true on already-registered Flow-curated marketplaces (FLWP-71702)").addHelpText("after",`
768
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Be("cli",{verbose:d.verbose});let m=await yg(c);L(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").option("--fix","Retroactively set autoUpdate: true on already-registered Flow-curated marketplaces (FLWP-71702)").addHelpText("after",`
769
769
  Examples:
770
770
  $ flow health
771
- $ flow health --fix`).action(async c=>{let d=await Sg(c);L(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
771
+ $ flow health --fix`).action(async c=>{let d=await bg(c);L(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
772
772
  Examples:
773
773
  $ flow usage
774
- $ flow usage --json`).action(async c=>{let d=await Pg(c);L(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Fc();L(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
774
+ $ flow usage --json`).action(async c=>{let d=await Tg(c);L(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Fc();L(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
775
775
  Examples:
776
776
  $ flow modules list`).action(async()=>{let c=await Fc();L(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
777
777
  Examples:
778
778
  $ flow modules install metrics
779
- $ flow modules install dashboard`).action(async c=>{let d=await rh(c);L(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",`
779
+ $ flow modules install dashboard`).action(async c=>{let d=await nh(c);L(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",`
780
780
  Examples:
781
781
  $ flow modules update
782
- $ flow modules update metrics`).action(async c=>{let d=await nh(c??null);L(d);}),t.addCommand(u);for(let c of de)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Qg(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=jh();if(m)throw new Error(p)}),t.hook("preAction",()=>{qi();}),t}R();function dT(){return oe__default.join(Te__default.homedir(),".claude","settings.json")}function Vh(){let e=dT();try{if(!le__default.existsSync(e))return !0;let r=JSON.parse(le__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var yT=b("updateChecker"),wT=promisify(execFile),ST=1440*60*1e3,Wh=3e4;function bT(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"update.lock")}async function Jh(e){try{let{stdout:t}=await wT(tr(),["view",e,"version"],{timeout:Wh,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function xT(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Wh);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 vT(e){return e.versionCheck.type==="npm-registry"?Jh(e.versionCheck.package):xT(e.versionCheck.repo)}async function IT(){let e=await Jh("@ciandt-flow/cli");return e&&Ve(he,e)?(ra({currentVersion:he,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function ET(){let e=an().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=de.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<ST)return;let s=await vT(r);try{await bt({...t,lastChecked:new Date().toISOString()});}catch(i){yT.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ve(t.installedVersion,s)&&ti(r,"background").catch(()=>{});}));}async function uu(){let e=Vh();if(e===false)return;let t=bT();le__default.mkdirSync(oe__default.dirname(t),{recursive:true});let r;try{r=await Sw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await IT().catch(()=>null);n&&process.stdout.write(`
782
+ $ flow modules update metrics`).action(async c=>{let d=await oh(c??null);L(d);}),t.addCommand(u);for(let c of de)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await eh(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=Kh();if(m)throw new Error(p)}),t.hook("preAction",()=>{qi();}),t}R();function dT(){return oe__default.join(Te__default.homedir(),".claude","settings.json")}function Wh(){let e=dT();try{if(!le__default.existsSync(e))return !0;let r=JSON.parse(le__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var yT=b("updateChecker"),wT=promisify(execFile),ST=1440*60*1e3,Jh=3e4;function bT(){let e=process.env.FLOW_HOME??oe__default.join(Te__default.homedir(),".flow");return oe__default.join(e,"update.lock")}async function Gh(e){try{let{stdout:t}=await wT(tr(),["view",e,"version"],{timeout:Jh,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function xT(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Jh);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 vT(e){return e.versionCheck.type==="npm-registry"?Gh(e.versionCheck.package):xT(e.versionCheck.repo)}async function IT(){let e=await Gh("@ciandt-flow/cli");return e&&Ve(he,e)?(ra({currentVersion:he,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function ET(){let e=an().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=de.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<ST)return;let s=await vT(r);try{await bt({...t,lastChecked:new Date().toISOString()});}catch(i){yT.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ve(t.installedVersion,s)&&ti(r,"background").catch(()=>{});}));}async function uu(){let e=Wh();if(e===false)return;let t=bT();le__default.mkdirSync(oe__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 IT().catch(()=>null);n&&process.stdout.write(`
783
783
  \u26A0 @ciandt-flow/cli v${n} installing in background.
784
784
  Restart flow to apply the update.
785
785
 
786
- `);}await ET().catch(()=>{});}finally{await r().catch(()=>{});}}N();var TT=b("cli"),du=Kh(async()=>{Be("tui"),Vu("tui"),Wu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Eo("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Eo("sigterm",t,r).finally(()=>process.exit(143));}),await uu().catch(()=>{}),await mp().catch(t=>{TT.error(`Failed to init catalog registry: ${String(t)}`);}),await Gf();let{waitUntilExit:e}=render(jsx(zf,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});du.hook("preAction",async(e,t)=>{t!==du&&await uu().catch(()=>{});});try{await du.parseAsync();}catch(e){I(e instanceof Error?e.message:String(e)),L(1);}
786
+ `);}await ET().catch(()=>{});}finally{await r().catch(()=>{});}}N();var TT=b("cli"),du=Hh(async()=>{Be("tui"),Vu("tui"),Wu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Eo("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Eo("sigterm",t,r).finally(()=>process.exit(143));}),await uu().catch(()=>{}),await mp().catch(t=>{TT.error(`Failed to init catalog registry: ${String(t)}`);}),await zf();let{waitUntilExit:e}=render(jsx(Xf,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});du.hook("preAction",async(e,t)=>{t!==du&&await uu().catch(()=>{});});try{await du.parseAsync();}catch(e){I(e instanceof Error?e.message:String(e)),L(1);}