@ciandt-flow/cli 2.11.0-beta.53 → 2.11.1-beta.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +132 -132
  2. package/package.json +1 -8
  3. package/dist/ctxa.js +0 -160
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- import*as In from'crypto';import {randomUUID,createHash}from'crypto';import*as Te from'os';import Te__default,{tmpdir,homedir}from'os';import*as le from'path';import le__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ie from'fs';import ie__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 P from'chalk';import*as Hl from'readline';import {createInterface}from'readline';import za from'conf';import op,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Nw,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import qy from'jsonwebtoken';import lw from'proper-lockfile';import $w from'ink-big-text';import em from'ink-spinner';import*as Ht from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import FS from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import tc from'semver';import na from'yocto-spinner';import {Command,Option}from'commander';import {fileURLToPath}from'url';import {parse,stringify}from'yaml';var Kh=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 iu=(e,t)=>{for(var r in t)Kh(e,r,{get:t[r],enumerable:true});};var gr,me,Ia,po,yn,hr,va,au,Ea,Lt,fe,et,Zt,fs,wn,Sn,xn,bn,j=W(()=>{"use strict";gr="FLOW",me="flow-skills",Ia="flow-cli",po="internal",yn="external",hr={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"}},va=new Set(Object.keys(hr)),au={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Ea=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"}},fe="flow-claude-md-setup",et=5,Zt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,fs="https://flow.ciandt.com",wn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,Sn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",xn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,bn="Must be a valid email address (e.g. name@example.com)";});var gs,Vh,lu,mo,Ta=W(()=>{"use strict";gs="aes-256-gcm",Vh=16,lu=16,mo=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=In.randomBytes(Vh),n=In.createCipheriv(gs,this.key,r,{authTagLength:lu}),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:gs}}decrypt(t){if(t.algorithm!==gs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=In.createDecipheriv(gs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:lu});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Pa(e){return e.replace(zh,"").replace(Xh,"").replace(qh,"").replace(Wh,"Bearer ***").replace(Jh,"***").replace(Gh,"***").replace(/\r\n|\r|\n/g,"\\n")}var Wh,Jh,Gh,zh,Xh,qh,Ca=W(()=>{"use strict";Wh=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Jh=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Gh=/[A-Za-z0-9+/]{40,}={0,2}/g,zh=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Xh=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,qh=/\x1b/g;});function ys(e){return e||me}function cu(e,t,r){return Aa(ys(r),e,t)}function ka(e,t){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(t),"plugins","native",e)}function ws(e){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(e),".claude-plugin","marketplace.json")}function Wr(){return le.join(Te.homedir(),ht,"plugins","known_marketplaces.json")}function uu(e){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(e))}function du(){return le.join(Te.homedir(),hs,"cache","install.lock")}function pu(){return le.join(Te.homedir(),hs,"logs","flowsetup.log")}function Aa(e,t,r){return le.join(Te.homedir(),ht,"plugins","cache",e,t,r)}function Jr(e){let t=e==="global"?Te.homedir():process.cwd();return le.join(t,".claude","skills")}function fo(e){let t=e==="global"?Te.homedir():process.cwd();return le.join(t,".claude","skills-lock.json")}function Ss(e="user"){return e==="project"?le.join(process.cwd(),".opencode","plugins"):le.join(Te.homedir(),".config","opencode","plugins")}function mu(){return le.join(Te.homedir(),hs,"flow-catalogs.json")}function fu(){let e=process.env.FLOW_HOME??le.join(Te.homedir(),hs);return le.join(e,"config.json")}function xs(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"agents"):le.join(Te.homedir(),ht,"agents")}function vn(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"rules"):le.join(Te.homedir(),ht,"rules")}function Ra(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"hooks"):le.join(Te.homedir(),ht,"hooks")}var ht,hs,Oe=W(()=>{"use strict";j();ht=".claude",hs=".flow";});var Yh,Zh,bs,gu=W(()=>{"use strict";Oe();Yh=5*1024*1024,Zh=3,bs=class{filePath;constructor(){this.filePath=pu(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=le.dirname(this.filePath);ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ie.statSync(this.filePath).size>Yh){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ie.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=le.dirname(this.filePath),r=le.basename(this.filePath,".log"),n=ie.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Zh))ie.unlinkSync(le.join(t,o));}catch{}}};});var Is,hu=W(()=>{"use strict";Is=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
- `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var vs,yu=W(()=>{"use strict";vs=class{write(t){process.stdout.write(t.message+`
5
- `);}};});function Ma(){return Es}function wu(e){return $a.add(e),()=>{$a.delete(e);}}var Es,$a,Ts,La=W(()=>{"use strict";Es=[],$a=new Set;Ts=class{write(t){Es.push(t),Es.length>100&&Es.shift();for(let r of $a)r();}};});function Qh(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function Je(e,t){if(e==="tui"){let r=Qh();zr={context:e,transports:[new Ts,new bs],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?zr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?zr={context:e,transports:[new Is("cli")],minLevel:"debug",debugModules:null}:zr={context:e,transports:[new vs],minLevel:"info",debugModules:null};}function Su(){return zr.transports}function xu(e,t){let{debugModules:r,minLevel:n}=zr;return zr.context==="tui"&&r&&r!=="all"?r.has(t)?En[e]>=En.debug:En[e]>=En.warn:En[e]>=En[n]}var En,zr,_a=W(()=>{"use strict";gu();hu();yu();La();En={debug:0,info:1,warn:2,error:3},zr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Ps(e,t,r){if(!xu(e,t))return;let n={level:e,module:t,message:Pa(r),timestamp:new Date};for(let o of Su())o.write(n);}function x(e){let t=bu.get(e);if(t)return t;let r={debug:n=>Ps("debug",e,n),info:n=>Ps("info",e,n),warn:n=>Ps("warn",e,n),error:n=>Ps("error",e,n)};return bu.set(e,r),r}var bu,Iu=W(()=>{"use strict";Ca();_a();bu=new Map;});var R=W(()=>{"use strict";Iu();_a();Ca();});function ey(e){return typeof e=="object"&&e!==null&&Oa in e&&e[Oa]===true}function Ua(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Oa]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Da.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(ey(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Da.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Da.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Da,Oa,Na=W(()=>{"use strict";R();Da=x("encryption"),Oa="__encrypted__";});var Ba,ny,yt,Tn,Fa=W(()=>{"use strict";R();Ba=promisify(execFile),ny=promisify(exec),yt=x("encryption:macos-keyvault"),Tn=class{static async isAvailable(){try{let{stdout:t}=await ny("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 Ba("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 Ba("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 Ba("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 Y(e){process.stdout.write(P.green(` \u2713 ${w(e)}
2
+ import*as In from'crypto';import {randomUUID,createHash}from'crypto';import*as Te from'os';import Te__default,{tmpdir,homedir}from'os';import*as le from'path';import le__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ie from'fs';import ie__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 P from'chalk';import*as Kl from'readline';import {createInterface}from'readline';import Ga from'conf';import np,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Uw,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Xy from'jsonwebtoken';import aw from'proper-lockfile';import Rw from'ink-big-text';import Qp from'ink-spinner';import*as Ht from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import BS from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import ec from'semver';import na from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var jh=Object.defineProperty;var J=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var su=(e,t)=>{for(var r in t)jh(e,r,{get:t[r],enumerable:true});};var gr,pe,xa,po,yn,hr,Ia,iu,va,Lt,me,tt,Zt,fs,wn,Sn,bn,xn,j=J(()=>{"use strict";gr="FLOW",pe="flow-skills",xa="flow-cli",po="internal",yn="external",hr={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"}},Ia=new Set(Object.keys(hr)),iu={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},va=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"}},me="flow-claude-md-setup",tt=5,Zt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,fs="https://flow.ciandt.com",wn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,Sn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",bn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,xn="Must be a valid email address (e.g. name@example.com)";});var gs,Hh,au,mo,Ea=J(()=>{"use strict";gs="aes-256-gcm",Hh=16,au=16,mo=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=In.randomBytes(Hh),n=In.createCipheriv(gs,this.key,r,{authTagLength:au}),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:gs}}decrypt(t){if(t.algorithm!==gs)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=In.createDecipheriv(gs,this.key,Buffer.from(t.iv,"hex"),{authTagLength:au});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Ta(e){return e.replace(Gh,"").replace(zh,"").replace(Xh,"").replace(Vh,"Bearer ***").replace(Jh,"***").replace(Wh,"***").replace(/\r\n|\r|\n/g,"\\n")}var Vh,Jh,Wh,Gh,zh,Xh,Pa=J(()=>{"use strict";Vh=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Jh=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Wh=/[A-Za-z0-9+/]{40,}={0,2}/g,Gh=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,zh=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Xh=/\x1b/g;});function ys(e){return e||pe}function lu(e,t,r){return ka(ys(r),e,t)}function Ca(e,t){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(t),"plugins","native",e)}function ws(e){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(e),".claude-plugin","marketplace.json")}function Jr(){return le.join(Te.homedir(),ht,"plugins","known_marketplaces.json")}function cu(e){return le.join(Te.homedir(),ht,"plugins","marketplaces",ys(e))}function uu(){return le.join(Te.homedir(),hs,"cache","install.lock")}function du(){return le.join(Te.homedir(),hs,"logs","flowsetup.log")}function ka(e,t,r){return le.join(Te.homedir(),ht,"plugins","cache",e,t,r)}function Wr(e){let t=e==="global"?Te.homedir():process.cwd();return le.join(t,".claude","skills")}function fo(e){let t=e==="global"?Te.homedir():process.cwd();return le.join(t,".claude","skills-lock.json")}function Ss(e="user"){return e==="project"?le.join(process.cwd(),".opencode","plugins"):le.join(Te.homedir(),".config","opencode","plugins")}function pu(){return le.join(Te.homedir(),hs,"flow-catalogs.json")}function mu(){let e=process.env.FLOW_HOME??le.join(Te.homedir(),hs);return le.join(e,"config.json")}function bs(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"agents"):le.join(Te.homedir(),ht,"agents")}function vn(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"rules"):le.join(Te.homedir(),ht,"rules")}function Aa(e="user"){return e==="project"||e==="local"?le.join(process.cwd(),ht,"hooks"):le.join(Te.homedir(),ht,"hooks")}var ht,hs,Oe=J(()=>{"use strict";j();ht=".claude",hs=".flow";});var qh,Yh,xs,fu=J(()=>{"use strict";Oe();qh=5*1024*1024,Yh=3,xs=class{filePath;constructor(){this.filePath=du(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=le.dirname(this.filePath);ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ie.statSync(this.filePath).size>qh){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ie.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=le.dirname(this.filePath),r=le.basename(this.filePath,".log"),n=ie.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Yh))ie.unlinkSync(le.join(t,o));}catch{}}};});var Is,gu=J(()=>{"use strict";Is=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
4
+ `);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};});var vs,hu=J(()=>{"use strict";vs=class{write(t){process.stdout.write(t.message+`
5
+ `);}};});function $a(){return Es}function yu(e){return Ra.add(e),()=>{Ra.delete(e);}}var Es,Ra,Ts,Ma=J(()=>{"use strict";Es=[],Ra=new Set;Ts=class{write(t){Es.push(t),Es.length>100&&Es.shift();for(let r of Ra)r();}};});function Zh(){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 We(e,t){if(e==="tui"){let r=Zh();zr={context:e,transports:[new Ts,new xs],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?zr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?zr={context:e,transports:[new Is("cli")],minLevel:"debug",debugModules:null}:zr={context:e,transports:[new vs],minLevel:"info",debugModules:null};}function wu(){return zr.transports}function Su(e,t){let{debugModules:r,minLevel:n}=zr;return zr.context==="tui"&&r&&r!=="all"?r.has(t)?En[e]>=En.debug:En[e]>=En.warn:En[e]>=En[n]}var En,zr,La=J(()=>{"use strict";fu();gu();hu();Ma();En={debug:0,info:1,warn:2,error:3},zr={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function Ps(e,t,r){if(!Su(e,t))return;let n={level:e,module:t,message:Ta(r),timestamp:new Date};for(let o of wu())o.write(n);}function b(e){let t=bu.get(e);if(t)return t;let r={debug:n=>Ps("debug",e,n),info:n=>Ps("info",e,n),warn:n=>Ps("warn",e,n),error:n=>Ps("error",e,n)};return bu.set(e,r),r}var bu,xu=J(()=>{"use strict";Pa();La();bu=new Map;});var R=J(()=>{"use strict";xu();La();Pa();});function Qh(e){return typeof e=="object"&&e!==null&&Da in e&&e[Da]===true}function Oa(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Da]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return _a.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Qh(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return _a.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return _a.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var _a,Da,Ua=J(()=>{"use strict";R();_a=b("encryption"),Da="__encrypted__";});var Na,ry,yt,Tn,Ba=J(()=>{"use strict";R();Na=promisify(execFile),ry=promisify(exec),yt=b("encryption:macos-keyvault"),Tn=class{static async isAvailable(){try{let{stdout:t}=await ry("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 Na("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 Na("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 Na("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 Y(e){process.stdout.write(P.green(` \u2713 ${w(e)}
6
6
  `));}function v(e){process.stderr.write(P.red(` \u2717 ${w(e)}
7
- `));}function b(e){process.stdout.write(P.cyan(` \u2139 ${w(e)}
7
+ `));}function x(e){process.stdout.write(P.cyan(` \u2139 ${w(e)}
8
8
  `));}function yr(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(`
9
9
  `),process.stdout.write(` ${P.bold(i(e))}
10
10
  `),process.stdout.write(` ${P.dim(s)}
11
11
  `);for(let a of r)process.stdout.write(` ${i(a)}
12
12
  `);process.stdout.write(`
13
13
  `);}function wr(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function ge(e){process.stdout.write(JSON.stringify(e)+`
14
+ `);}function fe(e){process.stdout.write(JSON.stringify(e)+`
15
15
  `);}function Ue(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function Q(e){return e instanceof Error?e.message:String(e)}function _t(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 ly(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 cy(e){let t=Hl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var ja,Ka,ay,oe,Sr,Ha=W(()=>{"use strict";R();N();ja=promisify(execFile),Ka=promisify(exec),ay=[{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"}],oe=x("encryption:linux-keyvault");Sr=class e{static async isAvailable(){try{let{stdout:t}=await Ka("command -v secret-tool");oe.debug(`secret-tool found at: ${t.trim()}`);}catch{return oe.debug("secret-tool binary not found in PATH"),!1}try{return await ja("secret-tool",["lookup","service","__flow_connectivity_check__"]),oe.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(oe.debug(`Secret Service D-Bus not available: ${n}`),!1):(oe.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of ay)try{return await Ka(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;oe.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 oe.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await cy(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return oe.info(`Running: ${t.command}`),await ly("Installing secret-tool...",()=>Ka(t.command)),e.isAvailable()}catch{return oe.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{oe.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await ja("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return oe.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return oe.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){oe.debug(`Storing secret: service=${t}, account=${r}`),oe.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),oe.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),oe.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?(oe.debug("secret-tool store succeeded"),o()):(oe.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=>{oe.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return oe.debug(`Deleting secret: service=${t}, account=${r}`),await ja("secret-tool",["clear","service",t,"account",r]),oe.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return oe.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Wa(e,t){return `${e}:${t}`}function ho(e){return e.replace(/'/g,"''")}function Cs(e){return ["-NoProfile","-NonInteractive","-Command",e]}function hy(e){return `Add-Type -TypeDefinition @'
16
+ `);}function Q(e){return e instanceof Error?e.message:String(e)}function _t(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var N=J(()=>{"use strict";});async function ay(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 ly(e){let t=Kl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var Fa,ja,iy,oe,Sr,Ka=J(()=>{"use strict";R();N();Fa=promisify(execFile),ja=promisify(exec),iy=[{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"}],oe=b("encryption:linux-keyvault");Sr=class e{static async isAvailable(){try{let{stdout:t}=await ja("command -v secret-tool");oe.debug(`secret-tool found at: ${t.trim()}`);}catch{return oe.debug("secret-tool binary not found in PATH"),!1}try{return await Fa("secret-tool",["lookup","service","__flow_connectivity_check__"]),oe.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(oe.debug(`Secret Service D-Bus not available: ${n}`),!1):(oe.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of iy)try{return await ja(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;oe.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 oe.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await ly(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return oe.info(`Running: ${t.command}`),await ay("Installing secret-tool...",()=>ja(t.command)),e.isAvailable()}catch{return oe.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{oe.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Fa("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return oe.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return oe.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){oe.debug(`Storing secret: service=${t}, account=${r}`),oe.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),oe.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),oe.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?(oe.debug("secret-tool store succeeded"),o()):(oe.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=>{oe.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return oe.debug(`Deleting secret: service=${t}, account=${r}`),await Fa("secret-tool",["clear","service",t,"account",r]),oe.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return oe.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Va(e,t){return `${e}:${t}`}function ho(e){return e.replace(/'/g,"''")}function Cs(e){return ["-NoProfile","-NonInteractive","-Command",e]}function gy(e){return `Add-Type -TypeDefinition @'
17
17
  ${Ja}
18
18
  '@
19
- [FlowCredManager]::Read('${ho(e)}')`}function yy(e,t,r){return `Add-Type -TypeDefinition @'
19
+ [FlowCredManager]::Read('${ho(e)}')`}function hy(e,t,r){return `Add-Type -TypeDefinition @'
20
20
  ${Ja}
21
21
  '@
22
- [FlowCredManager]::Write('${ho(e)}', '${ho(t)}', '${ho(r)}')`}function wy(e){return `Add-Type -TypeDefinition @'
22
+ [FlowCredManager]::Write('${ho(e)}', '${ho(t)}', '${ho(r)}')`}function yy(e){return `Add-Type -TypeDefinition @'
23
23
  ${Ja}
24
24
  '@
25
- [FlowCredManager]::Delete('${ho(e)}')`}async function ks(e){return py("powershell.exe",e)}var py,wt,Va,my,fy,gy,Ja,Pn,Ga=W(()=>{"use strict";R();py=promisify(execFile),wt=x("encryption:windows-keyvault"),Va=1,my=1,fy=2,gy=3;Ja=`
25
+ [FlowCredManager]::Delete('${ho(e)}')`}async function ks(e){return dy("powershell.exe",e)}var dy,wt,Ha,py,my,fy,Ja,Pn,Wa=J(()=>{"use strict";R();dy=promisify(execFile),wt=b("encryption:windows-keyvault"),Ha=1,py=1,my=2,fy=3;Ja=`
26
26
  using System;
27
27
  using System.Runtime.InteropServices;
28
28
  using System.Text;
@@ -58,7 +58,7 @@ public class FlowCredManager {
58
58
 
59
59
  public static string Read(string target) {
60
60
  IntPtr credPtr;
61
- if (!CredRead(target, ${Va}, 0, out credPtr)) return "";
61
+ if (!CredRead(target, ${Ha}, 0, out credPtr)) return "";
62
62
  try {
63
63
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
64
64
  if (cred.CredentialBlobSize <= 0) return "";
@@ -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[] { ${fy}, ${gy}, ${my} };
75
+ int[] persistLevels = new int[] { ${my}, ${fy}, ${py} };
76
76
  int lastErr = 0;
77
77
  try {
78
78
  foreach (int persist in persistLevels) {
@@ -80,7 +80,7 @@ public class FlowCredManager {
80
80
  try {
81
81
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
82
82
  var cred = new CREDENTIAL();
83
- cred.Type = ${Va};
83
+ cred.Type = ${Ha};
84
84
  cred.TargetName = targetPtr;
85
85
  cred.CredentialBlobSize = bytes.Length;
86
86
  cred.CredentialBlob = blobPtr;
@@ -98,172 +98,172 @@ public class FlowCredManager {
98
98
  }
99
99
 
100
100
  public static bool Delete(string target) {
101
- return CredDelete(target, ${Va}, 0);
101
+ return CredDelete(target, ${Ha}, 0);
102
102
  }
103
103
  }
104
104
  `;Pn=class{static async isAvailable(){try{let{stdout:t}=await ks(Cs('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=Wa(t,r);wt.debug(`Looking up secret: target=${n}`);let o=hy(n),{stdout:s}=await ks(Cs(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=Wa(t,r);wt.debug(`Storing secret: target=${o}`);let s=yy(o,n,r),{stdout:i}=await ks(Cs(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=Wa(t,r);wt.debug(`Deleting secret: target=${n}`);let o=wy(n),{stdout:s}=await ks(Cs(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 Iy(){let e=`${Te.hostname()}${Te.userInfo().username}`;return In.scryptSync(e,xy,Sy)}function vy(){let e=Iy(),t=new mo(e),r=Ua(t);return new za({projectName:Xa,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function As(){return Rs||(Rs=vy()),Rs}var Sy,xy,Xa,by,Rs,Ge,yo=W(()=>{"use strict";Ta();Na();Sy=32,xy="flow-plugins-cli-fallback",Xa="flow-plugins-cli-fallback",by={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)"};Rs=null;Ge=class{warned=!1;async getSecret(t,r){return As().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=by[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=Va(t,r);wt.debug(`Looking up secret: target=${n}`);let o=gy(n),{stdout:s}=await ks(Cs(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=Va(t,r);wt.debug(`Storing secret: target=${o}`);let s=hy(o,n,r),{stdout:i}=await ks(Cs(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=Va(t,r);wt.debug(`Deleting secret: target=${n}`);let o=yy(n),{stdout:s}=await ks(Cs(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 xy(){let e=`${Te.hostname()}${Te.userInfo().username}`;return In.scryptSync(e,Sy,wy)}function Iy(){let e=xy(),t=new mo(e),r=Oa(t);return new Ga({projectName:za,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function As(){return Rs||(Rs=Iy()),Rs}var wy,Sy,za,by,Rs,Ge,yo=J(()=>{"use strict";Ea();Ua();wy=32,Sy="flow-plugins-cli-fallback",za="flow-plugins-cli-fallback",by={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)"};Rs=null;Ge=class{warned=!1;async getSecret(t,r){return As().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=by[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;}As().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=As(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return As().path}static hasExistingData(){try{let t=new za({projectName:Xa});return ie.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new za({projectName:Xa});ie.rmSync(t.path,{force:!0});}catch{}Rs=null;}};});async function qa(){if(Ge.hasExistingData())return new Ge;switch(process.platform){case "darwin":return await Tn.isAvailable()?new Tn:new Ge;case "linux":return await Sr.isAvailable()?new Sr:await Sr.ensureInstalled()?new Sr:new Ge;case "win32":return await Pn.isAvailable()?new Pn:new Ge;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Cu=W(()=>{"use strict";Fa();Ha();Ga();yo();});var ku=W(()=>{"use strict";Ta();Na();Cu();Fa();Ha();Ga();yo();});async function xr(){return Ls||(Ls=qa()),Ls}function _s(){Ls=null;}async function ee(){let t=await(await xr()).getSecret(Qt,Ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function br(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 Au.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await xr()).setSecret(Qt,Ya,JSON.stringify(e));}async function Ru(){let e=await xr();await e.deleteSecret(Qt,Ya),await e.deleteSecret(Qt,Za),await e.deleteSecret(Qt,Qa);}async function $u(){return (await xr()).getStoragePath()}async function Mu(e){await(await xr()).setSecret(Qt,Za,JSON.stringify(e));}async function Ds(){let t=await(await xr()).getSecret(Qt,Za);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Os(e){await(await xr()).setSecret(Qt,Qa,JSON.stringify(e));}async function Cn(){let t=await(await xr()).getSecret(Qt,Qa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ir(){let e=await Ds();return e?new Date(e.expiresAt)>new Date:false}function Dt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Au.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Au,Qt,Ya,Za,Qa,Ls,Pe=W(()=>{"use strict";ku();R();Au=x("config:credentials"),Qt="flow-plugins-cli",Ya="credentials",Za="token-cache",Qa="user-info",Ls=null;});function kn(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 Us=W(()=>{"use strict";});function Ey(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 el(e){if(Lu.some(r=>r.test(e)))return true;let t=Ey(e);return !!(t&&Lu.some(r=>r.test(t)))}function Ty(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ot(e,t){let r=Ty(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&&el(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Lu,Xr=W(()=>{"use strict";Lu=[/^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 ky(e){if(!Zt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Ay(e){if(e instanceof HTTPError){let t=e.response.status;tl.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&&_u[r]?new Error(_u[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?(tl.debug(`Non-HTTP error during authentication: ${e.message}`),e):(tl.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function qr(e){let t=Ot("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");ky(e.tenant);let r;try{r=await op.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Ay(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await br(e),await Mu({accessToken:r.access_token,expiresAt:n});let o=kn(r.access_token);await Os({sub:o.sub,name:o.name,email:o.email});}var tl,_u,Ns=W(()=>{"use strict";Pe();Us();Xr();R();j();tl=x("api:auth");_u={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 Ut(){if(await Ir()){let n=await Ds();if(n)return n.accessToken}Du.debug("Token expired or missing, re-authenticating...");let t=await ee();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ge.clearFallbackFile(),_s(),await qr(t);let r=await Ds();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Du.debug("Token refreshed successfully"),r.accessToken}var Du,An=W(()=>{"use strict";Pe();Ns();yo();R();Du=x("lib:tokenProvider");});function Kt(){return op.create({prefix:Ot("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ut();e.headers.set("Authorization",`Bearer ${t}`);let r=await ee();r?.tenant&&Zt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Mo=W(()=>{"use strict";Xr();Pe();An();j();});function qd(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 Un(e,t,r){let n=Kt(),o=qd({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function Yd(e,t={}){let r=Kt(),n=qd(t);return n?r.head(e,n):r.head(e)}async function Nn(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 El=W(()=>{"use strict";Mo();});function Lo(e){if(!e||!TS.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Bn(e){return PS.test(e)}function Fn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Pl(e){if(!CS.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 jn(e,t){let r=Fn(e);Pl(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function mi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!kS.test(t)&&!AS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var TS,PS,CS,kS,AS,Mr=W(()=>{"use strict";TS=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;PS=/^[^@]+@[^@]+$/;CS=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;kS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,AS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var ep={};iu(ep,{FlowApiAdapter:()=>Kn});var RS,Kn,Cl=W(()=>{"use strict";Mo();El();R();Mr();RS=x("catalog.flow-api"),Kn=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 Un("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 Nn(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){Lo(t);try{return await Un(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Nn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await Kt().head("v1/plugins/catalog"),RS.debug("ping ok"),!0}catch{return !1}}};});function MS(){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 rp(){return tp??=MS(),tp}var tp,np=W(()=>{"use strict";});var ip={};iu(ip,{GitRepoAdapter:()=>Hn});function sp(e,t){if(!LS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var LS,Hn,kl=W(()=>{"use strict";np();Xr();LS=/^[a-zA-Z0-9_.-]+$/;Hn=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(el(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return sp(a,"owner"),sp(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 op.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 op.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 rp();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}}};});j();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(va),origins:new Set(Ea)},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(va)},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(Ea)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Pe();An();Us();j();Xr();R();var Bs=x("api:metrics");function Ou(){return Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Uu(e,t,r){return op.post(e,{json:t,headers:r})}async function $y(e){let t=await Cn();if(t)return t;let r=kn(e),n={sub:r.sub,name:r.name,email:r.email};return await Os(n),n}async function T(e,t){let r=await Ut(),n=await $y(r),o=await ee();if(!Zt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ia,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Uu(Ou(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Bs.debug(`Metrics event sent: ${e}`);}catch(i){throw Bs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Nu(e,t,r){try{let n=r&&Zt.test(r)?r:"unknown",o={action:e,booster:Ia,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Uu(Ou(),o,{FlowTenant:n}),Bs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Bs.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_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 My={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},St={...My};function Bu(e){let t=Date.now();St={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Yr(e){St.currentStep=e,St.stepStart=Date.now();}function te(){return {...St}}function vr(){return St.sessionStart===0?0:Date.now()-St.sessionStart}function Zr(){return St.stepStart===0?0:Date.now()-St.stepStart}function Fu(){St.tuiSessionStart=Date.now();}function ju(){return St.tuiSessionStart===0?0:Date.now()-St.tuiSessionStart}R();var Ly=3e3,_y=x("abandonment");async function Fs(e){let{currentStep:t,sessionStart:r}=te();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:vr()};try{await Promise.race([T(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Ly))]);}catch(o){_y.warn(`Abandonment event failed: ${String(o)}`);}}function Ku(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var Dy=3e3,Oy=x("session-end");async function So(e,t,r){let n=ju(),s=[T(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Fs(e));try{await Ku(Promise.all(s).then(()=>{}),Dy);}catch(i){Oy.warn(`Session end event failed: ${String(i)}`);}}var Fy=2e3;function Vu(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),So("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Fy);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Vy=16;function Wu({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(Vy)}),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]})})]})}j();function Ju({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();xn.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:bn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}j();function Gu({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[gr," \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"})]})]})}j();function zu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[gr," \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 rt=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})}));Ns();j();function tn(){return le__default.join(Te__default.homedir(),".claude","settings.json")}function qu(e){return `${(e&&e.trim().length>0?e.trim():fs).replace(/\/+$/,"")}/flow-litellm/`}function Po(){let e=tn();if(!ie__default.existsSync(e))return {status:"missing"};let t=ie__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Ks(e){let t=tn();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,t);}function Yu(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 ll(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 Zu(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 Yy=3600,rn=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Co(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 Zy(e){return qy.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Yy})}function Hs(e,t={}){let r=Po();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new rn;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?ll(r.settings):null,s=r.status==="ok"?Zu(r.settings):null,i=t.jwtOverride??Zy(e),a=qu(e.customUrl),l=Yu(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Vs(e){Ks(e.merged);}function Qu(){let e=Po();return e.status!=="ok"?false:ll(e.settings)!==null}Pe();Oe();function Qy(){let e=fu();if(!ie__default.existsSync(e))return {};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var cl=null;function ew(){return cl===null&&(cl=Qy()),cl}function Pr(){return !!ew().ENABLE_EXPERIMENTAL_BETAS}j();function ow(){return ce.filter(e=>e.platforms[process.platform]?.status==="supported")}function td(e){let t=ow();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Ws={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=le__default.join(Te__default.homedir(),".claude","settings.json"),r=ie__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??fs),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"}},sw={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},ce=Pr()?[Ws,sw]:[Ws];Pe();R();var cw=x("moduleState");function Gs(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"modules.json")}var uw={retries:5,minTimeout:50};async function rd(e,t){ie__default.mkdirSync(le__default.dirname(e),{recursive:true});let r=await lw.lock(e+".lock",{realpath:false,retries:uw});try{return await t()}finally{await r();}}function nd(){let e=Gs();if(!ie__default.existsSync(e))return [];try{let t=JSON.parse(ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(cw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ie__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ie__default.rmSync(e,{force:true}),[]}}function nn(){return nd()}function od(e){let t=Gs();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ie__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,t);}function nt(e){return nn().find(t=>t.alias===e)??null}async function xt(e){let t=Gs();await rd(t,async()=>{let r=nd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,od(r);});}async function on(){let e=Gs();ie__default.existsSync(e)||await rd(e,async()=>{ie__default.existsSync(e)||od([]);});}var mw=promisify(execFile);function Cr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Bt(e){let t=process.platform==="win32"?"where":"which";try{return await mw(t,[e]),!0}catch{return false}}function er(){return process.platform==="win32"?"npm.cmd":"npm"}var sd=promisify(execFile),$n=class{type="npm";async isAvailable(){return Bt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Cr(t,"npm");if(!r)return null;try{let{stdout:n}=await sd(er(),["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=Cr(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 sd(er(),["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),ww=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Xs=class{type="homebrew";async isAvailable(){return Bt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Cr(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=Cr(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(ww);return n?n[2]:null}catch{return null}}};var Mn=promisify(execFile),ad=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ld(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"bin")}var qs=class{type="curl";async isAvailable(){return Bt("curl")}async install(t){let r=Date.now(),n=Cr(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=le__default.join(ld(),le__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Mn(n,["--version"]),s=o.match(ad);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=le__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Mn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ie__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ie__default.chmodSync(s,448),await Mn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{ie__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ld(),i=le__default.join(s,le__default.basename(n.binaryName)),a=false;try{if(ie__default.mkdirSync(s,{recursive:!0}),a=!0,await Mn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ie__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Mn(i,["--version"]),c=u.match(ad);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ie__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=le__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Mn("curl",["-L","--fail","-o",n,r]);let o=ie__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ie__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{ie__default.unlinkSync(n);}catch{}}}};R();var cd="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(cd=e.version);}catch{}var ue=cd;var $e=x("moduleInstaller");function jt(e){switch(e){case "npm":return new $n;case "homebrew":return new Xs;case "curl":return new qs}}async function ko(e,t,r){try{await T(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){$e.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ar(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"){$e.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 ko(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 ko(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 ko(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=jt(r),u=false;try{u=await l.isAvailable();}catch(d){$e.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 ko(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await T(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:t});}catch(d){$e.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);$e.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await xt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await T(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){$e.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Tw(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await ko(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Tw(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 ee(),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 $e.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,$e.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&$e.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&$e.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Ys(e,t){let r=Date.now(),n=nt(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=jt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await T(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ue,trigger:"command"});}catch(a){$e.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);$e.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await xt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await T(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){$e.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await T(E.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){$e.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await T(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){$e.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var Zs=x("flowAiObsSetup");async function Qs(e,t){try{if(!await new $n().isAvailable().catch(()=>!1))return Zs.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ar(Ws,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Zs.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Zs.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Zs.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function ud(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 Pw=x("useAuthSetup");function dd(){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),f=useRef(0),h=useRef(false),{setCredentials:y,setJustAuthenticated:I}=rt(),M=()=>{m("fields"),g(null),t(""),r.current=null,n.current=null,o.current=null;},D=()=>{T(E.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:vr(),interface:"tui"}).catch(()=>{});},C=async H=>{h.current=true;let X={...r.current,customUrl:n.current??void 0};try{H&&Vs(H),await br(X);}catch(J){l(J instanceof Error?J.message:"Failed to persist credentials"),M(),h.current=false;return}let{clientSecret:A,...F}=X;y(F),I(true),D(),await Qs(n.current,o.current).catch(J=>Pw.warn(`installFlowAiObs threw unexpectedly: ${String(J)}`)),ei({starterKit:F.starterKit});},$=async()=>C(),O=async H=>C(H),U=H=>{try{let X={...r.current,customUrl:n.current??void 0};return Hs(X,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(X){return X instanceof rn?(m("malformedConfirm"),null):(l(X instanceof Error?X.message:"Failed to read settings.json"),m("fields"),null)}},ne=()=>{let H=U(true);H&&(g(H),O(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let X;try{X=Co(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=X,m("customUrl");},V=H=>{n.current=H,m("email");},re=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Dt(H),c(true),l(null),f.current+=1;try{await qr(r.current);let X=U(!1);X&&(g(X),m("preview"));}catch(X){let A=X instanceof Error?X.message:"Authentication failed";l(A),Nu(E.CLI_AUTH_FAILED,{error_code:ud(X),attempt:f.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:h,setJwtValue:t,setJwtError:i,cancelToFields:M,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:re,commitAndProceed:O,skipJwtAndProceed:$,planPersistOverwrite:ne}}j();N();function pd(){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:f}=dd(),[h,y]=useState("confirm"),[I,M]=useState(""),D=useRef(""),[C,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(y("confirm"),D.current="",M(""),$(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?f():U.escape&&u();return}if(o==="customUrl"){if(h==="confirm")O==="y"||O==="Y"?y("input"):(O==="n"||O==="N"||U.return)&&d(null);else if(U.escape)D.current="",M(""),y("confirm");else if(U.return){let ne=D.current.trim();ne.length>0&&wn.test(ne)?($(false),d(ne)):ne.length>0&&$(true);}else U.backspace||U.delete?(D.current=D.current.slice(0,-1),M(D.current)):O&&!U.ctrl&&!U.meta&&(D.current=D.current+O,M(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:[gr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:I}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:Sn}),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:[gr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Ju,{onConfirm:m})]}):o==="preview"&&s?jsx(Gu,{plan:s}):o==="malformedConfirm"?jsx(zu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[gr," \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(Wu,{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 _n(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx($w,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ue]})})]})}var hd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],se=Pr()?hd:hd.slice(0,3);function Mw(e){return se.findIndex(t=>t.id===e)}function pl(e,t,r){let n=Mw(r.activeTab);if(t.rightArrow||t.tab){let o=se[(n+1)%se.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=se[(n-1+se.length)%se.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:se[n]?.focus??"list"}]:[]}var Sd={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function xd({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:se.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Sd[r]} (${e})`:Sd[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var ze=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Id(){let e=S(i=>i.focus),t=ze(i=>i.query),r=ze(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..."})]})}j();var vd=Object.keys(hr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...hr[e]})),Ed=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...au[e]}));function Td(){let e=S(n=>n.catalogFilters),t=vd.every(n=>e.types.has(n.type)),r=Ed.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"]})]}),vd.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"]})]}),Ed.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)})]})}j();function Pd({type:e}){let{label:t,color:r}=hr[e];return jsx(Text,{color:r,children:t})}j();function Ad({origin:e}){return e===po?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ri=Nw.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(Pd,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ad,{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 ",_t(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Dn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}j();function Md({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Dn,{message:t});let n=Math.max(0,r-Math.floor(et/2)),o=Math.min(e.length,n+et);o===e.length&&(n=Math.max(0,o-et));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(ri,{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 Dd({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}j();function Ud({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(Dn,{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(et/2)),u=Math.min(n.length,l+et);u===n.length&&(l=Math.max(0,u-et));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(Dd,{label:p.label,pathHint:p.pathHint},p.key):jsx(ri,{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 Jw={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Gw({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Id,{}),jsx(Td,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Jw[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Ud,{groups:n,emptyMessage:r}):jsx(Md,{items:e,emptyMessage:r})]})}function Nd({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(Gw,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var qw={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 ni(){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:[qw[e],t?" | Ctrl+D: debug log":""]})})}N();function Bd({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 oi({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(em,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Sl(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Hd=20;function si(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Hd),s="\u2588".repeat(o)+"\u2591".repeat(Hd-o),i=`${Sl(e)} / ${Sl(t)}`;return {bar:s,percent:n,label:i}}function ii({received:e,total:t}){let{bar:r,percent:n,label:o}=si(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function ai({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 ot({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))})]})}j();var vl=Object.entries(Lt),Gd=[...vl.map(([,e])=>e.actionLabel),"Cancel"],zd=Object.fromEntries(vl.map(([,e])=>[e.actionLabel,e.description]));function Xd(e){let t=vl.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var dS=x("provider.registry"),pS=3e4,ci=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()+pS}),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"&&dS.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 mS={user:"global",project:"project",local:"local"};function ui(e){return e?mS[e]:"global"}var Xe=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},$r=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};Mo();El();R();var hS=x("catalog.registry"),di=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);hS.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()]}};Oe();var ES={retries:5,minTimeout:50};async function Tl(e,t){mkdirSync(dirname(e),{recursive:true});let r=await lw.lock(e+".lock",{realpath:false,retries:ES});try{return await t()}finally{await r();}}var pi=class{filePath;constructor(t){this.filePath=t??mu();}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 Tl(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 Tl(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Tl(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));});}};Cl();var he=new di,rr=new pi,_S=["flow-harness"];function DS(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?_S:e.split(",").map(t=>t.trim()).filter(Boolean)}he.register(new Kn);for(let e of DS())he.register(new Kn(e));var ap=false;async function lp(){if(ap)return;ap=true;let e=await rr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(kl(),ip));for(let r of e)he.register(new t(r.id,r.name,r.source));}Mr();function cp(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 US=x("api:actions"),up=2;async function nr(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Cl(),ep));return new t(e).fetchItems()}return he.fetchAll()}async function dp(){return he.fetchAllWithErrors()}async function Vn(e,t){Lo(e);try{return await Un(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Nn(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 NS(e,t){try{let n=(await Yd(`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){US.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function pp(e,t,r){Lo(e);try{let n=await NS(e,r),o=cp(n),s=await Un(`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:f}=await d.read();if(g)break;if(p+=f.byteLength,u&&p>l*up)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*up}`);m.push(f),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 Nn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function fi(){try{let{profiles:e}=await Kt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}Oe();Oe();async function mp(e,t){let r=le.resolve(t);await Ht.mkdir(r,{recursive:true});let n=le.join(le.dirname(r),`${randomUUID()}.zip`);try{await Ht.writeFile(n,e);let o=await FS.Open.file(n),s=le.normalize(r+le.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=le.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(le.resolve(le.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ht.unlink(n);}catch{}}}async function Al(e){await Ht.rm(e,{recursive:true,force:true});}async function Lr(){let e=du();await Ht.mkdir(le.dirname(e),{recursive:true});try{await Ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await lw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();j();function HS(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||me,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function hp(e){let t=ws(e);if(!ie__default.existsSync(t))return null;try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return null}}function VS(e){let t=hp(e);if(t)return t;let r=HS(e),n=ws(e);return ie__default.mkdirSync(le__default.dirname(n),{recursive:true}),Rl(r,e),r}function Rl(e,t){let r=ws(t),n=`${r}.${randomUUID()}.tmp`;ie__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(n,r);}function WS(e){let t=e||me,r=Wr(),n={};try{ie__default.existsSync(r)&&(n=JSON.parse(ie__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:uu(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,r);}function yp(e,t,r){st(e.name),WS(r);let n=ka(e.name,r);ie__default.mkdirSync(le__default.dirname(n),{recursive:true});try{ie__default.lstatSync(n),ie__default.rmSync(n,{recursive:!0,force:!0});}catch{}ie__default.cpSync(t,n,{recursive:true,dereference:true});let o=VS(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}),Rl(o,r));}function $l(e,t){st(e);let r=ka(e,t);try{ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=hp(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Rl(n,t);}N();R();var GS=x("mcpConfigReader"),zS=500,XS=512;function qS(){return le__default.join(Te__default.homedir(),".claude.json")}function YS(){return le__default.join(process.cwd(),".mcp.json")}function Sp(e){if(!ie__default.existsSync(e))return null;try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return GS.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function _o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ml(e){if(!_o(e))return {};let t=e.mcpServers;return _o(t)?t:{}}function Ll(e,t){return Object.keys(e).slice(0,zS).map(n=>({name:w(n.slice(0,XS)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function bp(){let e=[],t=qS(),r=Sp(t);if(_o(r)){let a=r,l=Ml(a);e.push(...Ll(l,"user"));let u=process.cwd();if(_o(a.projects)){let c=a.projects[u];if(_o(c)){let d=Ml(c);e.push(...Ll(d,"local"));}}}let n=YS(),o=Sp(n),s=Ml(o);e.push(...Ll(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();var it=x("storage");async function QS(e,t,r){try{await T(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:te().interfaceType});}catch(n){it.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function ex(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;T(n,{tool_id:e,source:r,interface:te().interfaceType}).catch(o=>it.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ul(){return le__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function tx(){return le__default.join(Te__default.homedir(),".claude","plugins")}function gi(e){let t;try{t=ie__default.realpathSync(e);}catch{t=le__default.resolve(e);}let r=le__default.resolve(tx()),n=le__default.resolve(le__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+le__default.sep),s=t.startsWith(n+le__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function vp(e="user"){return e==="local"?le__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?le__default.join(process.cwd(),".claude","settings.json"):le__default.join(Te__default.homedir(),".claude","settings.json")}function Ce(){let e=Ul();if(!ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Nl(){let e=Ul();try{let t=await ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function rx(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ep(e,t){try{ie__default.mkdirSync(le__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,e);}catch(r){throw rx(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){Ep(Ul(),e);}function Do(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function nx(e,t){let r=le__default.join(e,".claude-plugin"),n=le__default.join(r,"plugin.json");if(ie__default.existsSync(n))try{return JSON.parse(ie__default.readFileSync(n,"utf-8"))}catch{return null}let o=le__default.join(r,"marketplace.json");if(ie__default.existsSync(o))try{let s=JSON.parse(ie__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Oo(e="user"){let t=vp(e);if(!ie__default.existsSync(t))return {};try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function hi(e,t="user"){Ep(vp(t),e);}function ox(e,t){let{name:r,marketplace:n}=Do(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Do(i).name===r)[0],!o)throw it.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function sx(e,t){let{name:r,marketplace:n}=Do(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Do(i).name===r)[0],o?{key:o,name:r}:null}function _l(e="user"){return Oo(e).enabledPlugins??{}}function Dl(e,t="user"){let r=Oo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,hi(r,t);}function Uo(e,t,r="user"){let n=Oo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},hi(n,r);}function ix(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 de(){let e=Ce(),t=_l(),r=_l("project"),n=_l("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=Do(u),p=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return ix(p).map(f=>{let h=nx(f.installPath,d),I=(o[f.scope]??t)[u];return {name:d,marketplace:m,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:h?.description,author:h?.author,status:I===false?"disabled":"enabled"}})}),i=bp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function Ip(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function No(e,t){it.debug(`[${e}] Acquiring lock to uninstall`);let r=await Lr();try{let n=Ce(),o=sx(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);it.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),gi(l.installPath);let u=le__default.dirname(l.installPath);gi(u),it.debug(`[${i}] Removing directory: ${u}`),ie__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;at({...n,plugins:m}),Dl(s,t),$l(i,Ip(s));}else n.plugins[s]=c,at(n),Dl(s,t);}else {it.debug(`[${i}] Resolved key: ${s}`);for(let c of a){gi(c.installPath);let d=le__default.dirname(c.installPath);gi(d),it.debug(`[${i}] Removing directory: ${d}`),ie__default.rmSync(d,{recursive:!0,force:!0}),Dl(s,c.scope);}$l(i,Ip(s));let{[s]:l,...u}=n.plugins;at({...n,plugins:u});}await QS(i,a[0].origin??"internal",a[0].type??"skill"),it.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Bo(e,t,r){it.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Lr();try{let o=Ce(),{key:s,name:i}=ox(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";it.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Uo(s,t==="enabled",l),ex(i,t,u),it.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}Oe();function Bl(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,Bl(r)]))}function Fo(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(Bl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Bl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Fo(s,o):r[n]=o;}return r}R();var Fl=x("bundleContent"),yi="${CLAUDE_PLUGIN_ROOT}/hooks/";function ax(e){return e.split(yi).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function jl(e){return typeof e=="string"?ax(e):Array.isArray(e)?e.map(jl):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,jl(r)])):e}function lx(e,t){let r=le__default.join(e,"rules");if(!ie__default.existsSync(r))return 0;let n=ie__default.readdirSync(r).filter(s=>s.endsWith(".md")&&ie__default.lstatSync(le__default.join(r,s)).isFile());if(n.length===0)return 0;let o=vn(t);ie__default.mkdirSync(o,{recursive:true});for(let s of n)ie__default.copyFileSync(le__default.join(r,s),le__default.join(o,s));return n.length}function cx(e,t){let r=le__default.join(e,"hooks","hooks.json");if(!ie__default.existsSync(r))return 0;let n;try{n=JSON.parse(ie__default.readFileSync(r,"utf-8"));}catch(g){return Fl.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=le__default.join(e,"hooks"),i=Ra(t),a=new Set,l=g=>{if(typeof g=="string"&&g.includes(yi)){let f=g.slice(g.indexOf(yi)+yi.length),h=/^([^"'\s]+)/.exec(f);h&&a.add(h[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){ie__default.mkdirSync(i,{recursive:true});for(let g of a){let f=le__default.join(s,g);ie__default.existsSync(f)&&(ie__default.copyFileSync(f,le__default.join(i,g)),u++);}}let c=jl(o),d=Oo(t),m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Fo(m,c);return hi({...d,hooks:p},t),u}function Tp(e,t){let r=lx(e,t),n=cx(e,t);r>0&&Fl.debug(`Copied ${r} rule file(s) to ${vn(t)}`),n>0&&Fl.debug(`Copied ${n} hook script(s) to ${Ra(t)}`);}j();R();var ux=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,dx=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function st(e){if(!ux.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function px(e){if(!dx.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 Dr=x("installer");function mx(e,t,r){let n=`${e}@${r||me}`,s=Ce().plugins[n];if(s&&!t)throw new Xe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function fx(e,t,r){r&&await Al(t);try{Dr.debug(`[${t}] Extracting archive...`),await mp(e,t);}catch(n){throw await Al(t),n}}function gx(e,t,r,n,o,s="claude-code",i){let a=Ce(),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),Uo(e,true,n);}async function hx(e,t,r,n,o,s){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:te().interfaceType});}catch(i){Dr.warn(`Failed to send install metrics: ${String(i)}`);}}async function yx(e,t,r,n){try{await T(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:te().interfaceType});}catch(o){Dr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Fe(e,t={}){let r=Date.now(),n=null;try{Dr.debug(`[${e}] Acquiring lock...`),n=await Lr();let{pluginKey:o,alreadyInstalled:s}=mx(e,t.force,t.source),{source:i}=t;Dr.debug(`[${e}] Fetching manifest...`);let a=await Vn(e,i);st(a.name),px(a.version),Dr.debug(`[${e}] Downloading archive...`);let l=await pp(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=cu(a.name,a.version,t.source);await fx(l,d,!!s&&!!t.force),Tp(d,u),gx(o,d,a.version,u,"internal",t.providerId,c),yp(a,d,t.source);let m=Date.now()-r;Dr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await hx(a.name,a.version,m,ui(u),"internal",c),p}catch(o){throw await yx(e,o,"internal",t.type??"skill"),Dr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Pe();An();R();var wx=x("commands:helpers");async function Z(){let e=await ee();if(!e)return v("Not authenticated. Run: flow auth login"),false;e.customUrl&&Dt(e.customUrl);try{await Ut();}catch(t){return wx.debug(`Token validation failed: ${String(t)}`),v("Session expired. Run: flow auth login"),false}return true}async function z(e){let t=Hl.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 Wn(e){let t=Hl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim());});})}var Sx="\x1B[A",xx="\x1B[B";function Pp(e,t){let r=t?P.cyan("\u276F"):" ",n=t?P.cyan(e.label):e.label,o=e.description?P.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function bx(e,t){return e.map((r,n)=>Pp(r,n===t)).join(`
110
+ `),this.warned=!0;}As().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=As(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return As().path}static hasExistingData(){try{let t=new Ga({projectName:za});return ie.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new Ga({projectName:za});ie.rmSync(t.path,{force:!0});}catch{}Rs=null;}};});async function Xa(){if(Ge.hasExistingData())return new Ge;switch(process.platform){case "darwin":return await Tn.isAvailable()?new Tn:new Ge;case "linux":return await Sr.isAvailable()?new Sr:await Sr.ensureInstalled()?new Sr:new Ge;case "win32":return await Pn.isAvailable()?new Pn:new Ge;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Pu=J(()=>{"use strict";Ba();Ka();Wa();yo();});var Cu=J(()=>{"use strict";Ea();Ua();Pu();Ba();Ka();Wa();yo();});async function br(){return Ls||(Ls=Xa()),Ls}function _s(){Ls=null;}async function ee(){let t=await(await br()).getSecret(Qt,qa);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function xr(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 ku.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await br()).setSecret(Qt,qa,JSON.stringify(e));}async function Au(){let e=await br();await e.deleteSecret(Qt,qa),await e.deleteSecret(Qt,Ya),await e.deleteSecret(Qt,Za);}async function Ru(){return (await br()).getStoragePath()}async function $u(e){await(await br()).setSecret(Qt,Ya,JSON.stringify(e));}async function Ds(){let t=await(await br()).getSecret(Qt,Ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Os(e){await(await br()).setSecret(Qt,Za,JSON.stringify(e));}async function Cn(){let t=await(await br()).getSecret(Qt,Za);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ir(){let e=await Ds();return e?new Date(e.expiresAt)>new Date:false}function Dt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,ku.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var ku,Qt,qa,Ya,Za,Ls,Pe=J(()=>{"use strict";Cu();R();ku=b("config:credentials"),Qt="flow-plugins-cli",qa="credentials",Ya="token-cache",Za="user-info",Ls=null;});function kn(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 Us=J(()=>{"use strict";});function vy(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 Qa(e){if(Mu.some(r=>r.test(e)))return true;let t=vy(e);return !!(t&&Mu.some(r=>r.test(t)))}function Ey(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function Ot(e,t){let r=Ey(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&&Qa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Mu,Xr=J(()=>{"use strict";Mu=[/^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 Cy(e){if(!Zt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function ky(e){if(e instanceof HTTPError){let t=e.response.status;el.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&&Lu[r]?new Error(Lu[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?(el.debug(`Non-HTTP error during authentication: ${e.message}`),e):(el.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function qr(e){let t=Ot("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Cy(e.tenant);let r;try{r=await np.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await ky(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await xr(e),await $u({accessToken:r.access_token,expiresAt:n});let o=kn(r.access_token);await Os({sub:o.sub,name:o.name,email:o.email});}var el,Lu,Ns=J(()=>{"use strict";Pe();Us();Xr();R();j();el=b("api:auth");Lu={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 Ut(){if(await Ir()){let n=await Ds();if(n)return n.accessToken}_u.debug("Token expired or missing, re-authenticating...");let t=await ee();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ge.clearFallbackFile(),_s(),await qr(t);let r=await Ds();if(!r)throw new Error("Authentication succeeded but token was not persisted");return _u.debug("Token refreshed successfully"),r.accessToken}var _u,An=J(()=>{"use strict";Pe();Ns();yo();R();_u=b("lib:tokenProvider");});function Kt(){return np.create({prefix:Ot("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ut();e.headers.set("Authorization",`Bearer ${t}`);let r=await ee();r?.tenant&&Zt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Mo=J(()=>{"use strict";Xr();Pe();An();j();});function Xd(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 Un(e,t,r){let n=Kt(),o=Xd({source:t,timeoutMs:r});return o?n.get(e,o):n.get(e)}function qd(e,t={}){let r=Kt(),n=Xd(t);return n?r.head(e,n):r.head(e)}async function Nn(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 vl=J(()=>{"use strict";Mo();});function Lo(e){if(!e||!ES.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Bn(e){return TS.test(e)}function Fn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Tl(e){if(!PS.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 jn(e,t){let r=Fn(e);Tl(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function mi(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!CS.test(t)&&!kS.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var ES,TS,PS,CS,kS,Mr=J(()=>{"use strict";ES=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;TS=/^[^@]+@[^@]+$/;PS=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;CS=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,kS=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Qd={};su(Qd,{FlowApiAdapter:()=>Kn});var AS,Kn,Pl=J(()=>{"use strict";Mo();vl();R();Mr();AS=b("catalog.flow-api"),Kn=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 Un("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 Nn(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){Lo(t);try{return await Un(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await Nn(r);if(n)throw new Error(n,{cause:r});if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`,{cause:r}):new Error(`Failed to fetch manifest: HTTP ${o}`,{cause:r})}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`,{cause:r}):r}}async ping(){try{return await Kt().head("v1/plugins/catalog"),AS.debug("ping ok"),!0}catch{return !1}}};});function $S(){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 tp(){return ep??=$S(),ep}var ep,rp=J(()=>{"use strict";});var sp={};su(sp,{GitRepoAdapter:()=>Hn});function op(e,t){if(!MS.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var MS,Hn,Cl=J(()=>{"use strict";rp();Xr();MS=/^[a-zA-Z0-9_.-]+$/;Hn=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(Qa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return op(a,"owner"),op(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 np.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 np.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 tp();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}}};});j();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(Ia),origins:new Set(va)},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(Ia)},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(va)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Pe();An();Us();j();Xr();R();var Bs=b("api:metrics");function Du(){return Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ou(e,t,r){return np.post(e,{json:t,headers:r})}async function Ry(e){let t=await Cn();if(t)return t;let r=kn(e),n={sub:r.sub,name:r.name,email:r.email};return await Os(n),n}async function T(e,t){let r=await Ut(),n=await Ry(r),o=await ee();if(!Zt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:xa,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Ou(Du(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Bs.debug(`Metrics event sent: ${e}`);}catch(i){throw Bs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Uu(e,t,r){try{let n=r&&Zt.test(r)?r:"unknown",o={action:e,booster:xa,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Ou(Du(),o,{FlowTenant:n}),Bs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Bs.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_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 $y={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},St={...$y};function Nu(e){let t=Date.now();St={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Yr(e){St.currentStep=e,St.stepStart=Date.now();}function te(){return {...St}}function vr(){return St.sessionStart===0?0:Date.now()-St.sessionStart}function Zr(){return St.stepStart===0?0:Date.now()-St.stepStart}function Bu(){St.tuiSessionStart=Date.now();}function Fu(){return St.tuiSessionStart===0?0:Date.now()-St.tuiSessionStart}R();var My=3e3,Ly=b("abandonment");async function Fs(e){let{currentStep:t,sessionStart:r}=te();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:vr()};try{await Promise.race([T(E.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),My))]);}catch(o){Ly.warn(`Abandonment event failed: ${String(o)}`);}}function ju(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}R();var _y=3e3,Dy=b("session-end");async function So(e,t,r){let n=Fu(),s=[T(E.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Fs(e));try{await ju(Promise.all(s).then(()=>{}),_y);}catch(i){Dy.warn(`Session end event failed: ${String(i)}`);}}var By=2e3;function Hu(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),So("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},By);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Hy=16;function Vu({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(Hy)}),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]})})]})}j();function Ju({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();bn.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:xn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}j();function Wu({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[gr," \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"})]})]})}j();function Gu(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[gr," \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})}));Ns();j();function tn(){return le__default.join(Te__default.homedir(),".claude","settings.json")}function Xu(e){return `${(e&&e.trim().length>0?e.trim():fs).replace(/\/+$/,"")}/flow-litellm/`}function Po(){let e=tn();if(!ie__default.existsSync(e))return {status:"missing"};let t=ie__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Ks(e){let t=tn();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,t);}function qu(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 al(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 Yu(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 qy=3600,rn=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Co(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 Yy(e){return Xy.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:qy})}function Hs(e,t={}){let r=Po();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new rn;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?al(r.settings):null,s=r.status==="ok"?Yu(r.settings):null,i=t.jwtOverride??Yy(e),a=Xu(e.customUrl),l=qu(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Vs(e){Ks(e.merged);}function Zu(){let e=Po();return e.status!=="ok"?false:al(e.settings)!==null}Pe();Oe();function Zy(){let e=mu();if(!ie__default.existsSync(e))return {};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var ll=null;function Qy(){return ll===null&&(ll=Zy()),ll}function Pr(){return !!Qy().ENABLE_EXPERIMENTAL_BETAS}j();function nw(){return ce.filter(e=>e.platforms[process.platform]?.status==="supported")}function ed(e){let t=nw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Js={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=le__default.join(Te__default.homedir(),".claude","settings.json"),r=ie__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??fs),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},ow={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},ce=Pr()?[Js,ow]:[Js];Pe();R();var lw=b("moduleState");function Gs(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"modules.json")}var cw={retries:5,minTimeout:50};async function td(e,t){ie__default.mkdirSync(le__default.dirname(e),{recursive:true});let r=await aw.lock(e+".lock",{realpath:false,retries:cw});try{return await t()}finally{await r();}}function rd(){let e=Gs();if(!ie__default.existsSync(e))return [];try{let t=JSON.parse(ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(lw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ie__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ie__default.rmSync(e,{force:true}),[]}}function nn(){return rd()}function nd(e){let t=Gs();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ie__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,t);}function ot(e){return nn().find(t=>t.alias===e)??null}async function bt(e){let t=Gs();await td(t,async()=>{let r=rd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,nd(r);});}async function on(){let e=Gs();ie__default.existsSync(e)||await td(e,async()=>{ie__default.existsSync(e)||nd([]);});}var pw=promisify(execFile);function Cr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Bt(e){let t=process.platform==="win32"?"where":"which";try{return await pw(t,[e]),!0}catch{return false}}function er(){return process.platform==="win32"?"npm.cmd":"npm"}var od=promisify(execFile),$n=class{type="npm";async isAvailable(){return Bt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=Cr(t,"npm");if(!r)return null;try{let{stdout:n}=await od(er(),["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=Cr(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 od(er(),["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),yw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Xs=class{type="homebrew";async isAvailable(){return Bt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Cr(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=Cr(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(yw);return n?n[2]:null}catch{return null}}};var Mn=promisify(execFile),id=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ad(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"bin")}var qs=class{type="curl";async isAvailable(){return Bt("curl")}async install(t){let r=Date.now(),n=Cr(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=le__default.join(ad(),le__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await Mn(n,["--version"]),s=o.match(id);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=le__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Mn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ie__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ie__default.chmodSync(s,448),await Mn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{ie__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ad(),i=le__default.join(s,le__default.basename(n.binaryName)),a=false;try{if(ie__default.mkdirSync(s,{recursive:!0}),a=!0,await Mn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ie__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await Mn(i,["--version"]),c=u.match(id);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ie__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=le__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Mn("curl",["-L","--fail","-o",n,r]);let o=ie__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ie__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{ie__default.unlinkSync(n);}catch{}}}};R();var ld="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(ld=e.version);}catch{}var ge=ld;var $e=b("moduleInstaller");function jt(e){switch(e){case "npm":return new $n;case "homebrew":return new Xs;case "curl":return new qs}}async function ko(e,t,r){try{await T(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){$e.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ar(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"){$e.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 ko(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 ko(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 ko(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=jt(r),u=false;try{u=await l.isAvailable();}catch(d){$e.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 ko(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await T(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ge,trigger:t});}catch(d){$e.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);$e.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 T(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){$e.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Ew(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await ko(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Ew(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 ee(),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 $e.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,$e.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&$e.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&$e.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Ys(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=jt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await T(E.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ge,trigger:"command"});}catch(a){$e.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);$e.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 T(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){$e.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await T(E.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){$e.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await T(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){$e.warn(`Failed to emit update failed event: ${String(a)}`);}return i}R();var Zs=b("flowAiObsSetup");async function Qs(e,t){try{if(!await new $n().isAvailable().catch(()=>!1))return Zs.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ar(Js,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Zs.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Zs.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Zs.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}R();function cd(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 Tw=b("useAuthSetup");function ud(){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),f=useRef(0),h=useRef(false),{setCredentials:y,setJustAuthenticated:I}=nt(),M=()=>{m("fields"),g(null),t(""),r.current=null,n.current=null,o.current=null;},_=()=>{T(E.CLI_SESSION_STARTED,{cli_version:ge,os:process.platform,node_version:process.version,duration_ms:vr(),interface:"tui"}).catch(()=>{});},C=async H=>{h.current=true;let X={...r.current,customUrl:n.current??void 0};try{H&&Vs(H),await xr(X);}catch(W){l(W instanceof Error?W.message:"Failed to persist credentials"),M(),h.current=false;return}let{clientSecret:A,...F}=X;y(F),I(true),_(),await Qs(n.current,o.current).catch(W=>Tw.warn(`installFlowAiObs threw unexpectedly: ${String(W)}`)),ei({starterKit:F.starterKit});},$=async()=>C(),D=async H=>C(H),U=H=>{try{let X={...r.current,customUrl:n.current??void 0};return Hs(X,{allowOverwriteMalformed:H,jwtOverride:e.trim()})}catch(X){return X instanceof rn?(m("malformedConfirm"),null):(l(X instanceof Error?X.message:"Failed to read settings.json"),m("fields"),null)}},ne=()=>{let H=U(true);H&&(g(H),D(H));},k=async()=>{let H=e.trim();if(!H){i("This field is required");return}let X;try{X=Co(H);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=X,m("customUrl");},V=H=>{n.current=H,m("email");},re=H=>{o.current=H,K();},K=async()=>{let H=n.current;H&&Dt(H),c(true),l(null),f.current+=1;try{await qr(r.current);let X=U(!1);X&&(g(X),m("preview"));}catch(X){let A=X instanceof Error?X.message:"Authentication failed";l(A),Uu(E.CLI_AUTH_FAILED,{error_code:cd(X),attempt:f.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:h,setJwtValue:t,setJwtError:i,cancelToFields:M,handleSubmit:k,goToEmailStep:V,handleEmailConfirm:re,commitAndProceed:D,skipJwtAndProceed:$,planPersistOverwrite:ne}}j();N();function dd(){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:f}=ud(),[h,y]=useState("confirm"),[I,M]=useState(""),_=useRef(""),[C,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(y("confirm"),_.current="",M(""),$(false));},[o]),useInput((D,U)=>{if(!(n||i.current)){if(o==="preview"){U.return&&s?p(s):U.escape?g():D==="q"&&u();return}if(o==="malformedConfirm"){U.return?f():U.escape&&u();return}if(o==="customUrl"){if(h==="confirm")D==="y"||D==="Y"?y("input"):(D==="n"||D==="N"||U.return)&&d(null);else if(U.escape)_.current="",M(""),y("confirm");else if(U.return){let ne=_.current.trim();ne.length>0&&wn.test(ne)?($(false),d(ne)):ne.length>0&&$(true);}else U.backspace||U.delete?(_.current=_.current.slice(0,-1),M(_.current)):D&&!U.ctrl&&!U.meta&&(_.current=_.current+D,M(_.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:[gr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:I}),jsx(Text,{color:"cyan",children:"\u2588"})]}),C&&jsx(Text,{color:"red",children:Sn}),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:[gr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Ju,{onConfirm:m})]}):o==="preview"&&s?jsx(Wu,{plan:s}):o==="malformedConfirm"?jsx(Gu,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[gr," \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(Vu,{label:"JWT",value:e,onChange:D=>{a(D),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 _n(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Rw,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ge]})})]})}var gd=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],se=Pr()?gd:gd.slice(0,3);function $w(e){return se.findIndex(t=>t.id===e)}function dl(e,t,r){let n=$w(r.activeTab);if(t.rightArrow||t.tab){let o=se[(n+1)%se.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=se[(n-1+se.length)%se.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:se[n]?.focus??"list"}]:[]}var wd={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Sd({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:se.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${wd[r]} (${e})`:wd[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var ze=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function xd(){let e=S(i=>i.focus),t=ze(i=>i.query),r=ze(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..."})]})}j();var Id=Object.keys(hr).map((e,t)=>({key:t<3?String(t+2):String((t+5)%10),type:e,...hr[e]})),vd=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...iu[e]}));function Ed(){let e=S(n=>n.catalogFilters),t=Id.every(n=>e.types.has(n.type)),r=vd.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"]})]}),Id.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"]})]}),vd.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)})]})}j();function Td({type:e}){let{label:t,color:r}=hr[e];return jsx(Text,{color:r,children:t})}j();function kd({origin:e}){return e===po?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}N();var ri=Uw.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(Td,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(kd,{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 ",_t(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Dn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}j();function $d({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Dn,{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(ri,{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 _d({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}j();function Od({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(Dn,{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(_d,{label:p.label,pathHint:p.pathHint},p.key):jsx(ri,{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 Jw={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Ww({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(xd,{}),jsx(Ed,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Jw[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Od,{groups:n,emptyMessage:r}):jsx($d,{items:e,emptyMessage:r})]})}function Ud({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(Ww,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Xw={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 ni(){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:[Xw[e],t?" | Ctrl+D: debug log":""]})})}N();function Nd({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 oi({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function wl(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Kd=20;function si(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Kd),s="\u2588".repeat(o)+"\u2591".repeat(Kd-o),i=`${wl(e)} / ${wl(t)}`;return {bar:s,percent:n,label:i}}function ii({received:e,total:t}){let{bar:r,percent:n,label:o}=si(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function ai({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))})]})}j();var Il=Object.entries(Lt),Wd=[...Il.map(([,e])=>e.actionLabel),"Cancel"],Gd=Object.fromEntries(Il.map(([,e])=>[e.actionLabel,e.description]));function zd(e){let t=Il.find(([,r])=>r.actionLabel===e);return t?t[0]:null}R();var uS=b("provider.registry"),dS=3e4,ci=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()+dS}),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"&&uS.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 ui(e){return e?pS[e]:"global"}var Xe=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},$r=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};Mo();vl();R();var gS=b("catalog.registry"),di=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);gS.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()]}};Oe();var vS={retries:5,minTimeout:50};async function El(e,t){mkdirSync(dirname(e),{recursive:true});let r=await aw.lock(e+".lock",{realpath:false,retries:vS});try{return await t()}finally{await r();}}var pi=class{filePath;constructor(t){this.filePath=t??pu();}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 El(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 El(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await El(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));});}};Pl();var he=new di,rr=new pi,LS=["flow-harness"];function _S(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?LS:e.split(",").map(t=>t.trim()).filter(Boolean)}he.register(new Kn);for(let e of _S())he.register(new Kn(e));var ip=false;async function ap(){if(ip)return;ip=true;let e=await rr.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Cl(),sp));for(let r of e)he.register(new t(r.id,r.name,r.source));}Mr();function lp(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 OS=b("api:actions"),cp=2;async function nr(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Pl(),Qd));return new t(e).fetchItems()}return he.fetchAll()}async function up(){return he.fetchAllWithErrors()}async function Vn(e,t){Lo(e);try{return await Un(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await Nn(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 US(e,t){try{let n=(await qd(`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){OS.debug(`[${e}] Archive size probe failed, using default timeout: ${String(r)}`);return}}async function dp(e,t,r){Lo(e);try{let n=await US(e,r),o=lp(n),s=await Un(`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:f}=await d.read();if(g)break;if(p+=f.byteLength,u&&p>l*cp)throw await d.cancel(),new Error(`Download exceeded expected size: received ${p} bytes, expected at most ${l*cp}`);m.push(f),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 Nn(n);throw o?new Error(o,{cause:n}):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`,{cause:n}):n}}async function fi(){try{let{profiles:e}=await Kt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login",{cause:e}):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits",{cause:e}):new Error(`Failed to fetch starter kits: ${e.message}`,{cause:e}):e}}Oe();Oe();async function pp(e,t){let r=le.resolve(t);await Ht.mkdir(r,{recursive:true});let n=le.join(le.dirname(r),`${randomUUID()}.zip`);try{await Ht.writeFile(n,e);let o=await BS.Open.file(n),s=le.normalize(r+le.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=le.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(le.resolve(le.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ht.unlink(n);}catch{}}}async function kl(e){await Ht.rm(e,{recursive:true,force:true});}async function Lr(){let e=uu();await Ht.mkdir(le.dirname(e),{recursive:true});try{await Ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await aw.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();j();function KS(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||pe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function gp(e){let t=ws(e);if(!ie__default.existsSync(t))return null;try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return null}}function HS(e){let t=gp(e);if(t)return t;let r=KS(e),n=ws(e);return ie__default.mkdirSync(le__default.dirname(n),{recursive:true}),Al(r,e),r}function Al(e,t){let r=ws(t),n=`${r}.${randomUUID()}.tmp`;ie__default.writeFileSync(n,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(n,r);}function VS(e){let t=e||pe,r=Jr(),n={};try{ie__default.existsSync(r)&&(n=JSON.parse(ie__default.readFileSync(r,"utf-8")));}catch{n={};}if(n[t])return;n[t]={source:{source:"github",repo:`cit-flow/${t}`},installLocation:cu(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let o=`${r}.${randomUUID()}.tmp`;ie__default.writeFileSync(o,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,r);}function hp(e,t,r){it(e.name),VS(r);let n=Ca(e.name,r);ie__default.mkdirSync(le__default.dirname(n),{recursive:true});try{ie__default.lstatSync(n),ie__default.rmSync(n,{recursive:!0,force:!0});}catch{}ie__default.cpSync(t,n,{recursive:true,dereference:true});let o=HS(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}),Al(o,r));}function Rl(e,t){it(e);let r=Ca(e,t);try{ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}let n=gp(t);if(!n)return;let o=n.plugins.length;n.plugins=n.plugins.filter(s=>s.name!==e),n.plugins.length!==o&&Al(n,t);}N();R();var WS=b("mcpConfigReader"),GS=500,zS=512;function XS(){return le__default.join(Te__default.homedir(),".claude.json")}function qS(){return le__default.join(process.cwd(),".mcp.json")}function wp(e){if(!ie__default.existsSync(e))return null;try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return WS.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function _o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $l(e){if(!_o(e))return {};let t=e.mcpServers;return _o(t)?t:{}}function Ml(e,t){return Object.keys(e).slice(0,GS).map(n=>({name:w(n.slice(0,zS)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function bp(){let e=[],t=XS(),r=wp(t);if(_o(r)){let a=r,l=$l(a);e.push(...Ml(l,"user"));let u=process.cwd();if(_o(a.projects)){let c=a.projects[u];if(_o(c)){let d=$l(c);e.push(...Ml(d,"local"));}}}let n=qS(),o=wp(n),s=$l(o);e.push(...Ml(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();var qe=b("storage");async function ZS(e,t,r){try{await T(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:te().interfaceType});}catch(n){qe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function QS(e,t,r){let n=t==="enabled"?E.CLI_TOOL_ENABLED:E.CLI_TOOL_DISABLED;T(n,{tool_id:e,source:r,interface:te().interfaceType}).catch(o=>qe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ol(){return le__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function eb(){return le__default.join(Te__default.homedir(),".claude","plugins")}function gi(e){let t;try{t=ie__default.realpathSync(e);}catch{t=le__default.resolve(e);}let r=le__default.resolve(eb()),n=le__default.resolve(le__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+le__default.sep),s=t.startsWith(n+le__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Ip(e="user"){return e==="local"?le__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?le__default.join(process.cwd(),".claude","settings.json"):le__default.join(Te__default.homedir(),".claude","settings.json")}function Ce(){let e=Ol();if(!ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Ul(){let e=Ol();try{let t=await ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function tb(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function vp(e,t){try{ie__default.mkdirSync(le__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(r,e);}catch(r){throw tb(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`,{cause:r}):r}}function at(e){vp(Ol(),e);}function Do(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function rb(e,t){let r=le__default.join(e,".claude-plugin"),n=le__default.join(r,"plugin.json");if(ie__default.existsSync(n))try{return JSON.parse(ie__default.readFileSync(n,"utf-8"))}catch{return null}let o=le__default.join(r,"marketplace.json");if(ie__default.existsSync(o))try{let s=JSON.parse(ie__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function Oo(e="user"){let t=Ip(e);if(!ie__default.existsSync(t))return {};try{return JSON.parse(ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function hi(e,t="user"){vp(Ip(t),e);}function nb(e,t){let{name:r,marketplace:n}=Do(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Do(i).name===r)[0],!o)throw qe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function ob(e,t){let{name:r,marketplace:n}=Do(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Do(i).name===r)[0],o?{key:o,name:r}:null}function Ll(e="user"){return Oo(e).enabledPlugins??{}}function _l(e,t="user"){let r=Oo(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,hi(r,t);}function Uo(e,t,r="user"){let n=Oo(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},hi(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 ue(){let e=Ce(),t=Ll(),r=Ll("project"),n=Ll("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=Do(u),p=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return sb(p).map(f=>{let h=rb(f.installPath,d),I=(o[f.scope]??t)[u];return {name:d,marketplace:m,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:h?.description,author:h?.author,status:I===false?"disabled":"enabled"}})}),i=bp(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}function xp(e){let t=e.lastIndexOf("@");return t>0?e.slice(t+1):void 0}async function No(e,t){qe.debug(`[${e}] Acquiring lock to uninstall`);let r=await Lr();try{let n=Ce(),o=ob(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`);qe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`);let u=le__default.dirname(l.installPath),c=a.filter(m=>m.scope!==t);if(c.some(m=>le__default.dirname(m.installPath)===u)?qe.debug(`[${i}] Directory still used by another scope, keeping: ${u}`):(gi(l.installPath),gi(u),qe.debug(`[${i}] Removing directory: ${u}`),ie__default.rmSync(u,{recursive:!0,force:!0})),c.length===0){let{[s]:m,...p}=n.plugins;at({...n,plugins:p}),_l(s,t),Rl(i,xp(s));}else n.plugins[s]=c,at(n),_l(s,t);}else {qe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){gi(c.installPath);let d=le__default.dirname(c.installPath);gi(d),qe.debug(`[${i}] Removing directory: ${d}`),ie__default.rmSync(d,{recursive:!0,force:!0}),_l(s,c.scope);}Rl(i,xp(s));let{[s]:l,...u}=n.plugins;at({...n,plugins:u});}await ZS(i,a[0].origin??"internal",a[0].type??"skill"),qe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Bo(e,t,r){qe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Lr();try{let o=Ce(),{key:s,name:i}=nb(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";qe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Uo(s,t==="enabled",l),QS(i,t,u),qe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}Oe();function Nl(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,Nl(r)]))}function Fo(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(Nl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Nl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Fo(s,o):r[n]=o;}return r}R();var Bl=b("bundleContent"),yi="${CLAUDE_PLUGIN_ROOT}/hooks/";function ib(e){return e.split(yi).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Fl(e){return typeof e=="string"?ib(e):Array.isArray(e)?e.map(Fl):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Fl(r)])):e}function ab(e,t){let r=le__default.join(e,"rules");if(!ie__default.existsSync(r))return 0;let n=ie__default.readdirSync(r).filter(s=>s.endsWith(".md")&&ie__default.lstatSync(le__default.join(r,s)).isFile());if(n.length===0)return 0;let o=vn(t);ie__default.mkdirSync(o,{recursive:true});for(let s of n)ie__default.copyFileSync(le__default.join(r,s),le__default.join(o,s));return n.length}function lb(e,t){let r=le__default.join(e,"hooks","hooks.json");if(!ie__default.existsSync(r))return 0;let n;try{n=JSON.parse(ie__default.readFileSync(r,"utf-8"));}catch(g){return Bl.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=le__default.join(e,"hooks"),i=Aa(t),a=new Set,l=g=>{if(typeof g=="string"&&g.includes(yi)){let f=g.slice(g.indexOf(yi)+yi.length),h=/^([^"'\s]+)/.exec(f);h&&a.add(h[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){ie__default.mkdirSync(i,{recursive:true});for(let g of a){let f=le__default.join(s,g);ie__default.existsSync(f)&&(ie__default.copyFileSync(f,le__default.join(i,g)),u++);}}let c=Fl(o),d=Oo(t),m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Fo(m,c);return hi({...d,hooks:p},t),u}function Ep(e,t){let r=ab(e,t),n=lb(e,t);r>0&&Bl.debug(`Copied ${r} rule file(s) to ${vn(t)}`),n>0&&Bl.debug(`Copied ${n} hook script(s) to ${Aa(t)}`);}j();R();var cb=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ub=/^[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 db(e){if(!ub.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 Dr=b("installer");function pb(e,t,r){let n=`${e}@${r||pe}`,s=Ce().plugins[n];if(s&&!t)throw new Xe(e,s[0].version??"unknown");return {pluginKey:n,alreadyInstalled:s}}async function mb(e,t,r){r&&await kl(t);try{Dr.debug(`[${t}] Extracting archive...`),await pp(e,t);}catch(n){throw await kl(t),n}}function fb(e,t,r,n,o,s="claude-code",i){let a=Ce(),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),Uo(e,true,n);}async function gb(e,t,r,n,o,s){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:te().interfaceType});}catch(i){Dr.warn(`Failed to send install metrics: ${String(i)}`);}}async function hb(e,t,r,n){try{await T(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:te().interfaceType});}catch(o){Dr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Fe(e,t={}){let r=Date.now(),n=null;try{Dr.debug(`[${e}] Acquiring lock...`),n=await Lr();let{pluginKey:o,alreadyInstalled:s}=pb(e,t.force,t.source),{source:i}=t;Dr.debug(`[${e}] Fetching manifest...`);let a=await Vn(e,i);it(a.name),db(a.version),Dr.debug(`[${e}] Downloading archive...`);let l=await dp(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=lu(a.name,a.version,t.source);await mb(l,d,!!s&&!!t.force),Ep(d,u),fb(o,d,a.version,u,"internal",t.providerId,c),hp(a,d,t.source);let m=Date.now()-r;Dr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await gb(a.name,a.version,m,ui(u),"internal",c),p}catch(o){throw await hb(e,o,"internal",t.type??"skill"),Dr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}R();N();Pe();An();R();var yb=b("commands:helpers");async function Z(){let e=await ee();if(!e)return v("Not authenticated. Run: flow auth login"),false;e.customUrl&&Dt(e.customUrl);try{await Ut();}catch(t){return yb.debug(`Token validation failed: ${String(t)}`),v("Session expired. Run: flow auth login"),false}return true}async function z(e){let t=Kl.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 Jn(e){let t=Kl.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(w(e),n=>{t.close(),r(n.trim());});})}var wb="\x1B[A",Sb="\x1B[B";function Tp(e,t){let r=t?P.cyan("\u276F"):" ",n=t?P.cyan(e.label):e.label,o=e.description?P.dim(` \u2014 ${e.description}`):"";return ` ${r} ${n}${o}`}function bb(e,t){return e.map((r,n)=>Tp(r,n===t)).join(`
111
111
  `)}async function wi(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(bx(t,o));let s="",i=c=>{if(s+=c,s===""){l(),n(new Error("SIGINT"));return}if(s==="\r"||s===`
112
+ `),process.stdout.write(bb(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===Sx){o=(o-1+t.length)%t.length,a(),s="";return}if(s===xx){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${Pp(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);})}Mr();var Gn=x("claudeProxy"),Gl="claude ",Cp="flow ",Vl=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Jn=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";}},Ix=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,vx=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Ex={"--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}$/},Tx=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Px=/^(flow|claude)\s+auth\s+login(\s|$)/,kp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Ap(e){return kp.test(e.trim())}function Cx(e){return kp.exec(e.trim())?.[2]??""}async function Rp(e){let t=Cx(e);Pl(t);let r=Date.now();Gn.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 zl(n)?new Wl:n}}function kx(e){$p(e);let t=e.slice(Gl.length);if(!Ix.test(t))throw new Jn(e)}var Si=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Wl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function $p(e){if(!e||!/^claude /.test(e))throw new Vl(e)}function Ax(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!vx.test(r))throw new Jn(`Unexpected flag: ${r}`);let n=Ex[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Jn(`Flag ${r} requires a value`);if(!n.test(o))throw new Jn(`Unsafe value for flag ${r}`);t++;}}}async function Le(e){$p(e);let t=e.slice(Gl.length).split(/\s+/).filter(Boolean);Ax(t);let r=Rx(t);Gn.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 Gn.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 zl(o)?new Si:o}}function Rx(e){return e.length>=3?e[2]:e.join(" ")}function zl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function $x(e){return e.startsWith(Cp)?Gl+e.slice(Cp.length):e}function Mx(e){return Tx.test(e)||Px.test(e)}function Lx(e){let t=0;for(;t<e.length&&Mx(e[t]);)t++;return e.slice(t)}var _x=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Dx(e,t){return !t||e.includes("--scope")||!_x.test(e)?e:`${e} --scope ${t}`}async function jo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Lx(r).map(i=>$x(i)).map(i=>Dx(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)kx(i);Gn.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 xi(e,t,r){let n=Fn(e),o=t?.trim();if(!o&&(o=(await Wn(`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=mi(o),r?.(),Gn.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"}`);Gn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw zl(s)?new Si:s}}Mr();j();Oe();R();var Fx=6e4,Or=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:Fx},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 Or("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Or(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Or(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Tt(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 dn(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 Kx(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Hx(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Vx(e){return typeof e=="object"&&e!==null&&e.source==="github"}function pn(e,t){let r=e.source;if(Kx(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(Hx(r))return {cloneUrl:r.url,subPath:"."};if(Vx(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 Pt=x("claude-code.adapter");function Jx(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=Wr();if(!ie__default.existsSync(s))return r;try{let i=JSON.parse(ie__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Bp(e,t){let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=pn(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=Jx(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Aa(s,e.name,"external"):a=join(Jr(i==="user"?"global":"project"),e.name);let l=null;try{st(e.name),l=await Et(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(ie__default.existsSync(a)&&ie__default.rmSync(a,{recursive:!0,force:!0}),ie__default.mkdirSync(dirname(a),{recursive:!0}),ie__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Nl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(g=>g.scope!==i),m],at(d),Uo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Pt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Tt(l).catch(()=>{});}}async function Xl(e,t,r,n){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:ui(n),version:"unknown",duration_ms:t,interface:te().interfaceType});}catch(o){Pt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Op(e,t,r){try{await T(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:te().interfaceType});}catch(n){Pt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Gx={async install(e,t){if(e.origin===yn&&!e.installCommand&&!Bn(e.name))return Bp(e,t);if(e.origin===yn&&e.installCommand){let r=e.type??"skill",n=await jo(e.installCommand,t.scope);return n.exitCode===0?(await Xl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Op(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Bn(e.name)){let r=e.type??"skill",n=jn(e.name,t.scope);Pt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Le(n);if(o.exitCode===0)return await Xl(e.name,o.duration_ms,r,t.scope),{success:true};Pt.debug(`[${e.name}] First attempt failed, adding marketplace`),await xi(e.name,t.marketplaceSource,()=>{});let s=await Le(n);return s.exitCode===0?(await Xl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Op(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 Fe(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Pt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await No(e,t);},getInstallPath(e,t){return ""}};function Up(e){return {async install(t,r){if(t.origin===yn&&!t.installCommand&&!Bn(t.name))return Bp(t,r);if(!t.installCommand)try{let o=await Fe(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Pt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Pt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await 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=Ce(),o=`${t}@${me}`;if(n.plugins[o]){await No(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 zx(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ie__default.existsSync(t))continue;let r=ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Xx(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!ie__default.existsSync(t))continue;let r=ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function ql(e,t,r,n){let o=await Nl(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],at(o);}var qx={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{st(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=zx(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=xs(r);ie__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)ie__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));ie__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await ql(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){let r=xs(t),n=lt(e);if(ie__default.existsSync(r))for(let a of ie__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ie__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ce(),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(xs(t),`${lt(e)}.md`)}},Yx={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{st(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Xx(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=vn(r);ie__default.mkdirSync(l,{recursive:!0});for(let u of a)ie__default.copyFileSync(u,join(l,basename(u)));return await ql(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return vn(t)}},Zx={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{st(e.name),s=await Et(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!ie__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ie__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Po();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=Fo(m,u);return Ks({...d,hooks:p}),await ql(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},bi=class{id="claude-code";name="Claude Code";async isAvailable(){return dn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Gx,skill:Up("skill"),mcp:Up("mcp"),agent:qx,hook:Zx,rule:Yx}};function Ii(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 eb=new Set(["gh"]),tb=Ii(eb,"use: gh copilot mcp remove <name>"),vi=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await dn("gh",["--version"])?dn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:tb}};Oe();var rb=new Set(["opencode"]),nb=Ii(rb,"use: opencode config remove mcp <name>");function ob(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 Fp(){return {async install(e,t){try{st(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=pn(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=Ss(t.scope??"user"),a=join(s,".opencode","plugins");if(ie__default.existsSync(a)){let l=ie__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ie__default.mkdirSync(i,{recursive:!0}),ie__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ie__default.existsSync(l)&&ie__default.rmSync(l,{recursive:!0,force:!0}),ie__default.mkdirSync(l,{recursive:!0}),ie__default.cpSync(s,l,{recursive:!0}),ie__default.mkdirSync(i,{recursive:!0}),ie__default.writeFileSync(join(i,`${e.name}.js`),ob(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 Tt(o).catch(()=>{});}},async uninstall(e,t){st(e);let r=Ss(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ie__default.existsSync(n)&&ie__default.rmSync(n,{force:true}),ie__default.existsSync(o)&&ie__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Ss(t),`${e}.js`)}}}var Ei=class{id="opencode";name="OpenCode";async isAvailable(){return dn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:nb,skill:Fp(),bundle:Fp()}};var Wt=new ci;Wt.register(new bi);Pr()&&(Wt.register(new vi),Wt.register(new Ei));function jp({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(()=>{Wt.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let y=l.find(I=>I.name===h);y?(d(y.id),a(false),s(true)):a(false);},[l]),g=useCallback(h=>{let y=Xd(h);y?r(y,c):s(false);},[r,c]),f=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(y=>y.name),"Cancel"];return jsx(ot,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ot,{itemName:`${e} \u2014 Choose scope`,actions:Gd,descriptions:zd,onAction:g,onClose:f},"scope"):jsx(ot,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function Hp({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,f)=>{f.upArrow?a(h=>Math.max(0,h-1)):f.downArrow?a(h=>Math.min(d.length-1,h+1)):f.return?d[i]==="Confirm Install"?n():o():f.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 f=w(g.name??g.flowId),h=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((g,f)=>jsx(Box,{children:jsxs(Text,{bold:f===i,color:f===i?"cyan":void 0,children:[f===i?"\u203A ":" ",g]})},g))})]}):jsx(ot,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Ci({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 Jp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Ci({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(ot,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function Xp({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Ci({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(ot,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}R();var qn=x("bundle:installer"),qp=/already exists/i;async function pb(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Ap(t)){let r=await Rp(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(qp.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(qp.test(n))return;throw new Error(n)}}}async function mb(e,t){try{await T(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){qn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function fb(e,t,r){try{await T(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){qn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Yp(e,t,r,n){try{await T(E.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){qn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function gb(e,t,r,n,o){try{await T(E.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){qn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Ri(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 mb(i,o.length);let l=[],u=0,c=o.length;for(let[p,g]of o.entries()){let f=g.name??g.flowId,h=g.type??"unknown";if(!g.type){qn.warn(`Artifact "${f}" has no type \u2014 treated as failed`),l.push({name:f,type:h,reason:"unknown artifact type"}),await Yp(i,f,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await pb(g),u++,await fb(i,f,h),r?.({index:p+1,total:c,artifact:g,success:!0});}catch(y){let I=y instanceof Error?y.message:String(y);qn.error(`Failed to install artifact "${f}": ${I}`),l.push({name:f,type:h,reason:I}),await Yp(i,f,h,I),r?.({index:p+1,total:c,artifact:g,success:false,error:I});}}let d=Date.now()-a,m=l.length;return await gb(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function tm({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Ri(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(em,{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(em,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var Se=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:de()})}));N();function rm({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 ",_t(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function nm({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 ${_t(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((f,h)=>{let y=h===o;return jsxs(Box,{children:[jsx(Text,{color:y?"cyan":void 0,children:y?"\u203A ":" "}),jsx(Text,{bold:y,color:f.danger?"yellow":void 0,dimColor:!y,children:f.label})]},f.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 om(e){return e.adapter.removable!==false?4:2}j();N();function sm({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 am({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function lm({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(sm,{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(et/2)),p=Math.min(a.length,m+et);p===a.length&&(m=Math.max(0,p-et));let g=a.slice(m,p),f=m,h=a.length-p,y=s.length>0&&m<s.length,I=p>s.length,M=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:f>0?`\u2191 ${f} more above`:" "})}),y&&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"]}),M.map(C=>jsx(am,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),I&&jsxs(Box,{flexDirection:"column",marginTop:y?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(am,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}kl();var Ib=/^https?:\/\/.+/;function vb(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Eb(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function pm(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),g=useCallback(()=>{o("idle");},[]),f=useCallback(async()=>{let h=m.current,y=d.current;if(!Ib.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let I=randomUUID(),M=new Hn(I,y,h);try{await M.fetchItems(),await rr.add({id:I,name:y,source:h}),he.register(new Hn(I,y,h)),r(),e(),t(`Catalog "${y}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(D){let C=vb(D)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Eb(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((h,y)=>{if(y.escape){o("idle");return}if(y.return){d.current.trim().length>0&&o("add-url");return}if(y.backspace||y.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!y.ctrl&&!y.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,y)=>{if(y.escape){o("add-name");return}if(y.return){f();return}if(y.backspace||y.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!y.ctrl&&!y.meta&&(m.current=m.current+h,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:g}}function mm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await rr.remove(o),he.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function gm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=Se(A=>A.installedItems),[o,s]=useState(()=>he.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[g,f]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{g==="browse"&&!o[i-1]&&f("main");},[g,o,i]);let y=useCallback(()=>{(async()=>{let A=he.listAdapters(),F=await rr.read(),J=new Map(F.map(De=>[De.id,De]));s(A.map(De=>({adapter:De,stored:J.get(De.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),y();},[t,y]),useEffect(()=>{if(i===0){p(null);return}let A=h.current[i-1];if(!A)return;let F=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(J=>{F||p({items:J,loading:false,error:null});}).catch(J=>{F||p({items:[],loading:false,error:J instanceof Error?J.message:"Failed to load catalog"});}),()=>{F=true;}},[i]);let I=pm(y),M=useCallback(()=>{y(),a(0),u("list"),p(null),f("main");},[y]),{handleRemove:D}=mm(M),C=useCallback(async A=>{f("removing"),await D(A);},[D]),$=useCallback(async A=>{try{let F=await A.adapter.fetchItems();if(p({items:F,loading:!1,error:null}),A.stored){let J=new Date().toISOString();await rr.updateField(A.stored.id,{lastUpdated:J}),y();}r("Marketplace updated","success");}catch(F){r(F instanceof Error?F.message:"Update failed","error");}},[y,r]),O=useCallback(async A=>{if(!A.stored)return;let F=A.stored.autoUpdate!==false;await rr.updateField(A.stored.id,{autoUpdate:!F}),y();},[y]),U=useCallback(()=>f("browse"),[]),ne=useCallback(A=>{let F=o[i-1];if(!F)return;let J=F.adapter.removable!==false;[U,()=>{$(F);},...J?[()=>{O(F);},()=>{C(F.adapter.id);}]:[]][A]?.();},[o,i,U,$,O,C]),k=useCallback(()=>f("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,F)=>{if(F.upArrow){a(J=>Math.max(0,J-1));return}if(F.downArrow){a(J=>Math.min(o.length,J+1));return}(F.return||F.tab)&&(i===0?I.startAdd():(u("detail"),d(0)));},{isActive:g==="main"&&I.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,F)=>{if(F.escape||F.tab){u("list");return}if(F.upArrow){d(J=>Math.max(0,J-1));return}if(F.downArrow){let J=o[i-1],De=J?om(J)-1:0;d(ms=>Math.min(ms+1,De));return}F.return&&ne(c);},{isActive:g==="main"&&I.phase==="idle"&&l==="detail"&&e==="marketplaces"}),I.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:I.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.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(I.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:I.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:I.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:I.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(I.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 F=A.adapter.id??"default",J=new Set(n.filter(De=>De.marketplace===A.adapter.name).map(De=>`${De.name}@${F}`));return jsx(lm,{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,X=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(rm,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(nm,{entry:H,detailData:m,installedCount:X,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 hm(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=se.findIndex(i=>i.id===r.activeTab),s=se[(o-1+se.length)%se.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=se.findIndex(i=>i.id===r.activeTab),s=se[(o+1)%se.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=se.findIndex(i=>i.id===r.activeTab),s=se[(o+1)%se.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 ym(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function wm(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 Ab=new Set(se.filter(e=>e.focus!=="list").map(e=>e.focus));function Yo(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}=ze.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 Sm({listLength:e}){let t=S(f=>f.focus),r=S(f=>f.selectedIndex),n=S(f=>f.actionMenuOpen),o=S(f=>f.setFocus),s=S(f=>f.setActionMenuOpen),i=ze(f=>f.query),a=ze(f=>f.setQuery),l=ze(f=>f.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:f,setCursorPosition:h}=ze.getState();h(f.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let f=setTimeout(()=>d(i),300);return ()=>clearTimeout(f)},[i]),useInput((f,h)=>{let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(pl(f,h,{activeTab:y}));},{isActive:t==="tabs"}),useInput((f,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(pl("",h,{activeTab:y}));},{isActive:Ab.has(t)}),useInput((f,h)=>{let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(hm(f,h,{activeTab:y,selectedIndex:I},u.current));},{isActive:t==="list"}),useInput((f,h)=>{Yo(ym(f,h));},{isActive:t==="actionMenu"}),useInput((f,h)=>{let y=wm(f,h,ze.getState().query),I=y.queryUpdate;if(Yo(y.actions),I==="reset")l(),d("");else if(I!==null){let{query:M,cursorPosition:D,setCursorPosition:C}=ze.getState();if("backspace"in I)D>0&&(a(M.slice(0,D-1)+M.slice(D)),C(D-1));else if("append"in I)a(M.slice(0,D)+I.append+M.slice(D)),C(D+I.append.length);else if("cursorMove"in I){let $=D+I.cursorMove;$>=0&&$<=M.length&&C($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(f=>{let{setSelectedIndex:h,selectedIndex:y}=S.getState();f===0?h(0):y>=f&&h(f-1);},[]),g=useCallback(f=>{if(!c)return u.current=f.length,f;let h=c.toLowerCase(),y=f.filter(I=>I.name.toLowerCase().includes(h)||I.description?.toLowerCase().includes(h));return u.current=y.length,y},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:g}}function bm(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=rt(a=>a.justAuthenticated),o=rt(a=>a.credentials),s=rt(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 Ke(e,t,r=false){return r?true:!tc.valid(e)||!tc.valid(t)?false:tc.gt(t,e)}j();R();var ir=x("updater");async function Rb(e,t,r,n,o,s){try{await T(E.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:te().interfaceType});}catch(i){ir.warn(`Failed to send update metrics: ${String(i)}`);}}function $b(e){let t=Ce(),r=`${e}@${me}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function _i(e,t={}){let r=Date.now(),n=null;try{ir.debug(`[${e}] Acquiring lock...`),n=await Lr();let o=$b(e);if(!o)throw ir.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;ir.debug(`[${e}] Fetching manifest...`);let u=(await Vn(e,t.source)).version;if(!i||!Ke(i,u,t.force))throw ir.debug(`[${e}] Already up to date (v${i??"n/a"})`),new $r(e,i??"unknown");ir.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Fe(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await Rb(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),ir.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){ir.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Lr();let d=Ce(),m=`${e}@${me}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,at(d),ir.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Mr();R();var Di=x("dispatcher");async function Mb(e,t,r,n,o){let s=Fn(e);return Di.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await xi(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Di.debug(`[${e}] Retrying install after marketplace add`),Le(t)}async function Im(e,t,r,n){let o=jn(e,n),s=Fn(e);r?.onStatus?.(`Installing ${s}...`),Di.debug(`[${e}] Attempting install: ${o}`);let i=await Le(o);if(i.exitCode===0)return i;Di.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Mb(e,o,a,t,r)}async function vm(e,t,r){let n=e.type??"bundle",o=await Wt.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 Em(){let e=Se(i=>i.installedItems),t=Se(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await vm(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=de().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Wt.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 Bo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await _i(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var Ui=x("mcp");function Zo(e,t){e.silent?Ue({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):v(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Pm(e,t){e.silent?ge({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(Y(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&b(t.stdout));}function Lb(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 rc(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 Cm(e,t,r){if(!await Z())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Zo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Ui.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Lb(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===wb){o=(o-1+t.length)%t.length,a(),s="";return}if(s===Sb){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${Tp(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);})}Mr();var Gn=b("claudeProxy"),Wl="claude ",Pp="flow ",Hl=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Wn=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";}},xb=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ib=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,vb={"--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}$/},Eb=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Tb=/^(flow|claude)\s+auth\s+login(\s|$)/,Cp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function kp(e){return Cp.test(e.trim())}function Pb(e){return Cp.exec(e.trim())?.[2]??""}async function Ap(e){let t=Pb(e);Tl(t);let r=Date.now();Gn.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 Gl(n)?new Vl:n}}function Cb(e){Rp(e);let t=e.slice(Wl.length);if(!xb.test(t))throw new Wn(e)}var Si=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Vl=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Rp(e){if(!e||!/^claude /.test(e))throw new Hl(e)}function kb(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Ib.test(r))throw new Wn(`Unexpected flag: ${r}`);let n=vb[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Wn(`Flag ${r} requires a value`);if(!n.test(o))throw new Wn(`Unsafe value for flag ${r}`);t++;}}}async function Le(e){Rp(e);let t=e.slice(Wl.length).split(/\s+/).filter(Boolean);kb(t);let r=Ab(t);Gn.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 Gn.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 Gl(o)?new Si:o}}function Ab(e){return e.length>=3?e[2]:e.join(" ")}function Gl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Rb(e){return e.startsWith(Pp)?Wl+e.slice(Pp.length):e}function $b(e){return Eb.test(e)||Tb.test(e)}function Mb(e){let t=0;for(;t<e.length&&$b(e[t]);)t++;return e.slice(t)}var Lb=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function _b(e,t){return !t||e.includes("--scope")||!Lb.test(e)?e:`${e} --scope ${t}`}async function jo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Mb(r).map(i=>Rb(i)).map(i=>_b(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Cb(i);Gn.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 bi(e,t,r){let n=Fn(e),o=t?.trim();if(!o&&(o=(await Jn(`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=mi(o),r?.(),Gn.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"}`);Gn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Gl(s)?new Si:s}}Mr();j();Oe();R();var Bb=6e4,Or=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:Bb},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 Or("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Or(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Or(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Tt(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 dn(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 jb(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Kb(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Hb(e){return typeof e=="object"&&e!==null&&e.source==="github"}function pn(e,t){let r=e.source;if(jb(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(Kb(r))return {cloneUrl:r.url,subPath:"."};if(Hb(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 Pt=b("claude-code.adapter");function Jb(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=Jr();if(!ie__default.existsSync(s))return r;try{let i=JSON.parse(ie__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Np(e,t){let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=pn(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=Jb(e.catalogId,r?.source),i=t.scope??"user",a;o?a=ka(s,e.name,"external"):a=join(Wr(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(ie__default.existsSync(a)&&ie__default.rmSync(a,{recursive:!0,force:!0}),ie__default.mkdirSync(dirname(a),{recursive:!0}),ie__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Ul(),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),Uo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Pt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Tt(l).catch(()=>{});}}async function zl(e,t,r,n){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:ui(n),version:"unknown",duration_ms:t,interface:te().interfaceType});}catch(o){Pt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Dp(e,t,r){try{await T(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:te().interfaceType});}catch(n){Pt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Wb={async install(e,t){if(e.origin===yn&&!e.installCommand&&!Bn(e.name))return Np(e,t);if(e.origin===yn&&e.installCommand){let r=e.type??"skill",n=await jo(e.installCommand,t.scope);return n.exitCode===0?(await zl(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Dp(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(Bn(e.name)){let r=e.type??"skill",n=jn(e.name,t.scope);Pt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Le(n);if(o.exitCode===0)return await zl(e.name,o.duration_ms,r,t.scope),{success:true};Pt.debug(`[${e.name}] First attempt failed, adding marketplace`),await bi(e.name,t.marketplaceSource,()=>{});let s=await Le(n);return s.exitCode===0?(await zl(e.name,s.duration_ms,r,t.scope),{success:true}):(await Dp(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 Fe(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Pt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await No(e,t);},getInstallPath(e,t){return ""}};function Op(e){return {async install(t,r){if(t.origin===yn&&!t.installCommand&&!Bn(t.name))return Np(t,r);if(!t.installCommand)try{let o=await Fe(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Pt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Pt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await 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=Ce(),o=`${t}@${pe}`;if(n.plugins[o]){await No(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 Gb(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ie__default.existsSync(t))continue;let r=ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function zb(e){for(let t of [join(e,".claude","rules"),join(e,"rules")]){if(!ie__default.existsSync(t))continue;let r=ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}async function Xl(e,t,r,n){let o=await Ul(),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 Xb={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(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=Gb(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=bs(r);ie__default.mkdirSync(l,{recursive:!0});let u=lt(e.name);if(a.length===1)ie__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=lt(basename(d,".md"));ie__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Xl(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){let r=bs(t),n=lt(e);if(ie__default.existsSync(r))for(let a of ie__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ie__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ce(),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(bs(t),`${lt(e)}.md`)}},qb={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(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=zb(i);if(a.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let l=vn(r);ie__default.mkdirSync(l,{recursive:!0});for(let u of a)ie__default.copyFileSync(u,join(l,basename(u)));return await Xl(e.name,r,l,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Rule install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,t){return vn(t)}},Yb={async install(e,t){let r=t.scope??"user",n=e.catalogId?he.getAdapter(e.catalogId):void 0,o=pn(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(!ie__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ie__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Po();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=Fo(m,u);return Ks({...d,hooks:p}),await Xl(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Pt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Tt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},xi=class{id="claude-code";name="Claude Code";async isAvailable(){return dn("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Wb,skill:Op("skill"),mcp:Op("mcp"),agent:Xb,hook:Yb,rule:qb}};function Ii(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 Qb=new Set(["gh"]),ex=Ii(Qb,"use: gh copilot mcp remove <name>"),vi=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await dn("gh",["--version"])?dn("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:ex}};Oe();var tx=new Set(["opencode"]),rx=Ii(tx,"use: opencode config remove mcp <name>");function nx(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 Bp(){return {async install(e,t){try{it(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?he.getAdapter(e.catalogId):void 0,n=pn(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=Ss(t.scope??"user"),a=join(s,".opencode","plugins");if(ie__default.existsSync(a)){let l=ie__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ie__default.mkdirSync(i,{recursive:!0}),ie__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ie__default.existsSync(l)&&ie__default.rmSync(l,{recursive:!0,force:!0}),ie__default.mkdirSync(l,{recursive:!0}),ie__default.cpSync(s,l,{recursive:!0}),ie__default.mkdirSync(i,{recursive:!0}),ie__default.writeFileSync(join(i,`${e.name}.js`),nx(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 Tt(o).catch(()=>{});}},async uninstall(e,t){it(e);let r=Ss(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ie__default.existsSync(n)&&ie__default.rmSync(n,{force:true}),ie__default.existsSync(o)&&ie__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Ss(t),`${e}.js`)}}}var Ei=class{id="opencode";name="OpenCode";async isAvailable(){return dn("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:rx,skill:Bp(),bundle:Bp()}};var Jt=new ci;Jt.register(new xi);Pr()&&(Jt.register(new vi),Jt.register(new Ei));function Fp({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(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let y=l.find(I=>I.name===h);y?(d(y.id),a(false),s(true)):a(false);},[l]),g=useCallback(h=>{let y=zd(h);y?r(y,c):s(false);},[r,c]),f=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(y=>y.name),"Cancel"];return jsx(st,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(st,{itemName:`${e} \u2014 Choose scope`,actions:Wd,descriptions:Gd,onAction:g,onClose:f},"scope"):jsx(st,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}N();function Kp({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,f)=>{f.upArrow?a(h=>Math.max(0,h-1)):f.downArrow?a(h=>Math.min(d.length-1,h+1)):f.return?d[i]==="Confirm Install"?n():o():f.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 f=w(g.name??g.flowId),h=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((g,f)=>jsx(Box,{children:jsxs(Text,{bold:f===i,color:f===i?"cyan":void 0,children:[f===i?"\u203A ":" ",g]})},g))})]}):jsx(st,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Ci({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 Jp({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Ci({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:h=>{h==="Uninstall"?c():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function zp({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Ci({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 qn=b("bundle:installer"),Xp=/already exists/i;async function dx(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(kp(t)){let r=await Ap(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Xp.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(Xp.test(n))return;throw new Error(n)}}}async function px(e,t){try{await T(E.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){qn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function mx(e,t,r){try{await T(E.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){qn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function qp(e,t,r,n){try{await T(E.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){qn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function fx(e,t,r,n,o){try{await T(E.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){qn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Ri(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 px(i,o.length);let l=[],u=0,c=o.length;for(let[p,g]of o.entries()){let f=g.name??g.flowId,h=g.type??"unknown";if(!g.type){qn.warn(`Artifact "${f}" has no type \u2014 treated as failed`),l.push({name:f,type:h,reason:"unknown artifact type"}),await qp(i,f,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await dx(g),u++,await mx(i,f,h),r?.({index:p+1,total:c,artifact:g,success:!0});}catch(y){let I=y instanceof Error?y.message:String(y);qn.error(`Failed to install artifact "${f}": ${I}`),l.push({name:f,type:h,reason:I}),await qp(i,f,h,I),r?.({index:p+1,total:c,artifact:g,success:false,error:I});}}let d=Date.now()-a,m=l.length;return await fx(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}N();function em({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Ri(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(Qp,{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(Qp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var be=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ue()})}));N();function tm({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 ",_t(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}N();function rm({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 ${_t(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((f,h)=>{let y=h===o;return jsxs(Box,{children:[jsx(Text,{color:y?"cyan":void 0,children:y?"\u203A ":" "}),jsx(Text,{bold:y,color:f.danger?"yellow":void 0,dimColor:!y,children:f.label})]},f.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 nm(e){return e.adapter.removable!==false?4:2}j();N();function om({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 im({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 am({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(D=>Math.max(0,D-1));return}$.downArrow&&u(D=>Math.min(a.length-1,D+1));},{isActive:c===null}),c!==null)return jsx(om,{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),f=m,h=a.length-p,y=s.length>0&&m<s.length,I=p>s.length,M=g.filter(C=>r.has(`${C.name}@${o}`)),_=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:f>0?`\u2191 ${f} more above`:" "})}),y&&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"]}),M.map(C=>jsx(im,{item:C,isSelected:a.indexOf(C)===l,isInstalled:true},C.name))]}),I&&jsxs(Box,{flexDirection:"column",marginTop:y?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"]}),_.map(C=>jsx(im,{item:C,isSelected:a.indexOf(C)===l,isInstalled:false},C.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2193 ${h} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}Cl();var xx=/^https?:\/\/.+/;function Ix(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function vx(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function dm(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),g=useCallback(()=>{o("idle");},[]),f=useCallback(async()=>{let h=m.current,y=d.current;if(!xx.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let I=randomUUID(),M=new Hn(I,y,h);try{await M.fetchItems(),await rr.add({id:I,name:y,source:h}),he.register(new Hn(I,y,h)),r(),e(),t(`Catalog "${y}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(_){let C=Ix(_)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":vx(_)?_.message:_ instanceof Error?`Could not reach catalog URL: ${_.message}`:"Failed to validate catalog URL";t(C,"error"),o("add-url");}},[e,t,r]);return useInput((h,y)=>{if(y.escape){o("idle");return}if(y.return){d.current.trim().length>0&&o("add-url");return}if(y.backspace||y.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!y.ctrl&&!y.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,y)=>{if(y.escape){o("add-name");return}if(y.return){f();return}if(y.backspace||y.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!y.ctrl&&!y.meta&&(m.current=m.current+h,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:g}}function pm(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await rr.remove(o),he.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function fm(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=be(A=>A.installedItems),[o,s]=useState(()=>he.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[g,f]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{g==="browse"&&!o[i-1]&&f("main");},[g,o,i]);let y=useCallback(()=>{(async()=>{let A=he.listAdapters(),F=await rr.read(),W=new Map(F.map(De=>[De.id,De]));s(A.map(De=>({adapter:De,stored:W.get(De.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),y();},[t,y]),useEffect(()=>{if(i===0){p(null);return}let A=h.current[i-1];if(!A)return;let F=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(W=>{F||p({items:W,loading:false,error:null});}).catch(W=>{F||p({items:[],loading:false,error:W instanceof Error?W.message:"Failed to load catalog"});}),()=>{F=true;}},[i]);let I=dm(y),M=useCallback(()=>{y(),a(0),u("list"),p(null),f("main");},[y]),{handleRemove:_}=pm(M),C=useCallback(async A=>{f("removing"),await _(A);},[_]),$=useCallback(async A=>{try{let F=await A.adapter.fetchItems();if(p({items:F,loading:!1,error:null}),A.stored){let W=new Date().toISOString();await rr.updateField(A.stored.id,{lastUpdated:W}),y();}r("Marketplace updated","success");}catch(F){r(F instanceof Error?F.message:"Update failed","error");}},[y,r]),D=useCallback(async A=>{if(!A.stored)return;let F=A.stored.autoUpdate!==false;await rr.updateField(A.stored.id,{autoUpdate:!F}),y();},[y]),U=useCallback(()=>f("browse"),[]),ne=useCallback(A=>{let F=o[i-1];if(!F)return;let W=F.adapter.removable!==false;[U,()=>{$(F);},...W?[()=>{D(F);},()=>{C(F.adapter.id);}]:[]][A]?.();},[o,i,U,$,D,C]),k=useCallback(()=>f("main"),[]),V=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),re=useCallback(()=>{let A=o[i-1];A&&D(A);},[o,i,D]),K=useCallback(()=>{let A=o[i-1];A&&C(A.adapter.id);},[o,i,C]);if(useInput((A,F)=>{if(F.upArrow){a(W=>Math.max(0,W-1));return}if(F.downArrow){a(W=>Math.min(o.length,W+1));return}(F.return||F.tab)&&(i===0?I.startAdd():(u("detail"),d(0)));},{isActive:g==="main"&&I.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,F)=>{if(F.escape||F.tab){u("list");return}if(F.upArrow){d(W=>Math.max(0,W-1));return}if(F.downArrow){let W=o[i-1],De=W?nm(W)-1:0;d(ms=>Math.min(ms+1,De));return}F.return&&ne(c);},{isActive:g==="main"&&I.phase==="idle"&&l==="detail"&&e==="marketplaces"}),I.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:I.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.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(I.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:I.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:I.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),I.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:I.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(I.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 F=A.adapter.id??"default",W=new Set(n.filter(De=>De.marketplace===A.adapter.name).map(De=>`${De.name}@${F}`));return jsx(am,{entry:A,items:m?.items??[],installedKeys:W,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,X=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(tm,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&H?jsx(rm,{entry:H,detailData:m,installedCount:X,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 gm(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=se.findIndex(i=>i.id===r.activeTab),s=se[(o-1+se.length)%se.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=se.findIndex(i=>i.id===r.activeTab),s=se[(o+1)%se.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=se.findIndex(i=>i.id===r.activeTab),s=se[(o+1)%se.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 hm(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function ym(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 kx=new Set(se.filter(e=>e.focus!=="list").map(e=>e.focus));function Yo(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}=ze.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 wm({listLength:e}){let t=S(f=>f.focus),r=S(f=>f.selectedIndex),n=S(f=>f.actionMenuOpen),o=S(f=>f.setFocus),s=S(f=>f.setActionMenuOpen),i=ze(f=>f.query),a=ze(f=>f.setQuery),l=ze(f=>f.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:f,setCursorPosition:h}=ze.getState();h(f.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let f=setTimeout(()=>d(i),300);return ()=>clearTimeout(f)},[i]),useInput((f,h)=>{let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(dl(f,h,{activeTab:y}));},{isActive:t==="tabs"}),useInput((f,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(dl("",h,{activeTab:y}));},{isActive:kx.has(t)}),useInput((f,h)=>{let{activeTab:y,selectedIndex:I,actionMenuOpen:M}=S.getState();Yo(gm(f,h,{activeTab:y,selectedIndex:I},u.current));},{isActive:t==="list"}),useInput((f,h)=>{Yo(hm(f,h));},{isActive:t==="actionMenu"}),useInput((f,h)=>{let y=ym(f,h,ze.getState().query),I=y.queryUpdate;if(Yo(y.actions),I==="reset")l(),d("");else if(I!==null){let{query:M,cursorPosition:_,setCursorPosition:C}=ze.getState();if("backspace"in I)_>0&&(a(M.slice(0,_-1)+M.slice(_)),C(_-1));else if("append"in I)a(M.slice(0,_)+I.append+M.slice(_)),C(_+I.append.length);else if("cursorMove"in I){let $=_+I.cursorMove;$>=0&&$<=M.length&&C($);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(f=>{let{setSelectedIndex:h,selectedIndex:y}=S.getState();f===0?h(0):y>=f&&h(f-1);},[]),g=useCallback(f=>{if(!c)return u.current=f.length,f;let h=c.toLowerCase(),y=f.filter(I=>I.name.toLowerCase().includes(h)||I.description?.toLowerCase().includes(h));return u.current=y.length,y},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:g}}function bm(){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 Ke(e,t,r=false){return r?true:!ec.valid(e)||!ec.valid(t)?false:ec.gt(t,e)}j();R();var ir=b("updater");async function Ax(e,t,r,n,o,s){try{await T(E.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:te().interfaceType});}catch(i){ir.warn(`Failed to send update metrics: ${String(i)}`);}}function Rx(e){let t=Ce(),r=`${e}@${pe}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function _i(e,t={}){let r=Date.now(),n=null;try{ir.debug(`[${e}] Acquiring lock...`),n=await Lr();let o=Rx(e);if(!o)throw ir.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;ir.debug(`[${e}] Fetching manifest...`);let u=(await Vn(e,t.source)).version;if(!i||!Ke(i,u,t.force))throw ir.debug(`[${e}] Already up to date (v${i??"n/a"})`),new $r(e,i??"unknown");ir.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Fe(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await Ax(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),ir.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){ir.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Lr();let d=Ce(),m=`${e}@${pe}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,at(d),ir.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Mr();R();var Di=b("dispatcher");async function $x(e,t,r,n,o){let s=Fn(e);return Di.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await bi(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Di.debug(`[${e}] Retrying install after marketplace add`),Le(t)}async function xm(e,t,r,n){let o=jn(e,n),s=Fn(e);r?.onStatus?.(`Installing ${s}...`),Di.debug(`[${e}] Attempting install: ${o}`);let i=await Le(o);if(i.exitCode===0)return i;Di.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return $x(e,o,a,t,r)}async function Im(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 vm(){let e=be(i=>i.installedItems),t=be(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Im(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=ue().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 Bo(i,u,a),t();},[e,t]),s=useCallback(async i=>{await _i(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}N();R();var Ui=b("mcp");function Zo(e,t){e.silent?Ue({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):v(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Tm(e,t){e.silent?fe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(Y(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&x(t.stdout));}function Mx(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 tc(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 Pm(e,t,r){if(!await Z())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Zo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Ui.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Mx(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 Ui.debug(`[${e}] Installation cancelled by user`),b("Operation cancelled."),0}let o=r.silent?void 0:na({text:`Adding MCP "${w(e)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(Zo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&b(`stdout: ${s.stdout}`),1):(Pm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Zo(r,{name:e,action:"add",message:Q(s)}),1}}async function km(e,t){if(!await Z())return 1;Ui.debug(`[${e}] Starting MCP remove`);let r=rc(e,t.scope);if(!t.force){let o=w(e),s=w(r);if(!await z(`Remove MCP "${o}"?
119
+ [y/N] `))return Ui.debug(`[${e}] Installation cancelled by user`),x("Operation cancelled."),0}let o=r.silent?void 0:na({text:`Adding MCP "${w(e)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(Zo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&x(`stdout: ${s.stdout}`),1):(Tm(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Zo(r,{name:e,action:"add",message:Q(s)}),1}}async function Cm(e,t){if(!await Z())return 1;Ui.debug(`[${e}] Starting MCP remove`);let r=tc(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 Ui.debug(`[${e}] Removal cancelled by user`),b("Operation cancelled."),0}let n=t.silent?void 0:na({text:`Removing MCP "${w(e)}"...`}).start();try{let o=await Le(r);return n?.stop(),o.exitCode!==0?(Zo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&b(`stdout: ${o.stdout}`),1):(Pm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Zo(t,{name:e,action:"remove",message:Q(o)}),1}}R();function Am({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(C=>C.setLoading),u=S(C=>C.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Em(),g=async(C,$,O)=>{l(true,C),n();try{await $(),o(r.length),s(O,"success");}catch(U){let ne=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${ne}`),s(ne,"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 ne=Date.now();(ne-a.current>100||O>=U)&&(a.current=ne,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 $r)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 ne=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 ${ne}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${ne}/${$}; failed: ${k.join(", ")}`,ne>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:C=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let $=rc(e.name,C),O=await Le($);if(O.exitCode!==0)throw new Error(O.stderr||"MCP removal failed");Se.getState().loadFromDisk();},"\u2713 MCP removed");}}}Mo();R();var Qo=x("api:bundle"),to=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},es=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Ob=/^[a-zA-Z0-9_-]{1,128}$/;async function $m(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Qo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new to(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new es:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Qo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Mm(e){if(!Ob.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Qo.debug(`Fetching bundle by flowId "${e}"`);try{return await Kt().get(`v1/use-cases/${t}`).json()}catch(r){return $m(r,e)}}async function Ni(e){let t=encodeURIComponent(e);Qo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Kt().get(`v1/use-cases/by-name/${t}`).json(),Qo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return $m(n,e)}if(r.length===0)throw new to(e);return r[0]}R();var Ub=x("tui:bundle-flow");function Lm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Ub.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Mm(d):Ni(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(),Se.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}N();j();var ts=["local","project","user"],Nb=new Set(["--transport","--scope","-s"]);function _m(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(Nb.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function fn(e,t){return t?`${e}::${t}`:e}function nc(e){return e===me?po:yn}function Dm(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??po,flowId:e.flowId}}function oc(e,t){let r=nc(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 Om(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 ts.filter(r=>t.has(r)).map(r=>({scope:r,label:Lt[r].label,pathHint:Lt[r].pathHint,items:t.get(r)??[]}))}function Um(e){let t=r=>{if(!r)return 1/0;let n=ts.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Nm({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(g=>fn(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(h=>[fn(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let y=g.get(fn(h.name,h.author?.name))??f.get(h.name),I=y?.version,M=!!I&&!!h.version&&Ke(h.version,I);return {...h,updateAvailable:M,catalogItem:y}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(g=>{if(s.has(fn(g.name,g.author?.name)))return false;if(g.type==="mcp"){let f=g.installCommand?_m(g.installCommand)?.toLowerCase():null;if(i.has(g.name.toLowerCase())||f&&i.has(f))return false}return true}).map(g=>Dm(g)):r==="updates"?a.filter(g=>g.updateAvailable).map(g=>oc(g,g.catalogItem)):a.map(g=>oc(g,g.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(g=>{let f=g.type??"bundle";if(!n.types.has(f))return false;let h=g.origin??"internal";return n.origins.has(h)}),[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(h=>[fn(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return h=>h?g.get(fn(h.name,h.authorName))??f.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(g=>g.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function sc(){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 dp();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,T(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 Bm(){return {items:Se(t=>t.installedItems)}}R();var Hb=x("catalog");function jm(){let e=S(q=>q.bundleInstallFlow),t=S(q=>q.activeTab),r=S(q=>q.notification),n=S(q=>q.loading),o=S(q=>q.loadingMessage),s=S(q=>q.downloadProgress),i=S(q=>q.downloadTotal),a=S(q=>q.catalogError),l=S(q=>q.setCatalogError),u=S(q=>q.catalogFilters),c=ze(q=>q.query),{catalog:d,isLoading:m,error:p,refetch:g}=sc(),{items:f}=Bm(),h=Se(q=>q.loadFromDisk),{items:y,emptyMessage:I,getSelectedCatalogItem:M,outdatedCount:D}=Nm({catalog:d,installedItems:f,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:O,clampIndex:U,filteredItems:ne}=Sm({listLength:y.length}),k=ne(y),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:Um(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Om(V):[],[t,V]),K=V[O]??null,H=useMemo(()=>M(K),[M,K]),{notify:X}=bm(),{handleInstall:A,handleUninstall:F,handleToggleStatus:J,handleUpdate:De,handleBatchUpdate:ms,handleMcpConfigUninstall:Oh}=Am({selectedItem:K,selectedCatalogItem:H,items:y,closeMenu:$,clampIndex:U,notify:X}),{handleBundleInstallStart:Uh,handleBundleDetailConfirm:Nh,handleBundleDetailBack:Bh,handleBundleInstallComplete:Fh}=Lm({closeMenu:$,notify:X}),jh=useCallback(()=>ms(V),[ms,V]);return useEffect(()=>{h();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(Hb.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(_n,{}),jsx(xd,{outdatedCount:D}),t==="marketplaces"&&Pr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(gm,{})}):jsx(Nd,{filteredItems:V,groups:re,emptyMessage:I,onBatchUpdate:jh}),(n||m)&&jsxs(Fragment,{children:[jsx(oi,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(ii,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(ai,{message:a,onRetry:()=>{l(null),g();},onBack:()=>l(null)}),r&&jsx(Bd,{message:r.message,type:r.type}),C&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(tm,{bundle:e.bundle,onComplete:Fh}):jsx(Hp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Uh(K.name,K.flowId),onConfirm:Nh,onClose:e?.phase==="detail"?Bh:$}):jsx(jp,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(Xp,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Oh,onClose:$}):jsx(Jp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:F,onToggleStatus:q=>J(q),onUpdate:De,onClose:$})),jsx(ni,{})]})}var L=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(Se.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"})}));Pe();var zb=3;function Hm(){let e=L(c=>c.setStarterKits),t=L(c=>c.setIsLoadingStarterKits),r=L(c=>c.setStarterKitsError),n=L(c=>c.setPluginStatus),o=L(c=>c.setPluginDownloadProgress),s=L(c=>c.setStep),i=L(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await fi();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{Se.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=L.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 f=1;f<=zb;f++)try{await Fe(m.name,{onDownloadProgress:(h,y)=>{let I=Date.now();(I-l.current>100||h>=y)&&(l.current=I,o(m.name,h,y));}}),n(m.name,"success"),g=!0;break}catch(h){if(h instanceof Xe){n(m.name,"success"),g=true;break}p=h instanceof Error?h.message:"Unknown error";}g||(n(m.name,"failed",p),T(E.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:te().interfaceType}).catch(()=>{}));}let d=Zr();Yr("summary_review"),T(E.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),Se.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var rs={cursorDelta:0,confirm:false,back:false};function Vm(e,t){return t.upArrow?{...rs,cursorDelta:-1}:t.downArrow?{...rs,cursorDelta:1}:t.escape?{...rs,back:true}:t.return?{...rs,confirm:true}:rs}var Xb={cursorDelta:0,select:false};function Wm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Xb}N();var Jm=Nw.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 pc=5;function Gm({onRetry:e}){let t=L(c=>c.starterKits),r=L(c=>c.selectedStarterKitIndex),n=L(c=>c.isLoadingStarterKits),o=L(c=>c.starterKitsError);if(n)return jsx(oi,{message:"Loading Starter Kits..."});if(o)return jsx(ai,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Dn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(pc/2)),i=Math.min(t.length,s+pc);i===t.length&&(s=Math.max(0,i-pc));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(Jm,{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 Xm=Nw.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 gc=8;function qm(){let e=L(c=>c.selectedStarterKit),t=L(c=>c.plugins),r=L(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,T(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(gc/2)),i=Math.min(t.length,s+gc);i===t.length&&(s=Math.max(0,i-gc));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(Xm,{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 oI=["Retry failed","Continue anyway"];function Ym({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(em,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(ii,{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 Zm({onComplete:e,onRetry:t}){let r=L(u=>u.plugins),n=L(u=>u.step),o=L(u=>u.successCount),s=L(u=>u.failedCount),i=L(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(Ym,{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(Ym,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:oI.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 Qm(){let e=L(k=>k.step),t=L(k=>k.starterKits),r=L(k=>k.selectedStarterKitIndex),n=L(k=>k.setSelectedStarterKitIndex),o=L(k=>k.selectStarterKit),s=L(k=>k.plugins),i=L(k=>k.pluginCursorIndex),a=L(k=>k.setPluginCursorIndex),l=L(k=>k.setStep),u=L(k=>k.summaryActionIndex),c=L(k=>k.setSummaryActionIndex),d=L(k=>k.failedCount),m=L(k=>k.resetForRetry),p=L(k=>k.goBackToList),g=S(k=>k.setScreen),f=S(k=>k.setFocus),h=S(k=>k.focus),y=rt(k=>k.setJustAuthenticated),I=rt(k=>k.justAuthenticated),{loadStarterKits:M,installSelected:D}=Hm(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),C.current||(C.current=true,Yr("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let $=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let re=await ee();re&&await br({...re,starterKit:k.slug});}T(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Zr()}).catch(()=>{});let{successCount:V}=L.getState();T(E.CLI_ONBOARDING_COMPLETED,{duration_ms:vr(),tools_installed_count:V}).catch(()=>{}),y(false),f("verify"),g("verify");},[y,f,g]),O=useCallback(()=>{m(),D();},[m,D]),U=useCallback(()=>{M();},[M]),ne=useCallback(()=>{f("verify"),g("verify");},[f,g]);return useInput((k,V)=>{if(V.escape)Fs("esc"),ne();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=Zr();o(t[r]),Yr("kit_display"),T(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((k,V)=>{let re=Vm(k,V);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=L.getState().selectedStarterKit;K&&(async()=>(await ee())?.starterKit!==K.slug&&T(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=Zr();Yr("kit_confirmation"),T(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let X=Zr();Yr("tool_installation"),T(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:X}).catch(()=>{}),l("installing"),D();}if(re.back){let K=L.getState().selectedStarterKit;K&&T(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let re=Wm(k,V);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?O():$());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(_n,{}),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."}),!I&&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(Gm,{onRetry:U}),e==="starterKitDetail"&&jsx(qm,{}),(e==="installing"||e==="summary")&&jsx(Zm,{onComplete:$,onRetry:O})]}),jsx(ni,{})]})}j();var rf=null;function nf(){return rf}async function Ji(){let t=nn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=ce.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await of(n);(o||s)&&await xt({...r,installedVersion:o,installMethod:s});}}async function of(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await jt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function no(e){let t=await Promise.all(e.map(r=>aI(r)));return rf=t,t}async function aI(e){let t=ef(e.versionCommand);t==="permission-denied"&&(lI(e.versionCommand[0]),t=ef(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await jt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!nt(e.alias)){let{installedVersion:l,installMethod:u}=await of(e);await xt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function ef(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function lI(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=ie__default.realpathSync(r),{mode:o}=ie__default.statSync(n);ie__default.chmodSync(n,o|73);}catch{}}function dI(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 uf(e,t){let[r,n]=useState(()=>dI(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,f=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(f||h)f&&p>0?s(p-1):h&&p<g.length-1&&s(p+1);else if(d===" "){let y=g[p];y&&!y.module.required&&l(y.module.alias);}else if(m.tab){let y=g[p];if(y&&y.availableStrategies.length>1){let I=y.availableStrategies.indexOf(y.selectedStrategy??y.availableStrategies[0]),M=y.availableStrategies[(I+1)%y.availableStrategies.length];n(D=>D.map(C=>C.module.alias===y.module.alias?{...C,selectedStrategy:M}: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 pf({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}=uf(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 f=g===a,h=w(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:f?"cyan":void 0,children:[f?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children: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(ot,{itemName:m,actions:d,onAction:c,onClose:u})]})}var hI=/^https?:\/\/.+/;function mf({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&&hI.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 wI(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 hf(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=wI(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 Ar(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}}j();N();function yf({module:e}){let t=w(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(em,{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 bf({confirmedItems:e,customUrl:t}){let r=S(y=>y.setScreen),n=S(y=>y.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=hf(e,t),c=o.some(y=>y.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{on().catch(()=>{}),n("list");let y=de().some(I=>I.name===fe);r(y?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let y=setTimeout(p,1500);return ()=>clearTimeout(y)}},[i,l,c,p]),useInput((y,I)=>{I.return&&p();},{isActive:i});let g=o.filter(y=>y.pendingSetupCommand).length,f=a-g,h=[];return f>0&&h.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),g>0&&h.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(y=>jsx(yf,{module:y},y.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((y,I,M)=>(M>0&&y.push(jsx(Text,{children:" | "},`sep-${M}`)),y.push(I),y),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function vf(){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(td(p)){on().catch(()=>{}),l("list");let f=de().some(h=>h.name===fe);u(f?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=nf();if(p){c(p);return}no(ce).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let g=p.some(f=>f.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(pf,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(mf,{onConfirm:m}),e==="installation"&&jsx(bf,{confirmedItems:o,customUrl:i})]})}j();R();var kI=x("ClaudeMdSuggestion"),AI=[`Install ${fe}`,"Skip for now"],RI=["Retry","Skip for now"];function Pf(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{T(E.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,T(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Fe(fe),o("installed");}catch(m){if(m instanceof Xe){o("installed");return}kI.warn(`Failed to install ${fe}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?RI:AI;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(_n,{}),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(Tf,{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(em,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",fe,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",fe," 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:["/",fe]})]}),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 ",fe]}),jsx(Tf,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Tf({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 _I=promisify(execFile),Yi="@ciandt-flow/cli";async function Cf(){let e=ue;if(tc.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Yi};try{let t=await fetch(`https://registry.npmjs.org/${Yi}/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:Yi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Yi}}}async function Zi(e){try{return await _I(er(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function DI(e){let t=nt(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await jt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await xt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function kf(e){let t=await DI(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 Af(e,t){let r=nt(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await jt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await xt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Rf(e){let r=nt(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 $f(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ce.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([Cf(),no(ce),Promise.all(ce.map(l=>kf(l)))]);if(Ji(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Zi(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=ce.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 Af(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:Rf(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await on(),t(l=>({...l,outcome:"done"}));}catch{await on(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}j();function jI({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(em,{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 KI({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 Mf(){let{outcome:e,items:t}=$f(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=de().some(i=>i.name===fe);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(jI,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(KI,{outcome:e})})]})}Pe();An();R();La();var JI={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Lf=10;function _f(){let[e,t]=useState(Ma());useEffect(()=>wu(()=>{t([...Ma()]);}),[]);let r=e.slice(-Lf);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Lf,") \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:JI[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var qI=x("app"),YI={auth:pd,starterKitSetup:Qm,moduleSetup:vf,claudeMdSuggestion:Pf,verify:Mf,main:jm};function Uf(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function ei(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Nf(){T(E.CLI_SESSION_STARTED,{cli_version:ue,os:process.platform,node_version:process.version,duration_ms:vr(),interface:"tui"}).catch(()=>{});}async function Ff(){let e=await ee();if(e&&Qu()&&await Ir()){e.customUrl&&Dt(e.customUrl);let{clientSecret:n,...o}=e;rt.getState().setCredentials(o),Nf(),ei(e);return}if(!e){Uf();return}try{e.customUrl&&Dt(e.customUrl),await Ut();}catch(n){qI.debug(`Token validation failed: ${String(n)}`),Uf();return}Nf();let{clientSecret:t,...r}=e;rt.getState().setCredentials(r),ei(e);}function jf(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=YI[r],{pendingExit:o}=Vu(),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(_f,{}),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]})}Pe();Ns();N();j();R();yo();Pe();async function Cc(e,t={}){let r=Hs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Vs(r),await br(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=x("auth");function Hf(){Ge.clearFallbackFile(),_s();}var ZI=3,Kf=3,Vf=` \u2139 The data collected during setup is used solely to improve
121
+ [y/N] `))return Ui.debug(`[${e}] Removal cancelled by user`),x("Operation cancelled."),0}let n=t.silent?void 0:na({text:`Removing MCP "${w(e)}"...`}).start();try{let o=await Le(r);return n?.stop(),o.exitCode!==0?(Zo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&x(`stdout: ${o.stdout}`),1):(Tm(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Zo(t,{name:e,action:"remove",message:Q(o)}),1}}R();function km({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}=vm(),g=async(C,$,D)=>{l(true,C),n();try{await $(),o(r.length),s(D,"success");}catch(U){let ne=U instanceof Error?U.message:"Something went wrong";i.error(`[withLoading] ${C} failed: ${ne}`),s(ne,"error");}finally{l(false);}};return {handleInstall:(C,$)=>{e&&t&&(a.current=0,g(`Installing ${e.name}...`,()=>c(t,{scope:C,...$!==void 0?{providerId:$}:{},onDownloadProgress:(D,U)=>{let ne=Date.now();(ne-a.current>100||D>=U)&&(a.current=ne,u(D,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(D){if(D instanceof $r)s(D.message,"info");else {let U=D instanceof Error?D.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 ne=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 ${ne}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${ne}/${$}; failed: ${k.join(", ")}`,ne>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:C=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let $=tc(e.name,C),D=await Le($);if(D.exitCode!==0)throw new Error(D.stderr||"MCP removal failed");be.getState().loadFromDisk();},"\u2713 MCP removed");}}}Mo();R();var Qo=b("api:bundle"),to=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},es=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Dx=/^[a-zA-Z0-9_-]{1,128}$/;async function Rm(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Qo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new to(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new es:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Qo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function $m(e){if(!Dx.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Qo.debug(`Fetching bundle by flowId "${e}"`);try{return await Kt().get(`v1/use-cases/${t}`).json()}catch(r){return Rm(r,e)}}async function Ni(e){let t=encodeURIComponent(e);Qo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Kt().get(`v1/use-cases/by-name/${t}`).json(),Qo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Rm(n,e)}if(r.length===0)throw new to(e);return r[0]}R();var Ox=b("tui:bundle-flow");function Mm({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Ox.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?$m(d):Ni(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();j();var ts=["local","project","user"],Ux=new Set(["--transport","--scope","-s"]);function Lm(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(Ux.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function fn(e,t){return t?`${e}::${t}`:e}function rc(e){return e===pe?po:yn}function _m(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??po,flowId:e.flowId}}function nc(e,t){let r=rc(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 Dm(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 ts.filter(r=>t.has(r)).map(r=>({scope:r,label:Lt[r].label,pathHint:Lt[r].pathHint,items:t.get(r)??[]}))}function Om(e){let t=r=>{if(!r)return 1/0;let n=ts.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Um({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(g=>fn(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(h=>[fn(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let y=g.get(fn(h.name,h.author?.name))??f.get(h.name),I=y?.version,M=!!I&&!!h.version&&Ke(h.version,I);return {...h,updateAvailable:M,catalogItem:y}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(g=>{if(s.has(fn(g.name,g.author?.name)))return false;if(g.type==="mcp"){let f=g.installCommand?Lm(g.installCommand)?.toLowerCase():null;if(i.has(g.name.toLowerCase())||f&&i.has(f))return false}return true}).map(g=>_m(g)):r==="updates"?a.filter(g=>g.updateAvailable).map(g=>nc(g,g.catalogItem)):a.map(g=>nc(g,g.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(g=>{let f=g.type??"bundle";if(!n.types.has(f))return false;let h=g.origin??"internal";return n.origins.has(h)}),[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(h=>[fn(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return h=>h?g.get(fn(h.name,h.authorName))??f.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(g=>g.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function oc(){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 up();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,T(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 Nm(){return {items:be(t=>t.installedItems)}}R();var Kx=b("catalog");function Fm(){let e=S(q=>q.bundleInstallFlow),t=S(q=>q.activeTab),r=S(q=>q.notification),n=S(q=>q.loading),o=S(q=>q.loadingMessage),s=S(q=>q.downloadProgress),i=S(q=>q.downloadTotal),a=S(q=>q.catalogError),l=S(q=>q.setCatalogError),u=S(q=>q.catalogFilters),c=ze(q=>q.query),{catalog:d,isLoading:m,error:p,refetch:g}=oc(),{items:f}=Nm(),h=be(q=>q.loadFromDisk),{items:y,emptyMessage:I,getSelectedCatalogItem:M,outdatedCount:_}=Um({catalog:d,installedItems:f,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:C,closeMenu:$,selectedIndex:D,clampIndex:U,filteredItems:ne}=wm({listLength:y.length}),k=ne(y),V=useMemo(()=>t!=="installed"&&t!=="updates"?k:Om(k),[t,k]),re=useMemo(()=>t==="installed"||t==="updates"?Dm(V):[],[t,V]),K=V[D]??null,H=useMemo(()=>M(K),[M,K]),{notify:X}=bm(),{handleInstall:A,handleUninstall:F,handleToggleStatus:W,handleUpdate:De,handleBatchUpdate:ms,handleMcpConfigUninstall:Dh}=km({selectedItem:K,selectedCatalogItem:H,items:y,closeMenu:$,clampIndex:U,notify:X}),{handleBundleInstallStart:Oh,handleBundleDetailConfirm:Uh,handleBundleDetailBack:Nh,handleBundleInstallComplete:Bh}=Mm({closeMenu:$,notify:X}),Fh=useCallback(()=>ms(V),[ms,V]);return useEffect(()=>{h();},[]),useEffect(()=>{U(V.length);},[V.length,U]),useEffect(()=>{p&&(Kx.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(_n,{}),jsx(Sd,{outdatedCount:_}),t==="marketplaces"&&Pr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(fm,{})}):jsx(Ud,{filteredItems:V,groups:re,emptyMessage:I,onBatchUpdate:Fh}),(n||m)&&jsxs(Fragment,{children:[jsx(oi,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(ii,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(ai,{message:a,onRetry:()=>{l(null),g();},onBack:()=>l(null)}),r&&jsx(Nd,{message:r.message,type:r.type}),C&&K&&(t==="discover"?H?.type==="bundle"?e?.phase==="installing"?jsx(em,{bundle:e.bundle,onComplete:Bh}):jsx(Kp,{itemName:K.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Oh(K.name,K.flowId),onConfirm:Uh,onClose:e?.phase==="detail"?Nh:$}):jsx(Fp,{itemName:K.name,itemType:H?.type,onInstall:A,onClose:$}):K.type==="mcp"?jsx(zp,{itemName:K.name,itemScope:K.scope??"user",onUninstall:Dh,onClose:$}):jsx(Jp,{itemName:K.name,itemScope:K.scope??"user",itemStatus:K.status??"enabled",updateAvailable:K.updateAvailable??false,catalogVersion:H?.version,onUninstall:F,onToggleStatus:q=>W(q),onUpdate:De,onClose:$})),jsx(ni,{})]})}var L=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"})}));Pe();var Gx=3;function Km(){let e=L(c=>c.setStarterKits),t=L(c=>c.setIsLoadingStarterKits),r=L(c=>c.setStarterKitsError),n=L(c=>c.setPluginStatus),o=L(c=>c.setPluginDownloadProgress),s=L(c=>c.setStep),i=L(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await fi();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=L.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 f=1;f<=Gx;f++)try{await Fe(m.name,{onDownloadProgress:(h,y)=>{let I=Date.now();(I-l.current>100||h>=y)&&(l.current=I,o(m.name,h,y));}}),n(m.name,"success"),g=!0;break}catch(h){if(h instanceof Xe){n(m.name,"success"),g=true;break}p=h instanceof Error?h.message:"Unknown error";}g||(n(m.name,"failed",p),T(E.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:te().interfaceType}).catch(()=>{}));}let d=Zr();Yr("summary_review"),T(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 rs={cursorDelta:0,confirm:false,back:false};function Hm(e,t){return t.upArrow?{...rs,cursorDelta:-1}:t.downArrow?{...rs,cursorDelta:1}:t.escape?{...rs,back:true}:t.return?{...rs,confirm:true}:rs}var zx={cursorDelta:0,select:false};function Vm(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:zx}N();var Jm=Uw.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 dc=5;function Wm({onRetry:e}){let t=L(c=>c.starterKits),r=L(c=>c.selectedStarterKitIndex),n=L(c=>c.isLoadingStarterKits),o=L(c=>c.starterKitsError);if(n)return jsx(oi,{message:"Loading Starter Kits..."});if(o)return jsx(ai,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Dn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(dc/2)),i=Math.min(t.length,s+dc);i===t.length&&(s=Math.max(0,i-dc));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(Jm,{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 zm=Uw.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 fc=8;function Xm(){let e=L(c=>c.selectedStarterKit),t=L(c=>c.plugins),r=L(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,T(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(fc/2)),i=Math.min(t.length,s+fc);i===t.length&&(s=Math.max(0,i-fc));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(zm,{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 nI=["Retry failed","Continue anyway"];function qm({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(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(ii,{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 Ym({onComplete:e,onRetry:t}){let r=L(u=>u.plugins),n=L(u=>u.step),o=L(u=>u.successCount),s=L(u=>u.failedCount),i=L(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(qm,{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(qm,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:nI.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 Zm(){let e=L(k=>k.step),t=L(k=>k.starterKits),r=L(k=>k.selectedStarterKitIndex),n=L(k=>k.setSelectedStarterKitIndex),o=L(k=>k.selectStarterKit),s=L(k=>k.plugins),i=L(k=>k.pluginCursorIndex),a=L(k=>k.setPluginCursorIndex),l=L(k=>k.setStep),u=L(k=>k.summaryActionIndex),c=L(k=>k.setSummaryActionIndex),d=L(k=>k.failedCount),m=L(k=>k.resetForRetry),p=L(k=>k.goBackToList),g=S(k=>k.setScreen),f=S(k=>k.setFocus),h=S(k=>k.focus),y=nt(k=>k.setJustAuthenticated),I=nt(k=>k.justAuthenticated),{loadStarterKits:M,installSelected:_}=Km(),C=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),C.current||(C.current=true,Yr("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let $=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let re=await ee();re&&await xr({...re,starterKit:k.slug});}T(E.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Zr()}).catch(()=>{});let{successCount:V}=L.getState();T(E.CLI_ONBOARDING_COMPLETED,{duration_ms:vr(),tools_installed_count:V}).catch(()=>{}),y(false),f("verify"),g("verify");},[y,f,g]),D=useCallback(()=>{m(),_();},[m,_]),U=useCallback(()=>{M();},[M]),ne=useCallback(()=>{f("verify"),g("verify");},[f,g]);return useInput((k,V)=>{if(V.escape)Fs("esc"),ne();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=Zr();o(t[r]),Yr("kit_display"),T(E.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:re}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((k,V)=>{let re=Hm(k,V);if(re.cursorDelta!==0){let K=i+re.cursorDelta;K>=0&&K<s.length&&a(K);}if(re.confirm){let K=L.getState().selectedStarterKit;K&&(async()=>(await ee())?.starterKit!==K.slug&&T(E.CLI_KIT_ACCEPTED,{bundle_slug:K.slug}).catch(()=>{}))();let H=Zr();Yr("kit_confirmation"),T(E.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:H}).catch(()=>{});let X=Zr();Yr("tool_installation"),T(E.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:X}).catch(()=>{}),l("installing"),_();}if(re.back){let K=L.getState().selectedStarterKit;K&&T(E.CLI_KIT_REJECTED,{bundle_slug:K.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((k,V)=>{if(d===0)return;let re=Vm(k,V);if(re.cursorDelta!==0){let K=u+re.cursorDelta;K>=0&&K<=1&&c(K);}re.select&&(u===0?D():$());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(_n,{}),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."}),!I&&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(Wm,{onRetry:U}),e==="starterKitDetail"&&jsx(Xm,{}),(e==="installing"||e==="summary")&&jsx(Ym,{onComplete:$,onRetry:D})]}),jsx(ni,{})]})}j();var tf=null;function rf(){return tf}async function Wi(){let t=nn().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=ce.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await nf(n);(o||s)&&await bt({...r,installedVersion:o,installMethod:s});}}async function nf(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await jt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function no(e){let t=await Promise.all(e.map(r=>iI(r)));return tf=t,t}async function iI(e){let t=Qm(e.versionCommand);t==="permission-denied"&&(aI(e.versionCommand[0]),t=Qm(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await jt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ot(e.alias)){let{installedVersion:l,installMethod:u}=await nf(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 Qm(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 aI(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=ie__default.realpathSync(r),{mode:o}=ie__default.statSync(n);ie__default.chmodSync(n,o|73);}catch{}}function uI(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 cf(e,t){let[r,n]=useState(()=>uI(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,f=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(f||h)f&&p>0?s(p-1):h&&p<g.length-1&&s(p+1);else if(d===" "){let y=g[p];y&&!y.module.required&&l(y.module.alias);}else if(m.tab){let y=g[p];if(y&&y.availableStrategies.length>1){let I=y.availableStrategies.indexOf(y.selectedStrategy??y.availableStrategies[0]),M=y.availableStrategies[(I+1)%y.availableStrategies.length];n(_=>_.map(C=>C.module.alias===y.module.alias?{...C,selectedStrategy:M}: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 df({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=cf(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 f=g===a,h=w(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:f?"cyan":void 0,children:[f?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children: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 gI=/^https?:\/\/.+/;function pf({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&&gI.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 yI(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 gf(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=yI(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 Ar(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}}j();N();function hf({module:e}){let t=w(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{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 bf({confirmedItems:e,customUrl:t}){let r=S(y=>y.setScreen),n=S(y=>y.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=gf(e,t),c=o.some(y=>y.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{on().catch(()=>{}),n("list");let y=ue().some(I=>I.name===me);r(y?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let y=setTimeout(p,1500);return ()=>clearTimeout(y)}},[i,l,c,p]),useInput((y,I)=>{I.return&&p();},{isActive:i});let g=o.filter(y=>y.pendingSetupCommand).length,f=a-g,h=[];return f>0&&h.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),g>0&&h.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(y=>jsx(hf,{module:y},y.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((y,I,M)=>(M>0&&y.push(jsx(Text,{children:" | "},`sep-${M}`)),y.push(I),y),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function If(){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(ed(p)){on().catch(()=>{}),l("list");let f=ue().some(h=>h.name===me);u(f?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=rf();if(p){c(p);return}no(ce).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let g=p.some(f=>f.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(df,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(pf,{onConfirm:m}),e==="installation"&&jsx(bf,{confirmedItems:o,customUrl:i})]})}j();R();var CI=b("ClaudeMdSuggestion"),kI=[`Install ${me}`,"Skip for now"],AI=["Retry","Skip for now"];function Tf(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{T(E.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,T(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Fe(me),o("installed");}catch(m){if(m instanceof Xe){o("installed");return}CI.warn(`Failed to install ${me}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?AI:kI;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(_n,{}),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(Ef,{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(Qp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",me,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",me," 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:["/",me]})]}),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 ",me]}),jsx(Ef,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Ef({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 LI=promisify(execFile),Yi="@ciandt-flow/cli";async function Pf(){let e=ge;if(ec.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Yi};try{let t=await fetch(`https://registry.npmjs.org/${Yi}/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:Yi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Yi}}}async function Zi(e){try{return await LI(er(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function _I(e){let t=ot(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await jt(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 Cf(e){let t=await _I(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 kf(e,t){let r=ot(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await jt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await bt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Af(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 Rf(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ce.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([Pf(),no(ce),Promise.all(ce.map(l=>Cf(l)))]);if(Wi(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Zi(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=ce.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 kf(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:Af(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await on(),t(l=>({...l,outcome:"done"}));}catch{await on(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}j();function FI({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Qp,{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 jI({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 $f(){let{outcome:e,items:t}=Rf(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=ue().some(i=>i.name===me);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(FI,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(jI,{outcome:e})})]})}Pe();An();R();Ma();var JI={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Mf=10;function Lf(){let[e,t]=useState($a());useEffect(()=>yu(()=>{t([...$a()]);}),[]);let r=e.slice(-Mf);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Mf,") \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:JI[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var XI=b("app"),qI={auth:dd,starterKitSetup:Zm,moduleSetup:If,claudeMdSuggestion:Tf,verify:$f,main:Fm};function Of(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function ei(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Uf(){T(E.CLI_SESSION_STARTED,{cli_version:ge,os:process.platform,node_version:process.version,duration_ms:vr(),interface:"tui"}).catch(()=>{});}async function Bf(){let e=await ee();if(e&&Zu()&&await Ir()){e.customUrl&&Dt(e.customUrl);let{clientSecret:n,...o}=e;nt.getState().setCredentials(o),Uf(),ei(e);return}if(!e){Of();return}try{e.customUrl&&Dt(e.customUrl),await Ut();}catch(n){XI.debug(`Token validation failed: ${String(n)}`),Of();return}Uf();let{clientSecret:t,...r}=e;nt.getState().setCredentials(r),ei(e);}function Ff(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=qI[r],{pendingExit:o}=Hu(),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(Lf,{}),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]})}Pe();Ns();N();j();R();yo();Pe();async function Pc(e,t={}){let r=Hs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Vs(r),await xr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var Rt=b("auth");function Kf(){Ge.clearFallbackFile(),_s();}var YI=3,jf=3,Hf=` \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 qt(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
124
124
  `){l(),process.stdout.write(`
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 QI(){let e=tn();return process.stdout.write(`
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 ZI(){let e=tn();return process.stdout.write(`
126
126
  `+P.yellow(" \u26A0 ")+`${w(e)} contains invalid JSON.
127
- `),(await qt(P.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Wf(e,t,r){try{await Cc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof rn))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${tn()} and retry.`,{cause:n});if(!await QI())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Cc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function ev(){if((await qt(P.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await qt(P.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(wn.test(t))return t;process.stderr.write(P.yellow(` \u26A0 ${Sn}. Try again.
128
- `));}}async function tv(){let e=(await qt(P.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await qt(P.cyan(" ? ")+"Enter your email address: ")).trim();if(xn.test(t))return t;process.stderr.write(P.yellow(` \u26A0 ${bn}. Try again.
127
+ `),(await qt(P.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Vf(e,t,r){try{await Pc(e,{jwtOverride:r});return}catch(n){if(!(n instanceof rn))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${tn()} and retry.`,{cause:n});if(!await ZI())throw new Error("Setup cancelled: settings.json must be valid JSON to continue",{cause:n});await Pc(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function QI(){if((await qt(P.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await qt(P.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(wn.test(t))return t;process.stderr.write(P.yellow(` \u26A0 ${Sn}. Try again.
128
+ `));}}async function ev(){let e=(await qt(P.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await qt(P.cyan(" ? ")+"Enter your email address: ")).trim();if(bn.test(t))return t;process.stderr.write(P.yellow(` \u26A0 ${xn}. Try again.
129
129
  `));}}async function Jf(e,t){process.stdout.write(P.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await Qs(e,t);return r?process.stdout.write(P.yellow(` \u26A0 npm install failed. Please contact Flow support.
130
130
  `)):o?process.stdout.write(P.yellow(` \u26A0 Unexpected error. Please contact Flow support.
131
131
  `)):n?process.stdout.write(P.yellow(`
132
132
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
133
133
  `)):process.stdout.write(P.green(` done
134
- `)),{initFailed:n}}async function Gf(){for(let e=1;e<=Kf;e++)try{return await fi()}catch{if(e===Kf)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function zf(){let e=await Gf();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await qt(P.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 Wf(){for(let e=1;e<=jf;e++)try{return await fi()}catch{if(e===jf)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Gf(){let e=await Wf();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");let t=(await qt(P.cyan(" ? ")+"Install a starter kit? (y/N): ")).trim().toLowerCase();if(t!=="y"&&t!=="yes")return null;for(process.stdout.write(`
135
135
  `+P.cyan(" ? ")+`Starter Kit:
136
136
  `),e.forEach((r,n)=>{process.stdout.write(` ${P.cyan(`${n+1})`)} ${w(r.name)}
137
137
  `);}),process.stdout.write(`
138
138
  `);;){let r=(await qt(P.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(P.yellow(` \u26A0 Invalid selection. Please try again.
139
- `));}}async function Xf(e){if(e.plugins.length===0)return process.stdout.write(P.dim(`
139
+ `));}}async function zf(e){if(e.plugins.length===0)return process.stdout.write(P.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)}'...
143
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(P.dim(` [${s}/${n}] Installing ${w(o)}...`));let i=false;for(let a=1;a<=ZI;a++)try{await Fe(o),t++,i=!0;break}catch(l){if(l instanceof Xe){t++,i=true;break}}i?process.stdout.write(P.green(` done
143
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(P.dim(` [${s}/${n}] Installing ${w(o)}...`));let i=false;for(let a=1;a<=YI;a++)try{await Fe(o),t++,i=!0;break}catch(l){if(l instanceof Xe){t++,i=true;break}}i?process.stdout.write(P.green(` done
144
144
  `)):(r++,process.stdout.write(P.red(` failed
145
145
  `)));}return r===0?process.stdout.write(P.green(` \u2713 Starter kit '${w(e.name)}' selected. ${t}/${n} plugins installed successfully.
146
146
  `)):process.stdout.write(P.yellow(` \u26A0 Starter kit '${w(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
147
- `)),r===0}async function qf(){process.stdout.write(`
147
+ `)),r===0}async function Xf(){process.stdout.write(`
148
148
  `),process.stdout.write(P.bold(` Personalize your Claude Code
149
149
  `)),process.stdout.write(P.dim(` This plugin helps Claude understand your preferences and work style.
150
150
 
151
- `));let e=(await qt(P.cyan(" ? ")+`Install ${fe}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){T(E.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(P.dim(`
151
+ `));let e=(await qt(P.cyan(" ? ")+`Install ${me}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){T(E.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(P.dim(`
152
152
  You can always install it later from the catalog.
153
- `));return}T(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(P.dim(` Installing ${fe}...`));try{await Fe(fe),process.stdout.write(P.green(` done
153
+ `));return}T(E.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(P.dim(` Installing ${me}...`));try{await Fe(me),process.stdout.write(P.green(` done
154
154
  `));}catch(t){if(t instanceof Xe)process.stdout.write(P.green(` already installed
155
- `));else {Rt.warn(`Failed to install ${fe}: ${t instanceof Error?t.message:t}`),process.stdout.write(P.red(` failed
155
+ `));else {Rt.warn(`Failed to install ${me}: ${t instanceof Error?t.message:t}`),process.stdout.write(P.red(` failed
156
156
  `)),process.stdout.write(P.dim(` You can install it later from the catalog.
157
157
  `));return}}process.stdout.write(`
158
158
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
159
- `),process.stdout.write(P.cyan.bold(` /${fe}
159
+ `),process.stdout.write(P.cyan.bold(` /${me}
160
160
  `)),process.stdout.write(` Claude will guide you through the rest.
161
- `);}async function rv(e){if(Hf(),process.stdout.write(`
162
- `+Vf+`
161
+ `);}async function tv(e){if(Kf(),process.stdout.write(`
162
+ `+Hf+`
163
163
  `),e.customUrl!==void 0&&!wn.test(e.customUrl))return process.stderr.write(P.red(` \u2717 ${Sn}.
164
- `)),1;if(e.customEmail!==void 0&&!xn.test(e.customEmail))return process.stderr.write(P.red(` \u2717 ${bn}.
164
+ `)),1;if(e.customEmail!==void 0&&!bn.test(e.customEmail))return process.stderr.write(P.red(` \u2717 ${xn}.
165
165
  `)),1;let t=e.jwt.trim(),r;try{r=Co(t);}catch(o){let s=w(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(P.red(` \u2717 ${s}
166
166
  `)),1}e.customUrl&&Dt(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(P.red(` \u2717 Authentication failed: ${s}
167
- `)),1}let{initFailed:n}=await Jf(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Gf(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(P.red(` \u2717 Starter kit '${w(e.starterKit)}' not found.
167
+ `)),1}let{initFailed:n}=await Jf(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Wf(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(P.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 zf();return await Wf({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await Xf(o):process.stdout.write(P.dim(`
170
+ `);return 1}o=i;}else o=await Gf();return await Vf({...r,starterKit:o?.slug,customUrl:e.customUrl},!1,t),o?await zf(o):process.stdout.write(P.dim(`
171
171
  Skipped starter kit installation.
172
- `)),await qf(),Rt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(P.green(`
172
+ `)),await Xf(),Rt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(P.green(`
173
173
  \u2713 Setup complete. Tenant: ${w(r.tenant)}. JWT written to ${tn()}.
174
174
 
175
175
  `)),n&&process.stdout.write(P.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(P.red(` \u2717 Starter kit setup failed: ${s}
177
- `)),1}}async function nv(e,t){Hf(),Rt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
178
- `),process.stdout.write(Vf+`
177
+ `)),1}}async function rv(e,t){Kf(),Rt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
178
+ `),process.stdout.write(Hf+`
179
179
  `);let r=(await qt(P.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return Rt.error("[auth] Validation failed: JWT is required"),process.stderr.write(P.red(` \u2717 JWT is required
180
180
  `)),1;let n;try{n=Co(r);}catch(l){let u=w(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(P.red(` \u2717 ${u}
181
- `)),1}let o=e??await ev(),s=t??await tv();o&&Dt(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(P.red(` \u2717 Authentication failed: ${u}
182
- `)),1}let{initFailed:i}=await Jf(o,s),a=await zf();return await Wf({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await Xf(a):process.stdout.write(P.dim(`
181
+ `)),1}let o=e??await QI(),s=t??await ev();o&&Dt(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(P.red(` \u2717 Authentication failed: ${u}
182
+ `)),1}let{initFailed:i}=await Jf(o,s),a=await Gf();return await Vf({...n,starterKit:a?.slug,customUrl:o??void 0},!0,r),a?await zf(a):process.stdout.write(P.dim(`
183
183
  Skipped starter kit installation.
184
- `)),await qf(),Rt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(P.green(`
184
+ `)),await Xf(),Rt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(P.green(`
185
185
  \u2713 Setup complete. Tenant: ${w(n.tenant)}. JWT written to ${tn()}.
186
186
 
187
187
  `)),i&&process.stdout.write(P.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
188
188
  `)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=w(r instanceof Error?r.message:"unknown error");return Rt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(P.red(` \u2717 Unexpected error: ${n}
189
- `)),1}}async function kc(e={}){if(e.jwt)return rv({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!wn.test(e.customUrl))return process.stderr.write(P.red(` \u2717 ${Sn}.
190
- `)),1;if(e.customEmail!==void 0&&!xn.test(e.customEmail))return process.stderr.write(P.red(` \u2717 ${bn}.
191
- `)),1;try{return await nv(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
192
- `),130;throw t}}async function ov(){try{return process.stdout.write(`
189
+ `)),1}}async function Cc(e={}){if(e.jwt)return tv({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!wn.test(e.customUrl))return process.stderr.write(P.red(` \u2717 ${Sn}.
190
+ `)),1;if(e.customEmail!==void 0&&!bn.test(e.customEmail))return process.stderr.write(P.red(` \u2717 ${xn}.
191
+ `)),1;try{return await rv(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
192
+ `),130;throw t}}async function nv(){try{return process.stdout.write(`
193
193
  `),(await qt(P.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(P.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 Yf(e){if(!await ee())return process.stdout.write(P.yellow(` \u26A0 You are not authenticated
196
- `)),0;if(!e){let t=await ov();if(t!==null)return t}try{return await Ru(),process.stdout.write(P.green(` \u2713 Credentials removed successfully
195
+ `),130;throw e}}async function qf(e){if(!await ee())return process.stdout.write(P.yellow(` \u26A0 You are not authenticated
196
+ `)),0;if(!e){let t=await nv();if(t!==null)return t}try{return await Au(),process.stdout.write(P.green(` \u2713 Credentials removed successfully
197
197
  `)),0}catch{return process.stderr.write(P.red(` \u2717 Error removing credentials
198
- `)),1}}async function Zf(){let e=await ee();return e?await Ir()?(process.stdout.write(`
198
+ `)),1}}async function Yf(){let e=await ee();return e?await Ir()?(process.stdout.write(`
199
199
  `+P.bold(` Authenticated
200
200
  `)),process.stdout.write(P.dim(" Tenant: ")+w(e.tenant)+`
201
201
  `),process.stdout.write(P.dim(" Client ID: ")+w(e.clientId)+`
202
202
  `),process.stdout.write(P.dim(" Starter Kit: ")+w(e.starterKit??"not set")+`
203
- `),process.stdout.write(P.dim(" Config: ")+w(await $u())+`
203
+ `),process.stdout.write(P.dim(" Config: ")+w(await Ru())+`
204
204
  `),process.stdout.write(`
205
- `),0):(process.stdout.write(P.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(P.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();j();Oe();j();var iv=[me,"flow-harness"];function Qf(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function av(e,t,r=process.env){return Qf(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Qf(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 eg(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 ea(e=process.env){let t=Wr();if(!ie__default.existsSync(t))return [];try{let r=JSON.parse(ie__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>av(n,o,e))}catch{return []}}function tg(){let e=Wr(),t={fixed:[],skipped:[]};if(!ie__default.existsSync(e))return t;let r;try{r=JSON.parse(ie__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 iv){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`;ie__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,e);}return t}async function lv(e){let t=de(),r;try{r=await nr(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return T(E.CLI_CATALOG_VIEWED,{interface:te().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(wr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(yr(["","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 cv(e){let t=de(),r=await nr(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&&Ke(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return T(E.CLI_CATALOG_VIEWED,{interface:te().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(wr(o),0):o.length===0?(b("All plugins are up to date."),0):(yr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
205
+ `),0):(process.stdout.write(P.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(P.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}N();j();Oe();j();var sv=[pe,"flow-harness"];function Zf(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function iv(e,t,r=process.env){return Zf(r.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Zf(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 Qf(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 ea(e=process.env){let t=Jr();if(!ie__default.existsSync(t))return [];try{let r=JSON.parse(ie__default.readFileSync(t,"utf-8"));return Object.entries(r).map(([n,o])=>iv(n,o,e))}catch{return []}}function eg(){let e=Jr(),t={fixed:[],skipped:[]};if(!ie__default.existsSync(e))return t;let r;try{r=JSON.parse(ie__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 sv){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`;ie__default.writeFileSync(o,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384}),ie__default.renameSync(o,e);}return t}async function av(e){let t=ue(),r;try{r=await nr(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return T(E.CLI_CATALOG_VIEWED,{interface:te().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(wr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(yr(["","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 lv(e){let t=ue(),r=await nr(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&&Ke(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return T(E.CLI_CATALOG_VIEWED,{interface:te().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),e.json?(wr(o),0):o.length===0?(x("All plugins are up to date."),0):(yr(["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
- `),0)}async function uv(e){let t=de();if(T(E.CLI_CATALOG_VIEWED,{interface:te().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return b("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return wr(t),0;let r;try{r=await nr(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(ea().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=ts.indexOf(i.scope??"user"),u=ts.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return yr(["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??nc(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",hr[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,_t(i.installedAt??"")]})),process.stdout.write(`
207
+ `),0)}async function cv(e){let t=ue();if(T(E.CLI_CATALOG_VIEWED,{interface:te().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 wr(t),0;let r;try{r=await nr(e.source);}catch{r=[];}let n=new Map(r.map(i=>[i.name,i])),o=new Map(ea().map(i=>[i.name,i.enabled])),s=[...t].sort((i,a)=>{let l=ts.indexOf(i.scope??"user"),u=ts.indexOf(a.scope??"user");return (l===-1?1/0:l)-(u===-1?1/0:u)});return yr(["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??rc(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",hr[l]?.label??"Plugin",u,i.scope??"user",i.status??"enabled",d,_t(i.installedAt??"")]})),process.stdout.write(`
208
208
  ${t.length} plugin(s) installed.
209
- `),0}async function rg(e){if(!await Z())return 1;try{return e.available?await lv(e):e.outdated?await cv(e):await uv(e)}catch(t){return v(t instanceof Error?t.message:"Failed to list plugins."),1}}Mr();N();j();function ta(e){let t=Ce().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function Yt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function ra(e,t,r){return b(`${e} is already installed ${Yt(r)}.`),z(` Move it to ${Lt[t].actionLabel} instead? This uninstalls it from ${Yt(r)} first. [y/N] `)}N();j();R();var we=x("manage");function oa(e,t){return t?de().find(r=>r.name===e&&r.scope===t):de().find(r=>r.name===e)}function dv(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,b(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=na({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function pv(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=w(e),a=w(jn(e,r.scope));if(!await z(`${t}Install external plugin "${i}"?
209
+ `),0}async function tg(e){if(!await Z())return 1;try{return e.available?await av(e):e.outdated?await lv(e):await cv(e)}catch(t){return v(t instanceof Error?t.message:"Failed to list plugins."),1}}Mr();N();j();function ta(e){let t=Ce().plugins,r=process.cwd();for(let[n,o]of Object.entries(t))if(n===e||n.startsWith(`${e}@`)){let s=o.find(i=>i.scope==="user"||i.projectPath===r);if(s)return s}}function Yt(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function ra(e,t,r){return x(`${e} is already installed ${Yt(r)}.`),z(` Move it to ${Lt[t].actionLabel} instead? This uninstalls it from ${Yt(r)} first. [y/N] `)}N();j();R();var we=b("manage");function oa(e,t){return t?ue().find(r=>r.name===e&&r.scope===t):ue().find(r=>r.name===e)}function uv(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=na({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function dv(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=w(e),a=w(jn(e,r.scope));if(!await z(`${t}Install external plugin "${i}"?
210
210
  This will run: ${a}
211
- [y/N] `))return we.debug(`[${e}] Installation cancelled by user`),r.silent||b(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=na({text:`${t}Installing ${e}...`}).start());}let s=o?dv(t,o):void 0;try{let i=await Im(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ue({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?ge({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):Y(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=Q(i);return r.silent?Ue({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function mv(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=ta(e);if(!o)return {proceed:true,spinner:n};n?.stop();let s=r.scope??"user";if(o.scope===s){let c=`${e} is already installed ${Yt(o)}. Use --force to reinstall.`;return r.silent?ge({status:"already_installed",plugin:e,message:c}):b(`${t}${c}`),{proceed:false}}let i=r.isInteractive??!!process.stdin.isTTY;if(r.silent||!i){let c=`Already installed ${Yt(o)}. Re-run with --force to install here too.`;return r.silent?ge({status:"already_installed",plugin:e,message:c}):b(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await ra(e,s,o)?await is(e,{force:true,scope:o.scope})!==0?(b(`${t}Could not remove ${e} from ${Yt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:na({text:`${t}Installing ${e}...`}).start()}:(b(`${t}Skipped ${e}.`),{proceed:false})}async function fv(e,t,r){let n=r.silent?void 0:na({text:`${t}Installing ${e}...`}).start();if(Bn(e))return pv(e,t,r,n);let o=await mv(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await Fe(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=si(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?ge({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):Y(`${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 Xe)return r.silent?ge({status:"already_installed",plugin:e,message:s.message}):b(`${t}${s.message}`),{name:e,success:true};let i=Q(s);return r.silent?Ue({status:"error",plugin:e,message:i}):v(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function gv(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;b(`
212
- Installation summary: ${t} succeeded, ${r} failed`);}async function hv(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 nr();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 ao(e,t={}){if(!await Z())return 1;let r=[],n=await hv(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 fv(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?ge({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}:{}}))}):gv(r)),r.some(o=>!o.success)?1:0}async function is(e,t){if(!await Z())return 1;if(we.debug(`[${e}] Looking up installed plugin`),!t.force){let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`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 we.debug(`[${e}] Uninstall cancelled by user`),b("Operation cancelled."),0}try{return we.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await No(e,t.scope),we.info(`[${e}] Uninstalled successfully`),Y("Plugin removed successfully"),0}catch(r){return we.error(`[${e}] Failed to uninstall: ${Q(r)}`),v(Q(r)),1}}async function ng(e,t={}){if(!await Z())return 1;we.debug(`[${e}] Looking up installed plugin`);let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return we.debug(`[${e}] Already enabled, skipping`),b(`${r.name} is already enabled`),0;try{return we.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Bo(e,"enabled",t.scope),we.info(`[${e}] Enabled successfully`),Y(`${r.name} enabled successfully`),0}catch(n){return we.error(`[${e}] Failed to enable: ${Q(n)}`),v(Q(n)),1}}async function og(e,t={}){if(!await Z())return 1;we.debug(`[${e}] Looking up installed plugin`);let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return we.debug(`[${e}] Already disabled, skipping`),b(`${r.name} is already disabled`),0;try{return we.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Bo(e,"disabled",t.scope),we.info(`[${e}] Disabled successfully`),Y(`${r.name} disabled successfully`),0}catch(n){return we.error(`[${e}] Failed to disable: ${Q(n)}`),v(Q(n)),1}}async function sg(e,t,r){r.silent||b(`${t}Updating ${e}...`);try{let n=await _i(e,r);return r.silent?ge({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):Y(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof $r)return r.silent?ge({status:"up_to_date",plugin:e,message:n.message}):b(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=Q(n);return r.silent?Ue({status:"error",plugin:e,message:o}):v(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function yv(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;b(`
213
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function wv(e,t,r){try{let n=await Vn(e,r.source);Ke(t,n.version,r.force)?b(`Would update ${e}: v${t} \u2192 v${n.version}`):b(`${e} is already up to date (v${t})`);}catch(n){return v(Q(n)),1}return 0}function Sv(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function xv(e,t,r){let n=t.get(e.name);return n?e.version&&Ke(e.version,n,r)?(b(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(b(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(b(`Skipping ${e.name}: not found in catalog`),false)}async function bv(e,t){try{let r=await nr(t.source),n=Sv(r),o=0;for(let s of e)xv(s,n,t.force)&&o++;o===0&&b("All plugins are up to date");}catch(r){return v(Q(r)),1}return 0}async function Iv(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await sg(e[n].name,o,t);r.push(s);}return t.silent?ge({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}:{}}))}):yv(r),r.some(n=>!n.success)?1:0}async function ig(e,t={}){if(!await Z())return 1;if(e){let o=oa(e,t.scope);return o?t.dryRun?wv(e,o.version??"",t):(await sg(e,"",t)).success?0:1:(t.silent?Ue({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):v(`Plugin "${e}" is not installed`),1)}let n=de().filter(o=>o.marketplace===me);return n.length===0?(t.silent?ge({status:"empty",message:"No plugins installed"}):b("No plugins installed"),0):t.dryRun?bv(n,t):Iv(n,t)}N();R();var as=x("cli:bundle");function vv(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 Ev(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
211
+ [y/N] `))return we.debug(`[${e}] Installation cancelled by user`),r.silent||x(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=na({text:`${t}Installing ${e}...`}).start());}let s=o?uv(t,o):void 0;try{let i=await xm(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ue({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?fe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):Y(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=Q(i);return r.silent?Ue({status:"error",plugin:e,message:a}):v(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function pv(e,t,r,n){if(r.force)return {proceed:true,spinner:n};let o=ta(e);if(!o)return {proceed:true,spinner:n};n?.stop();let s=r.scope??"user";if(o.scope===s){let c=`${e} is already installed ${Yt(o)}. Use --force to reinstall.`;return r.silent?fe({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 ${Yt(o)}. Re-run with --force to install here too.`;return r.silent?fe({status:"already_installed",plugin:e,message:c}):x(`${t}Skipping ${e} \u2014 ${c}`),{proceed:false}}return await ra(e,s,o)?await is(e,{force:true,scope:o.scope})!==0?(x(`${t}Could not remove ${e} from ${Yt(o)} \u2014 skipping rather than leaving it in an inconsistent state.`),{proceed:false}):{proceed:true,spinner:r.silent?void 0:na({text:`${t}Installing ${e}...`}).start()}:(x(`${t}Skipped ${e}.`),{proceed:false})}async function mv(e,t,r){let n=r.silent?void 0:na({text:`${t}Installing ${e}...`}).start();if(Bn(e))return dv(e,t,r,n);let o=await pv(e,t,r,n);if(!o.proceed)return {name:e,success:true};n=o.spinner;try{let s=await Fe(e,{...r,onDownloadProgress:r.silent?void 0:(i,a)=>{if(!n||a===0)return;let{bar:l,percent:u,label:c}=si(i,a);n.text=`${t}Downloading ${e}... ${l} ${u}% (${c})`;}});return n?.stop(),r.silent?fe({status:"success",plugin:e,version:s.version,duration_ms:s.duration_ms}):Y(`${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 Xe)return r.silent?fe({status:"already_installed",plugin:e,message:s.message}):x(`${t}${s.message}`),{name:e,success:true};let i=Q(s);return r.silent?Ue({status:"error",plugin:e,message:i}):v(`${t}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function fv(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 gv(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 nr();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 ao(e,t={}){if(!await Z())return 1;let r=[],n=await gv(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 mv(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?fe({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}:{}}))}):fv(r)),r.some(o=>!o.success)?1:0}async function is(e,t){if(!await Z())return 1;if(we.debug(`[${e}] Looking up installed plugin`),!t.force){let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`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 we.debug(`[${e}] Uninstall cancelled by user`),x("Operation cancelled."),0}try{return we.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await No(e,t.scope),we.info(`[${e}] Uninstalled successfully`),Y("Plugin removed successfully"),0}catch(r){return we.error(`[${e}] Failed to uninstall: ${Q(r)}`),v(Q(r)),1}}async function rg(e,t={}){if(!await Z())return 1;we.debug(`[${e}] Looking up installed plugin`);let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return we.debug(`[${e}] Already enabled, skipping`),x(`${r.name} is already enabled`),0;try{return we.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Bo(e,"enabled",t.scope),we.info(`[${e}] Enabled successfully`),Y(`${r.name} enabled successfully`),0}catch(n){return we.error(`[${e}] Failed to enable: ${Q(n)}`),v(Q(n)),1}}async function ng(e,t={}){if(!await Z())return 1;we.debug(`[${e}] Looking up installed plugin`);let r=oa(e,t.scope);if(!r)return we.error(`[${e}] Plugin is not installed`),v(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return we.debug(`[${e}] Already disabled, skipping`),x(`${r.name} is already disabled`),0;try{return we.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Bo(e,"disabled",t.scope),we.info(`[${e}] Disabled successfully`),Y(`${r.name} disabled successfully`),0}catch(n){return we.error(`[${e}] Failed to disable: ${Q(n)}`),v(Q(n)),1}}async function og(e,t,r){r.silent||x(`${t}Updating ${e}...`);try{let n=await _i(e,r);return r.silent?fe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):Y(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof $r)return r.silent?fe({status:"up_to_date",plugin:e,message:n.message}):x(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=Q(n);return r.silent?Ue({status:"error",plugin:e,message:o}):v(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function hv(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 yv(e,t,r){try{let n=await Vn(e,r.source);Ke(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 v(Q(n)),1}return 0}function wv(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Sv(e,t,r){let n=t.get(e.name);return n?e.version&&Ke(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 bv(e,t){try{let r=await nr(t.source),n=wv(r),o=0;for(let s of e)Sv(s,n,t.force)&&o++;o===0&&x("All plugins are up to date");}catch(r){return v(Q(r)),1}return 0}async function xv(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await og(e[n].name,o,t);r.push(s);}return t.silent?fe({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}:{}}))}):hv(r),r.some(n=>!n.success)?1:0}async function sg(e,t={}){if(!await Z())return 1;if(e){let o=oa(e,t.scope);return o?t.dryRun?yv(e,o.version??"",t):(await og(e,"",t)).success?0:1:(t.silent?Ue({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):v(`Plugin "${e}" is not installed`),1)}let n=ue().filter(o=>o.marketplace===pe);return n.length===0?(t.silent?fe({status:"empty",message:"No plugins installed"}):x("No plugins installed"),0):t.dryRun?bv(n,t):xv(n,t)}N();R();var as=b("cli:bundle");function Iv(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 vv(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
- `);for(let o of t)process.stdout.write(`${vv(o)}
215
+ `);for(let o of t)process.stdout.write(`${Iv(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 ag(e){if(!e.trim())return v("Bundle name cannot be empty."),1;if(!await Z())return 1;as.debug(`Fetching bundle "${e}"`);let r;try{r=await Ni(e);}catch(a){return a instanceof to||a instanceof es?(v(a.message),1):(v(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(as.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),Ev(r.title,n),o.length===0)return v("No artifacts available for installation in this bundle."),1;if(!await z(`Install ${o.length} artifact(s)? [Y/n] `))return as.debug("Installation cancelled by user"),0;as.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Ri(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 ig(e){if(!e.trim())return v("Bundle name cannot be empty."),1;if(!await Z())return 1;as.debug(`Fetching bundle "${e}"`);let r;try{r=await Ni(e);}catch(a){return a instanceof to||a instanceof es?(v(a.message),1):(v(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(as.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),vv(r.title,n),o.length===0)return v("No artifacts available for installation in this bundle."),1;if(!await z(`Install ${o.length} artifact(s)? [Y/n] `))return as.debug("Installation cancelled by user"),0;as.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Ri(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(as.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&Y(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");v(`${i.failed} failed: ${w(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>w(l.name??l.flowId)).join(", ");b(`${i.skipped} unavailable: ${a}`);}return 0}Mr();N();R();var lg=x("marketplace");function Pv(e){return `claude plugin marketplace add ${e}`}async function cg(e,t){if(!await Z())return 1;let r;try{r=mi(e);}catch(s){let i=Q(s);return t.silent?Ue({status:"error",source:e,message:i}):v(i),1}lg.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Pv(r);if(!t.force){let s=w(r),i=w(n);if(!await z(`Add marketplace "${s}"?
222
+ `);}});if(as.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&Y(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");v(`${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}Mr();N();R();var ag=b("marketplace");function Tv(e){return `claude plugin marketplace add ${e}`}async function lg(e,t){if(!await Z())return 1;let r;try{r=mi(e);}catch(s){let i=Q(s);return t.silent?Ue({status:"error",source:e,message:i}):v(i),1}ag.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Tv(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 lg.debug("[marketplace] Operation cancelled by user"),b("Operation cancelled."),0}let o=t.silent?void 0:na({text:`Adding marketplace "${w(r)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(t.silent?Ue({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(v(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&b(`stdout: ${s.stdout}`)),1):(t.silent?ge({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(Y(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&b(s.stdout)),0)}catch(s){o?.stop();let i=Q(s);return t.silent?Ue({status:"error",source:r,message:i}):v(`Failed to add marketplace "${r}": ${i}`),1}}Pe();N();async function Rv(){return await ee()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function $v(){let e=Date.now();try{await nr();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 Mv(){return await Ir()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Lv(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function _v(){let e=ea();if(e.length!==0){process.stdout.write(`
224
+ [y/N] `))return ag.debug("[marketplace] Operation cancelled by user"),x("Operation cancelled."),0}let o=t.silent?void 0:na({text:`Adding marketplace "${w(r)}"...`}).start();try{let s=await Le(n);return o?.stop(),s.exitCode!==0?(t.silent?Ue({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(v(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&x(`stdout: ${s.stdout}`)),1):(t.silent?fe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(Y(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&x(s.stdout)),0)}catch(s){o?.stop();let i=Q(s);return t.silent?Ue({status:"error",source:r,message:i}):v(`Failed to add marketplace "${r}": ${i}`),1}}Pe();N();async function Av(){return await ee()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Rv(){let e=Date.now();try{await nr();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 $v(){return await Ir()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Mv(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function Lv(){let e=ea();if(e.length!==0){process.stdout.write(`
225
225
  `+P.bold(` Marketplace Auto-Update
226
226
 
227
- `));for(let t of e){let r=t.enabled?P.green("[ON] "):P.dim("[OFF]"),n=w(t.name).padEnd(20),o=w(eg(t));process.stdout.write(` ${r} ${n} ${P.dim(o)}
228
- `);}}}function Dv(){process.stdout.write(`
227
+ `));for(let t of e){let r=t.enabled?P.green("[ON] "):P.dim("[OFF]"),n=w(t.name).padEnd(20),o=w(Qf(t));process.stdout.write(` ${r} ${n} ${P.dim(o)}
228
+ `);}}}function _v(){process.stdout.write(`
229
229
  `+P.bold(` FlowSetup CLI \u2014 Auto-Update Fix
230
230
 
231
- `));let e=tg();for(let t of e.fixed)process.stdout.write(` ${P.green("[FIXED]")} ${w(t)} \u2014 autoUpdate: true set
231
+ `));let e=eg();for(let t of e.fixed)process.stdout.write(` ${P.green("[FIXED]")} ${w(t)} \u2014 autoUpdate: true set
232
232
  `);for(let{name:t,reason:r}of e.skipped)process.stdout.write(` ${P.dim("[SKIP] ")} ${w(t)} \u2014 ${w(r)}
233
233
  `);return process.stdout.write(`
234
234
  `),e.fixed.length===0?process.stdout.write(P.dim(` Nothing to fix \u2014 all set.
235
235
 
236
236
  `)):process.stdout.write(P.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
237
237
 
238
- `)),0}async function ug(e={}){if(e.fix)return Dv();process.stdout.write(`
238
+ `)),0}async function cg(e={}){if(e.fix)return _v();process.stdout.write(`
239
239
  `+P.bold(` FlowSetup CLI Diagnostics
240
240
 
241
- `));let t=[{name:"Credentials",fn:Rv},{name:"Prompt Manager",fn:$v},{name:"Valid Token",fn:Mv},{name:"Claude Code",fn:Lv}],r=true;for(let n of t){let o=await n.fn(),s,i=P.green;o.passed?s=P.green("[OK] "):(s=P.red("[FAIL]"),i=P.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${w(o.message)}`;process.stdout.write(a+`
242
- `);}return _v(),process.stdout.write(`
241
+ `));let t=[{name:"Credentials",fn:Av},{name:"Prompt Manager",fn:Rv},{name:"Valid Token",fn:$v},{name:"Claude Code",fn:Mv}],r=true;for(let n of t){let o=await n.fn(),s,i=P.green;o.passed?s=P.green("[OK] "):(s=P.red("[FAIL]"),i=P.red,r=false);let a=` ${s} ${i(n.name.padEnd(18))} ${w(o.message)}`;process.stdout.write(a+`
242
+ `);}return Lv(),process.stdout.write(`
243
243
  `),r?(process.stdout.write(P.green(` \u2713 All checks passed!
244
244
 
245
245
  `)),0):(process.stdout.write(P.red(` \u2717 Some checks failed \u2014 verify your configuration
246
246
 
247
- `)),1)}Pe();Xr();j();async function dg(e){let t=await ee(),r=Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Zt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await op.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}An();Us();Pe();N();R();var Uv=x("commands:usage"),sa=20,pg="EMAIL",mg="MONTHLY CONSUMPTION (USD)",fg="STATUS";function Nv(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*sa),n=sa-r,o=P.green;return t>=90?o=P.red:t>=70&&(o=P.yellow),o("\u2588".repeat(r))+P.dim("\u2591".repeat(n))}function gg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Bv(e){let t=e.toLowerCase(),r=w(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?P.green(`\u2299 ${n}`):t==="warning"?P.yellow(`\u26A0 ${n}`):t==="blocked"?P.red("\u2717 Budget limit reached"):P.red(`\u2717 ${n}`)}function Fv(e){let t=_t(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 jv(e){try{let t=await Cn();if(t?.email)return w(t.email);let r=kn(e);return w(r.email??"")}catch(t){return Uv.debug(`JWT email decode failed: ${String(t)}`),""}}async function hg(e){if(!await Z())return 1;let r;try{r=await Ut();}catch(h){return v(`Authentication error: ${Q(h)}`),1}let n;try{n=await dg(r);}catch(h){return v(`Failed to fetch usage data: ${Q(h)}`),1}if(e.json)return wr(n),0;let o=await jv(r)||w(n.user_id),s=gg(n.consumed_usd),i=gg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(pg.length,o.length+2),c=Math.max(mg.length,sa+2+l.length),d=` ${pg.padEnd(u)} ${mg.padEnd(c)} ${fg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(fg.length)}`,p=`${P.cyan("\u2022")} ${o.padEnd(u-2)}`,g=`${Nv(n.percentage)} ${l.padEnd(c-sa-2)}`,f=` ${P.dim("Resets")} ${Fv(n.renewal_date)}`;return process.stdout.write(`
247
+ `)),1)}Pe();Xr();j();async function ug(e){let t=await ee(),r=Ot("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Zt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await np.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}An();Us();Pe();N();R();var Ov=b("commands:usage"),sa=20,dg="EMAIL",pg="MONTHLY CONSUMPTION (USD)",mg="STATUS";function Uv(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*sa),n=sa-r,o=P.green;return t>=90?o=P.red:t>=70&&(o=P.yellow),o("\u2588".repeat(r))+P.dim("\u2591".repeat(n))}function fg(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Nv(e){let t=e.toLowerCase(),r=w(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?P.green(`\u2299 ${n}`):t==="warning"?P.yellow(`\u26A0 ${n}`):t==="blocked"?P.red("\u2717 Budget limit reached"):P.red(`\u2717 ${n}`)}function Bv(e){let t=_t(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 Fv(e){try{let t=await Cn();if(t?.email)return w(t.email);let r=kn(e);return w(r.email??"")}catch(t){return Ov.debug(`JWT email decode failed: ${String(t)}`),""}}async function gg(e){if(!await Z())return 1;let r;try{r=await Ut();}catch(h){return v(`Authentication error: ${Q(h)}`),1}let n;try{n=await ug(r);}catch(h){return v(`Failed to fetch usage data: ${Q(h)}`),1}if(e.json)return wr(n),0;let o=await Fv(r)||w(n.user_id),s=fg(n.consumed_usd),i=fg(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(dg.length,o.length+2),c=Math.max(pg.length,sa+2+l.length),d=` ${dg.padEnd(u)} ${pg.padEnd(c)} ${mg}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(mg.length)}`,p=`${P.cyan("\u2022")} ${o.padEnd(u-2)}`,g=`${Uv(n.percentage)} ${l.padEnd(c-sa-2)}`,f=` ${P.dim("Resets")} ${Bv(n.renewal_date)}`;return process.stdout.write(`
248
248
  `),process.stdout.write(P.dim(d)+`
249
249
  `),process.stdout.write(P.dim(m)+`
250
- `),process.stdout.write(` ${p} ${g} ${Bv(n.status)}
250
+ `),process.stdout.write(` ${p} ${g} ${Nv(n.status)}
251
251
  `),process.stdout.write(f+`
252
252
  `),process.stdout.write(`
253
- `),0}var Vv=["github.com","www.github.com"],Wv=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Jv=/^([^@]+)@(.+)$/;function Gv(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Ac(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 zv(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=Ac(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Ac(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ia(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Gv(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:")&&Vv.includes(r.hostname))return zv(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(Wv);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(Jv);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=Ac(m));}return d}}return {type:"git",url:t}}function aa(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 yg(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 $c=new Set(["node_modules",".git","dist","build","__pycache__"]);function xg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Qv(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Rc(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ls(e){try{let t=await readFile(e,"utf-8"),{data:r}=yg(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 bg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Rc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!$c.has(a.name)).map(a=>bg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function ua(e,t){let r=[],n=new Set;if(t&&!Qv(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Rc(o)){let i=await ls(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 Rc(u)){let c=await ls(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await bg(o);for(let a of i){let l=await ls(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Ig(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}Oe();var Pg=1,sE={retries:5,minTimeout:50};async function Cg(e,t){mkdirSync(dirname(e),{recursive:true});let r=await lw.lock(e+".lock",{realpath:false,retries:sE});try{return await t()}finally{await r();}}function vg(){return {version:Pg,skills:{}}}async function da(e){let t=fo(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Pg?vg():n}catch{return vg()}}function iE(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function kg(e,t){let r=fo(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:iE(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
254
- `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function Ag(e,t,r){let n=fo(r);await Cg(n,async()=>{let o=await da(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await kg(o,r);});}async function Rg(e,t){let r=fo(t);await Cg(r,async()=>{let n=await da(t);e in n.skills&&(delete n.skills[e],await kg(n,t));});}Oe();R();var $g=x("skillInstaller");async function fE(e,t,r,n){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:te().interfaceType});}catch(o){$g.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function gE(e,t){try{await T(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:te().interfaceType});}catch(r){$g.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function hE(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if($c.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function yE(e,t,r){let n=lt(e.name),o=Jr(t),s=join(o,n);if(!xg(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 hE(e.path,s);let a=aa(r)??r.url;return await Ag(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 Mg(e,t){let r=ia(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 ua(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Ig(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await yE(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await fE(c.name,t.scope,u,p):await gE(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 Tt(n).catch(()=>{});}}Oe();N();R();var IE=x("skills");async function vE(e){try{await T(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:te().interfaceType});}catch(t){IE.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function EE(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 TE(e){let t=ia(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return v("Invalid local path."),1;n=t.localPath;}else b(`Fetching skills from ${w(e)}...`),r=await Et(t.url,t.ref),n=r;let o=await ua(n,t.subpath);if(o.length===0)return b("No skills found in this source."),0;let i=aa(t)??w(e);b(`Found ${o.length} skill(s) in ${i}:
253
+ `),0}var Hv=["github.com","www.github.com"],Vv=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Jv=/^([^@]+)@(.+)$/;function Wv(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function kc(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 Gv(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=kc(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=kc(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ia(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Wv(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:")&&Hv.includes(r.hostname))return Gv(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(Vv);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(Jv);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=kc(m));}return d}}return {type:"git",url:t}}function aa(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}function hg(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var Rc=new Set(["node_modules",".git","dist","build","__pycache__"]);function Sg(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Zv(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Ac(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function ls(e){try{let t=await readFile(e,"utf-8"),{data:r}=hg(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function bg(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Ac(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Rc.has(a.name)).map(a=>bg(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function ua(e,t){let r=[],n=new Set;if(t&&!Zv(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Ac(o)){let i=await ls(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 Ac(u)){let c=await ls(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await bg(o);for(let a of i){let l=await ls(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function xg(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}Oe();var Tg=1,oE={retries:5,minTimeout:50};async function Pg(e,t){mkdirSync(dirname(e),{recursive:true});let r=await aw.lock(e+".lock",{realpath:false,retries:oE});try{return await t()}finally{await r();}}function Ig(){return {version:Tg,skills:{}}}async function da(e){let t=fo(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Tg?Ig():n}catch{return Ig()}}function sE(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Cg(e,t){let r=fo(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:sE(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
254
+ `,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function kg(e,t,r){let n=fo(r);await Pg(n,async()=>{let o=await da(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Cg(o,r);});}async function Ag(e,t){let r=fo(t);await Pg(r,async()=>{let n=await da(t);e in n.skills&&(delete n.skills[e],await Cg(n,t));});}Oe();R();var Rg=b("skillInstaller");async function mE(e,t,r,n){try{await T(E.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:te().interfaceType});}catch(o){Rg.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function fE(e,t){try{await T(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:te().interfaceType});}catch(r){Rg.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function gE(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(Rc.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function hE(e,t,r){let n=lt(e.name),o=Wr(t),s=join(o,n);if(!Sg(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 gE(e.path,s);let a=aa(r)??r.url;return await kg(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 $g(e,t){let r=ia(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 ua(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?xg(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await hE(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await mE(c.name,t.scope,u,p):await fE(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 Tt(n).catch(()=>{});}}Oe();N();R();var xE=b("skills");async function IE(e){try{await T(E.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:te().interfaceType});}catch(t){xE.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function vE(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 EE(e){let t=ia(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return v("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 ua(n,t.subpath);if(o.length===0)return x("No skills found in this source."),0;let i=aa(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(` ${P.bold(l)} ${P.dim(u)}
256
256
  `);}return process.stdout.write(`
257
- `),0}catch(n){return n instanceof Or?v(n.message):v(n instanceof Error?n.message:String(n)),1}finally{r&&await Tt(r).catch(()=>{});}}function PE(e){for(let r of e.results){let n=w(r.skill);if(r.success){let o=relative(process.cwd(),r.path);Y(`${n} installed ${P.dim(`\u2192 ${o}/`)}`);}else v(`${n}: ${w(r.error??"unknown error")}`);}process.stdout.write(`
258
- `);let t=e.source;e.installed>0&&b(`Installed ${e.installed} of ${e.discovered} skill(s) from ${w(t)}`),e.failed>0&&v(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?b("No skills found in this source."):e.results.length===0&&e.discovered>0&&b(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function _g(e,t){if(t.list)return TE(e);let r=t.global?"global":"project";try{let n=await Mg(e,{scope:r,skillFilter:t.skill,yes:t.yes});return PE(n),n.failed>0?1:0}catch(n){return n instanceof Or?v(n.message):v(n instanceof Error?n.message:String(n)),1}}async function Dg(e){let t=Jr(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 ls(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 Og(e){let t=e.global?"global":"project",r=await Dg(t),n=await da(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 wr(s),0}if(r.length===0)return b(`No skills installed (${t==="global"?"global":"project"} scope).`),0;b(`${t==="global"?"Global":"Project"} skills (${r.length}):
257
+ `),0}catch(n){return n instanceof Or?v(n.message):v(n instanceof Error?n.message:String(n)),1}finally{r&&await Tt(r).catch(()=>{});}}function TE(e){for(let r of e.results){let n=w(r.skill);if(r.success){let o=relative(process.cwd(),r.path);Y(`${n} installed ${P.dim(`\u2192 ${o}/`)}`);}else v(`${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&&v(`${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 Lg(e,t){if(t.list)return EE(e);let r=t.global?"global":"project";try{let n=await $g(e,{scope:r,skillFilter:t.skill,yes:t.yes});return TE(n),n.failed>0?1:0}catch(n){return n instanceof Or?v(n.message):v(n instanceof Error?n.message:String(n)),1}}async function _g(e){let t=Wr(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 ls(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 Dg(e){let t=e.global?"global":"project",r=await _g(t),n=await da(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 wr(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?P.dim(` (${i})`):"";process.stdout.write(` ${P.bold(a)}${c}
260
260
  `),process.stdout.write(` ${P.dim(u)}
261
261
 
262
- `);}return 0}async function Ug(e,t){let r=t.global?"global":"project";if(!e){let i=await Dg(r);if(i.length===0)return b("No skills installed."),0;b("Installed skills:");for(let a of i)process.stdout.write(` - ${w(a.name)}
262
+ `);}return 0}async function Og(e,t){let r=t.global?"global":"project";if(!e){let i=await _g(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
- `),b("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=Jr(r),s=join(o,n);try{await stat(s);}catch{return v(`Skill "${w(e)}" is not installed.`),1}if(!t.force&&!await EE(`Remove skill "${w(n)}"?`))return b("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Rg(n,r),await vE(n),Y(`Skill "${w(n)}" removed.`),0}catch(i){return v(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();j();var pa=x("transfer"),Lc=1;function CE(e){return e.marketplace&&e.marketplace!==me?`${e.name}@${e.marketplace}`:e.name}function kE(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&b(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),b(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Fg(e){let t=le__default.resolve(e.output);try{let r=de(),n={version:Lc,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return ie__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),Y(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=Q(r);return pa.error(`Export failed: ${n}`),v(`Failed to export plugins: ${n}`),1}}async function jg(e,t={}){if(!await Z())return 1;let r;try{let a=ie__default.readFileSync(le__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return v(`Failed to read import file "${e}": ${Q(a)}`),1}if(r.version!==Lc)return v(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Lc}`),1;if(!Array.isArray(r.plugins))return v('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return b("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}]`;pa.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(pa.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&b(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(de().map(l=>l.name));kE(n,a);}if(t.dryRun)return b("Dry-run mode: no plugins were installed"),0;if(n.length===0){b(`
265
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}b(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=CE(a);pa.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await ao([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}b(`
266
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function _(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var RE=x("moduleProxy");function $E(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Hl.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 Kg(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await T(E.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{RE.warn(`Failed to emit proxy executed event: ${String(s)}`);}),_(o);}async function Vg(e,t){let r=ce.find(o=>o.alias===e);if(!r){v(`Unknown module alias: '${e}'`),_(1);return}if(!await Bt(r.binaryName)){v(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),_(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await jt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){v(`No supported installation method available for '${e}' on this platform.`),_(1);return}if(await $E("Would you like to install it now? [Y/n] ")){await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Ar(r,"inline",s);if(!a.success){v(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),_(1);return}await Kg(r,t);}else b(`To install manually, run: flow modules install ${e}`),await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),_(1);return}await Kg(r,t);}N();var DE=promisify(execFile);async function OE(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await DE(er(),["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/${ue}`,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 UE(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ke(t,r)?"outdated":"installed"}async function _c(){let e=await Promise.all(ce.map(async t=>{let[r,n]=await Promise.all([Bt(t.binaryName),OE(t)]),s=nt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=UE(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return yr(["Name","Alias","Version","Status","Platform"],e),0}async function Gg(e){let t=ce.find(i=>i.alias===e);if(!t)return v(`Unknown module alias: '${e}'`),1;let[r]=await no([t]);if(r.alreadyInstalled){let i=nt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return b(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?v(`Module ${t.name} is not supported on ${process.platform}.${a}`):v(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=na({text:`Installing ${t.name}...`}).start(),s;try{s=await Ar(t,"on_demand",n);}finally{o.stop();}return s.success?(Y(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(v(s.error?.message??"Installation failed"),1)}async function Wg(e,t){let r=na({text:`Updating ${e.name}...`}).start(),n;try{n=await Ys(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 zg(e){if(e!==null){let n=ce.find(i=>i.alias===e);if(!n)return v(`Unknown module alias: '${e}'`),1;let o=nt(n.alias);return o?.installMethod?await Wg(n,o.installedVersion??"unknown")==="error"?1:0:(v(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=nn().filter(n=>n.installMethod!==null);if(t.length===0)return b("No installed modules to update."),0;let r=0;for(let n of t){let o=ce.find(i=>i.alias===n.alias);if(!o)continue;await Wg(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var cs=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
264
+ `),x("Specify a skill name to remove: flow skills remove <name>"),1}let n=lt(e),o=Wr(r),s=join(o,n);try{await stat(s);}catch{return v(`Skill "${w(e)}" is not installed.`),1}if(!t.force&&!await vE(`Remove skill "${w(n)}"?`))return x("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Ag(n,r),await IE(n),Y(`Skill "${w(n)}" removed.`),0}catch(i){return v(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}N();R();j();var pa=b("transfer"),Mc=1;function PE(e){return e.marketplace&&e.marketplace!==pe?`${e.name}@${e.marketplace}`:e.name}function CE(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 Bg(e){let t=le__default.resolve(e.output);try{let r=ue(),n={version:Mc,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return ie__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),Y(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=Q(r);return pa.error(`Export failed: ${n}`),v(`Failed to export plugins: ${n}`),1}}async function Fg(e,t={}){if(!await Z())return 1;let r;try{let a=ie__default.readFileSync(le__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return v(`Failed to read import file "${e}": ${Q(a)}`),1}if(r.version!==Mc)return v(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Mc}`),1;if(!Array.isArray(r.plugins))return v('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}]`;pa.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(pa.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(ue().map(l=>l.name));CE(n,a);}if(t.dryRun)return x("Dry-run mode: no plugins were installed"),0;if(n.length===0){x(`
265
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)v(` ${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=PE(a);pa.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await ao([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)v(` ${a.name}: ${a.error}`);return o.length>0?1:0}R();N();function O(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}N();R();var AE=b("moduleProxy");function RE(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Kl.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 jg(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await T(E.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{AE.warn(`Failed to emit proxy executed event: ${String(s)}`);}),O(o);}async function Hg(e,t){let r=ce.find(o=>o.alias===e);if(!r){v(`Unknown module alias: '${e}'`),O(1);return}if(!await Bt(r.binaryName)){v(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),O(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await jt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){v(`No supported installation method available for '${e}' on this platform.`),O(1);return}if(await RE("Would you like to install it now? [Y/n] ")){await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Ar(r,"inline",s);if(!a.success){v(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),O(1);return}await jg(r,t);}else x(`To install manually, run: flow modules install ${e}`),await T(E.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),O(1);return}await jg(r,t);}N();var _E=promisify(execFile);async function DE(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await _E(er(),["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/${ge}`,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 OE(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ke(t,r)?"outdated":"installed"}async function Lc(){let e=await Promise.all(ce.map(async t=>{let[r,n]=await Promise.all([Bt(t.binaryName),DE(t)]),s=ot(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=OE(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return yr(["Name","Alias","Version","Status","Platform"],e),0}async function Wg(e){let t=ce.find(i=>i.alias===e);if(!t)return v(`Unknown module alias: '${e}'`),1;let[r]=await no([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"?v(`Module ${t.name} is not supported on ${process.platform}.${a}`):v(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=na({text:`Installing ${t.name}...`}).start(),s;try{s=await Ar(t,"on_demand",n);}finally{o.stop();}return s.success?(Y(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(v(s.error?.message??"Installation failed"),1)}async function Vg(e,t){let r=na({text:`Updating ${e.name}...`}).start(),n;try{n=await Ys(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 Gg(e){if(e!==null){let n=ce.find(i=>i.alias===e);if(!n)return v(`Unknown module alias: '${e}'`),1;let o=ot(n.alias);return o?.installMethod?await Vg(n,o.installedVersion??"unknown")==="error"?1:0:(v(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=nn().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=ce.find(i=>i.alias===n.alias);if(!o)continue;await Vg(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}var cs=[{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,30 +554,30 @@ 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 Bc="CLAUDE.md";function FE(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Fc(){return {new:0,unchanged:0,divergent:0,declined:0}}async function qg(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??Kc,i=e.confirmCreate??KE,a=[],l=Fc(),u=cs.find(m=>m.path===Bc),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"))):b(`declined: ${Bc} 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 cs){if(m.path===Bc&&!c)continue;let p=join(t,m.path),g=await jc({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:f=>s(f)});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 jc(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?FE(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(jE(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function jE(e){b(`${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 Kc(e){return z(` Overwrite ${e} with the updated template? [y/N] `)}async function KE(e){return z(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}function JE(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Yg(e,t=e,r=[]){for(let n of readdirSync(e).sort()){let o=join(e,n),s=statSync(o);s.isDirectory()?Yg(o,t,r):s.isFile()&&r.push(relative(t,o).split("\\").join("/"));}return r}function Zg(e,t){let r=readFileSync(t,"utf8");return {path:e,sha256:JE(r),content:r}}function ma(){return process.env.FLOW_HARNESS_PATH}function Qg(e){let t=join(e,"docs","catalog");return Yg(t).map(r=>Zg(`docs/catalog/${r}`,join(t,r)))}function fa(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=>Zg(`docs/playbooks/${a}`,join(s,a))));}return n}var ga=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 YE(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 ZE(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function QE(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function eT(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=ZE(s.path),a=QE(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 eh(e){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??Kc,i=ma();if(!i)throw new ga("FLOW_HARNESS_PATH is not set");let a,l;try{a=Qg(i),l=fa(i);}catch(h){throw new ga(`could not read docs from "${i}" (${h instanceof Error?h.message:String(h)})`)}let u=e.docsLang??"all",c=e.installedBundles.length===0,d=c?[]:YE(e.installedBundles,l),m=eT([...a,...d],u),p=[],g=Fc();for(let h of m){let y=join(t,h.path),I=await jc({dstPath:y,template:h,force:n,isInteractive:o,confirmOverwrite:M=>s(M)});p.push({path:h.path,status:I.status}),g[I.status]++,I.write&&!r&&(mkdirSync(dirname(y),{recursive:true}),writeFileSync(y,h.content,"utf8"));}let f=g.divergent>0||g.declined>0;return {files:p,counts:g,hasUnresolved:f,skippedPlaybooks:c}}function th(e){let t=Ce().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();Pe();Xr();R();var Wc=x("lib:otelMetrics"),rT="flow-plugins-cli",nT="1.0.0",oT=5e3;function sT(){return Ot("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function iT(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 aT(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:rT,version:nT},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>iT(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Jc(e,t={}){try{let[r,n]=await Promise.all([Cn(),ee()]),o=r?.email,s=n?.tenant;if(!o||!s){Wc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=aT(e,t);await op.post(sT(),{json:i,timeout:oT,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Wc.debug(`OTel metric sent: ${e}`);}catch(r){Wc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Gc=x("cli:init"),uT={new:{label:"new",color:P.green},unchanged:{label:"unchanged",color:P.dim},divergent:{label:"kept (differs from template)",color:P.yellow},declined:{label:"pending (declined)",color:P.yellow}};function dT(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 Nc="CLAUDE.md";function BE(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Bc(){return {new:0,unchanged:0,divergent:0,declined:0}}async function Xg(e={}){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??jc,i=e.confirmCreate??jE,a=[],l=Bc(),u=cs.find(m=>m.path===Nc),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: ${Nc} 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 cs){if(m.path===Nc&&!c)continue;let p=join(t,m.path),g=await Fc({dstPath:p,template:m,force:n,isInteractive:o,confirmOverwrite:f=>s(f)});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 Fc(e){let{dstPath:t,template:r,force:n,isInteractive:o,confirmOverwrite:s}=e;return existsSync(t)?BE(readFileSync(t,"utf8"))===r.sha256?{status:"unchanged",write:false}:n?{status:"divergent",write:true}:(FE(r.path),o?await s(r.path)?{status:"divergent",write:true}:{status:"declined",write:false}:{status:"declined",write:false}):{status:"new",write:true}}function FE(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 jc(e){return z(` Overwrite ${e} with the updated template? [y/N] `)}async function jE(e){return z(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}function JE(e){return createHash("sha256").update(e,"utf8").digest("hex")}function qg(e,t=e,r=[]){for(let n of readdirSync(e).sort()){let o=join(e,n),s=statSync(o);s.isDirectory()?qg(o,t,r):s.isFile()&&r.push(relative(t,o).split("\\").join("/"));}return r}function Yg(e,t){let r=readFileSync(t,"utf8");return {path:e,sha256:JE(r),content:r}}function ma(){return process.env.FLOW_HARNESS_PATH}function Zg(e){let t=join(e,"docs","catalog");return qg(t).map(r=>Yg(`docs/catalog/${r}`,join(t,r)))}function fa(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=>Yg(`docs/playbooks/${a}`,join(s,a))));}return n}var ga=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 qE(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 YE(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function ZE(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function QE(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=YE(s.path),a=ZE(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 Qg(e){let t=e.targetDir??process.cwd(),r=e.dryRun??false,n=e.force??false,o=e.isInteractive??!!process.stdin.isTTY,s=e.confirmOverwrite??jc,i=ma();if(!i)throw new ga("FLOW_HARNESS_PATH is not set");let a,l;try{a=Zg(i),l=fa(i);}catch(h){throw new ga(`could not read docs from "${i}" (${h instanceof Error?h.message:String(h)})`)}let u=e.docsLang??"all",c=e.installedBundles.length===0,d=c?[]:qE(e.installedBundles,l),m=QE([...a,...d],u),p=[],g=Bc();for(let h of m){let y=join(t,h.path),I=await Fc({dstPath:y,template:h,force:n,isInteractive:o,confirmOverwrite:M=>s(M)});p.push({path:h.path,status:I.status}),g[I.status]++,I.write&&!r&&(mkdirSync(dirname(y),{recursive:true}),writeFileSync(y,h.content,"utf8"));}let f=g.divergent>0||g.declined>0;return {files:p,counts:g,hasUnresolved:f,skippedPlaybooks:c}}function eh(e){let t=Ce().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();Pe();Xr();R();var Vc=b("lib:otelMetrics"),tT="flow-plugins-cli",rT="1.0.0",nT=5e3;function oT(){return Ot("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function sT(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 iT(e,t){let r=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:tT,version:rT},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:r,timeUnixNano:r,attributes:Object.entries(t).map(([n,o])=>sT(n,o))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Jc(e,t={}){try{let[r,n]=await Promise.all([Cn(),ee()]),o=r?.email,s=n?.tenant;if(!o||!s){Vc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let i=iT(e,t);await np.post(oT(),{json:i,timeout:nT,headers:{"Content-Type":"application/json","x-flow-user":o,flowtenant:s}}),Vc.debug(`OTel metric sent: ${e}`);}catch(r){Vc.warn(`Failed to send OTel metric "${e}": ${String(r)}`);}}var Wc=b("cli:init"),cT={new:{label:"new",color:P.green},unchanged:{label:"unchanged",color:P.dim},divergent:{label:"kept (differs from template)",color:P.yellow},declined:{label:"pending (declined)",color:P.yellow}};function uT(e){process.stdout.write(`
558
558
  `+P.bold(` flow setup strategy
559
559
  `)),process.stdout.write(P.dim(` Target: ${e}
560
560
 
561
561
  `)),process.stdout.write(P.dim(` Files evaluated:
562
562
  `));for(let t of cs)process.stdout.write(P.dim(` \xB7 ${t.path}
563
563
  `));process.stdout.write(`
564
- `);}function pT(e,t,r,n){T(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=>{Gc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),Jc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function rh(e,t){T(E.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{Gc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),Jc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function mT(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function fT(){return z(" Continue anyway? [y/N] ")}async function gT(){return b(`docs/catalog/ is the skill/agent/command catalog (~2.6MB); docs/playbooks/ is the
564
+ `);}function dT(e,t,r,n){T(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=>{Wc.warn(`Failed to emit strategy init completed event: ${String(o)}`);}),Jc("flow_cli.strategy_init",{dry_run:t,files_new:e.new,exit_code:r}).catch(()=>{});}function th(e,t){T(E.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:t}).catch(r=>{Wc.warn(`Failed to emit strategy init failed event: ${String(r)}`);}),Jc("flow_cli.strategy_init_failed",{duration_ms:t}).catch(()=>{});}async function pT(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function mT(){return z(" Continue anyway? [y/N] ")}async function fT(){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 hT(){return wi(" 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 ha(e){if(Gc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await Z())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmContinueWithoutGit??fT;if(!await mT(t)){let y=`${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?Ue({error:y,exitCode:1}):v(`${y} Re-run interactively to confirm, or run "git init" first.`),1;if(b(y),!await n())return 1}e.json||dT(t);let o=Date.now(),s;try{s=await qg({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(y){throw rh(y instanceof Error?y.message:String(y),Date.now()-o),y}let i,a=e.confirmDocsContent??gT,l=e.selectDocsLang??hT,u=!!e.docsContent,c=e.docsLang??"all";if(!u&&r&&(u=await a(),u&&(c=await l())),u)try{let y=ma();if(!y)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 I=new Set(Object.keys(fa(y))),M=th(I);i=await eh({targetDir:t,dryRun:e.dryRun,force:e.force,installedBundles:M,docsLang:c});}catch(y){throw rh(y instanceof Error?y.message:String(y),Date.now()-o),y}let d=s.hasUnresolved||i?.hasUnresolved?2:0;if(pT(s.counts,!!e.dryRun,d,Date.now()-o),e.json)return ge({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?P.dim("[dry-run] "):"";process.stdout.write(P.bold(` Result:
568
- `));for(let y of s.files){let{label:I,color:M}=uT[y.status];process.stdout.write(` ${m}${M(I.padEnd(18))} ${y.path}
567
+ it if you don't run that app.`),z(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function gT(){return wi(" 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 ha(e){if(Wc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`),!await Z())return 1;let t=e.path??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=e.confirmContinueWithoutGit??mT;if(!await pT(t)){let y=`${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?Ue({error:y,exitCode:1}):v(`${y} Re-run interactively to confirm, or run "git init" first.`),1;if(x(y),!await n())return 1}e.json||uT(t);let o=Date.now(),s;try{s=await Xg({targetDir:t,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(y){throw th(y instanceof Error?y.message:String(y),Date.now()-o),y}let i,a=e.confirmDocsContent??fT,l=e.selectDocsLang??gT,u=!!e.docsContent,c=e.docsLang??"all";if(!u&&r&&(u=await a(),u&&(c=await l())),u)try{let y=ma();if(!y)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 I=new Set(Object.keys(fa(y))),M=eh(I);i=await Qg({targetDir:t,dryRun:e.dryRun,force:e.force,installedBundles:M,docsLang:c});}catch(y){throw th(y instanceof Error?y.message:String(y),Date.now()-o),y}let d=s.hasUnresolved||i?.hasUnresolved?2:0;if(dT(s.counts,!!e.dryRun,d,Date.now()-o),e.json)return fe({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?P.dim("[dry-run] "):"";process.stdout.write(P.bold(` Result:
568
+ `));for(let y of s.files){let{label:I,color:M}=cT[y.status];process.stdout.write(` ${m}${M(I.padEnd(18))} ${y.path}
569
569
  `);}process.stdout.write(`
570
- `);let{new:p,unchanged:g,divergent:f,declined:h}=s.counts;if(Y(`${p} new, ${g} unchanged, ${f} kept (differs from template)`+(h>0?`, ${h} pending confirmation`:"")),(f>0||h>0)&&b(`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(`
570
+ `);let{new:p,unchanged:g,divergent:f,declined:h}=s.counts;if(Y(`${p} new, ${g} unchanged, ${f} kept (differs from template)`+(h>0?`, ${h} pending confirmation`:"")),(f>0||h>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
  `+P.bold(` docs/catalog + docs/playbooks:
572
- `)),i.skippedPlaybooks&&b('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let y=i.counts;Y(`${y.new} new, ${y.unchanged} unchanged, ${y.divergent} kept (differs from template)`+(y.declined>0?`, ${y.declined} pending confirmation`:"")),(y.divergent>0||y.declined>0)&&b("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return d!==0&&v("flow setup strategy finished with unresolved files \u2014 see above."),d}N();j();var co=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var zc="repos.yaml",ST="projects";function xT(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 Xc(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}function oh(e){let t=[];return {repos:e.map(n=>{let o=Xc(n.remote);if(o===n.remote)return n;let s={...n,remote:o};return t.push({before:n,after:s}),s}),converted:t}}var bT=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function Sa(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(!bT.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 sh(e){let t=join(e,zc);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??ST)},repos:xT(r.repos,"repos",n),warnings:n}}function xa(e,t){let r=join(e,zc),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function ih(e){let t=join(e,".gitignore"),r=zc;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 y=i.counts;Y(`${y.new} new, ${y.unchanged} unchanged, ${y.divergent} kept (differs from template)`+(y.declined>0?`, ${y.declined} pending confirmation`:"")),(y.divergent>0||y.declined>0)&&x("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return d!==0&&v("flow setup strategy finished with unresolved files \u2014 see above."),d}N();j();var co=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Gc="repos.yaml",wT="projects";function ST(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 zc(e){let t=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return t?`git@github.com:${t[1]}/${t[2]}.git`:e}function nh(e){let t=[];return {repos:e.map(n=>{let o=zc(n.remote);if(o===n.remote)return n;let s={...n,remote:o};return t.push({before:n,after:s}),s}),converted:t}}var bT=/^(git@[^:]+:[^/]+\/[^/]+(\.git)?|https?:\/\/[^/]+\/[^/]+\/[^/]+(\.git)?)\/?$/;function Sa(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(!bT.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 oh(e){let t=join(e,Gc);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??wT)},repos:ST(r.repos,"repos",n),warnings:n}}function ba(e,t){let r=join(e,Gc),{warnings:n,...o}=t;writeFileSync(r,stringify(o),"utf8");}function sh(e){let t=join(e,".gitignore"),r=Gc;if(!existsSync(t)){writeFileSync(t,`${r}
573
573
  `,"utf8");return}readFileSync(t,"utf8").split(`
574
574
  `).some(s=>s.trim()===r)||appendFileSync(t,`${r}
575
- `,"utf8");}function ah(e,t){let r=join(e,".gitignore"),n=`${t}/`;if(!existsSync(r)){writeFileSync(r,`${n}
575
+ `,"utf8");}function ih(e,t){let r=join(e,".gitignore"),n=`${t}/`;if(!existsSync(r)){writeFileSync(r,`${n}
576
576
  `,"utf8");return}let o=readFileSync(r,"utf8");o.split(`
577
577
  `).some(i=>i.trim()===n)||appendFileSync(r,`${o.endsWith(`
578
578
  `)?"":`
579
579
  `}${n}
580
- `,"utf8");}function lh(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
580
+ `,"utf8");}function ah(e,t){let r=join(e,".claudeignore"),n=existsSync(r)?readFileSync(r,"utf8"):"",o=new Set(n.split(`
581
581
  `).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.
582
582
  `,a=s.map(l=>`# ${l}/ \u2014 repos cloned via flow setup workspace, not part of this repo's own docs.
583
583
  ${l}/`).join(`
@@ -586,21 +586,21 @@ ${l}/`).join(`
586
586
  ${a}
587
587
  `,"utf8"):writeFileSync(r,`${i}
588
588
  ${a}
589
- `,"utf8");}var nh="## Off-Limits \u2014 Workspace Repos";function ch(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(nh))return "already-present";let s=`
590
- ${nh}
589
+ `,"utf8");}var rh="## Off-Limits \u2014 Workspace Repos";function lh(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(rh))return "already-present";let s=`
590
+ ${rh}
591
591
 
592
592
  \`${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\`.
593
593
 
594
594
  > Off-limits: do not read, index, link, or reference files inside this folder in any context.
595
595
  `;return appendFileSync(n,`${o.endsWith(`
596
596
  `)?"":`
597
- `}${s}`,"utf8"),"appended"}var uh="projects";function IT(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 dh(){let e=await Wn(" Repo URL \u2014 SSH or HTTPS (ENTER to finish): ");if(!e)return null;let t=IT(e);if(!t)return process.stdout.write(` Could not parse a repo name from that URL \u2014 skipped.
598
- `),null;let r=await Wn(` Group/category for '${t}' (optional, default: general): `),n=Xc(e);return {name:t,remote:n,group:r||"general"}}async function ph(){if(!await z("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Wn(` Folder for work repos (default: ${uh}): `),r=[];for(;;){let n=await dh();if(!n)break;r.push(n);}return r.length===0?null:{workspace:{repos_dir:t||uh},repos:r,warnings:[]}}async function mh(e){let{valid:t,invalid:r}=Sa(e);process.stdout.write(` Current repos in repos.yaml (${e.length}):
597
+ `}${s}`,"utf8"),"appended"}var ch="projects";function xT(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 uh(){let e=await Jn(" Repo URL \u2014 SSH or HTTPS (ENTER to finish): ");if(!e)return null;let t=xT(e);if(!t)return process.stdout.write(` Could not parse a repo name from that URL \u2014 skipped.
598
+ `),null;let r=await Jn(` Group/category for '${t}' (optional, default: general): `),n=zc(e);return {name:t,remote:n,group:r||"general"}}async function dh(){if(!await z("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let t=await Jn(` Folder for work repos (default: ${ch}): `),r=[];for(;;){let n=await uh();if(!n)break;r.push(n);}return r.length===0?null:{workspace:{repos_dir:t||ch},repos:r,warnings:[]}}async function ph(e){let{valid:t,invalid:r}=Sa(e);process.stdout.write(` Current repos in repos.yaml (${e.length}):
599
599
  `);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}
600
- `);}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 dh();if(!i)break;n=[...n,i],o=true;}return {repos:n,changed:o}}R();var fh=x("workspace:repos"),gh=6e4;async function TT(e){try{return (await simpleGit(e).status()).current}catch{return null}}function hh(){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 yh=["GIT_TERMINAL_PROMPT"];async function PT(e){await simpleGit(e,{timeout:{block:gh},allowEnvironment:yh}).env(hh()).pull(["--ff-only"]);}async function CT(e,t){await simpleGit({timeout:{block:gh},allowEnvironment:yh}).env(hh()).clone(e,t);}async function wh(e,t){let r=join(t,e.name),n=join(r,".git");if(existsSync(n)){let o=await TT(r);if(o==="main"||o==="master")try{return await PT(r),{name:e.name,outcome:"updated"}}catch(s){return fh.warn(`[${e.name}] pull failed (branch diverged?): ${String(s)}`),{name:e.name,outcome:"skipped"}}return {name:e.name,outcome:"skipped"}}try{return mkdirSync(t,{recursive:!0}),await CT(e.remote,r),{name:e.name,outcome:"cloned"}}catch(o){let s=o instanceof Error?o.message:String(o);return fh.error(`[${e.name}] clone failed: ${s}`),{name:e.name,outcome:"failed",error:s}}}function Sh(e,t){return !existsSync(join(t,e.name,".git"))}function xh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var RT=promisify(execFile),bh=5e3;async function Ih(){try{let{stdout:e,stderr:t}=await RT("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${bh/1e3}`],{timeout:bh+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Qc(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function Eh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=sh(t);if(n){if(r){let f=await mh(n.repos);f.changed?(n={...n,repos:f.repos},xa(t,n)):n={...n,repos:f.repos};}}else {if(!r)return Qc();let f=await ph();if(!f)return Qc();xa(t,f),ih(t),n=f;}let{repos:o,converted:s}=oh(n.repos);s.length>0&&(n={...n,repos:o},xa(t,n)),lh(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=Sa(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=>Sh(f,i))&&!await Ih())return Qc({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let d=[];for(let f=0;f<a.length;f++){let h=a[f];e.onRepoProgress?.({name:h.name,index:f,total:a.length,status:"start"});let y=await wh(h,i);d.push(y),e.onRepoProgress?.({name:h.name,index:f,total:a.length,status:y.outcome});}let m=new Set(a.map(f=>f.name)),p=xh(i,m),g=0;if(e.prune&&p.length>0)for(let f of p)rmSync(join(i,f),{recursive:true,force:true}),g++;return ah(t,n.workspace.repos_dir),{repos:d,orphans:e.prune?[]:p,prunedCount:g,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}R();var MT=["local","project","user"],Ph=[{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"}],eu=Ph.map(e=>e.name);function LT(e){return e.filter(t=>!eu.includes(t))}function _T(){b(`The following ${co.length} runbook bundles will be installed:`);for(let e of co)process.stdout.write(` - ${e}
601
- `);}async function DT(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of Ph)await z(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function OT(){return wi(" Install scope:",MT.map(e=>({value:e,label:Lt[e].actionLabel,description:Lt[e].description})))}var ps=Symbol("skip");async function Th(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=ta(e);if(a){if(a.scope===n)return o||b(`${t}${e} is already installed ${Yt(a)}. Use --force to reinstall.`),ps;if(o||!s)return o||b(`${t}Skipping ${e} \u2014 already installed ${Yt(a)}. Re-run with --force to install here too.`),ps;if(!await ra(e,n,a))return b(`${t}Skipped ${e}.`),ps;let u=await is(e,{force:true,scope:a.scope});if(u!==0)return b(`${t}Could not remove ${e} from ${Yt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||b(`${t}Installing ${e}...`),ao([e],{scope:n,silent:o,force:i})}async function tu(e={}){if(!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=LT(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${eu.join(", ")}`;return e.silent?ge({error:a}):v(a),1}}e.silent||_T();let r=e.scope;if(!r&&!e.silent&&t)try{r=await OT();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
602
- `),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<co.length;a++){let l=co[a],u=`[${a+1}/${co.length}] `,c=await Th(l,u,o);c!==ps&&s.push(c);}let i=e.extraPlugins?eu.filter(a=>e.extraPlugins.includes(a)):await DT(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await Th(l,u,o);c!==ps&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
603
- `),130;throw i}return s.some(i=>i!==0)?1:0}var UT=x("cli:setup-workspace");function Ch(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function NT(){b("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:
600
+ `);}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 uh();if(!i)break;n=[...n,i],o=true;}return {repos:n,changed:o}}R();var mh=b("workspace:repos"),fh=6e4;async function ET(e){try{return (await simpleGit(e).status()).current}catch{return null}}function gh(){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 hh=["GIT_TERMINAL_PROMPT"];async function TT(e){await simpleGit(e,{timeout:{block:fh},allowEnvironment:hh}).env(gh()).pull(["--ff-only"]);}async function PT(e,t){await simpleGit({timeout:{block:fh},allowEnvironment:hh}).env(gh()).clone(e,t);}async function yh(e,t){let r=join(t,e.name),n=join(r,".git");if(existsSync(n)){let o=await ET(r);if(o==="main"||o==="master")try{return await TT(r),{name:e.name,outcome:"updated"}}catch(s){return mh.warn(`[${e.name}] pull failed (branch diverged?): ${String(s)}`),{name:e.name,outcome:"skipped"}}return {name:e.name,outcome:"skipped"}}try{return mkdirSync(t,{recursive:!0}),await PT(e.remote,r),{name:e.name,outcome:"cloned"}}catch(o){let s=o instanceof Error?o.message:String(o);return mh.error(`[${e.name}] clone failed: ${s}`),{name:e.name,outcome:"failed",error:s}}}function wh(e,t){return !existsSync(join(t,e.name,".git"))}function Sh(e,t){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(r=>r.isDirectory()&&!t.has(r.name)).map(r=>r.name):[]}var AT=promisify(execFile),bh=5e3;async function xh(){try{let{stdout:e,stderr:t}=await AT("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${bh/1e3}`],{timeout:bh+2e3});return `${e}${t}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}function Zc(e={}){return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true,manifestWarnings:[],sshBlocked:false,...e}}async function vh(e={}){let t=e.targetDir??process.cwd(),r=e.isInteractive??!!process.stdin.isTTY,n=oh(t);if(n){if(r){let f=await ph(n.repos);f.changed?(n={...n,repos:f.repos},ba(t,n)):n={...n,repos:f.repos};}}else {if(!r)return Zc();let f=await dh();if(!f)return Zc();ba(t,f),sh(t),n=f;}let{repos:o,converted:s}=nh(n.repos);s.length>0&&(n={...n,repos:o},ba(t,n)),ah(t,n.workspace);let i=join(t,n.workspace.repos_dir),{valid:a,invalid:l}=Sa(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=>wh(f,i))&&!await xh())return Zc({skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:true});let d=[];for(let f=0;f<a.length;f++){let h=a[f];e.onRepoProgress?.({name:h.name,index:f,total:a.length,status:"start"});let y=await yh(h,i);d.push(y),e.onRepoProgress?.({name:h.name,index:f,total:a.length,status:y.outcome});}let m=new Set(a.map(f=>f.name)),p=Sh(i,m),g=0;if(e.prune&&p.length>0)for(let f of p)rmSync(join(i,f),{recursive:true,force:true}),g++;return ih(t,n.workspace.repos_dir),{repos:d,orphans:e.prune?[]:p,prunedCount:g,skippedNoManifest:false,manifestWarnings:u,workspaceDirs:n.workspace,sshBlocked:false}}R();var $T=["local","project","user"],Th=[{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"}],Qc=Th.map(e=>e.name);function MT(e){return e.filter(t=>!Qc.includes(t))}function LT(){x(`The following ${co.length} runbook bundles will be installed:`);for(let e of co)process.stdout.write(` - ${e}
601
+ `);}async function _T(e,t){if(t||!e)return [];let r=[];for(let{name:n,description:o}of Th)await z(` Also install ${n}? (${o}) [y/N] `)&&r.push(n);return r}async function DT(){return wi(" Install scope:",$T.map(e=>({value:e,label:Lt[e].actionLabel,description:Lt[e].description})))}var ps=Symbol("skip");async function Eh(e,t,r){let{scope:n,silent:o,isInteractive:s,force:i}=r;if(!i){let a=ta(e);if(a){if(a.scope===n)return o||x(`${t}${e} is already installed ${Yt(a)}. Use --force to reinstall.`),ps;if(o||!s)return o||x(`${t}Skipping ${e} \u2014 already installed ${Yt(a)}. Re-run with --force to install here too.`),ps;if(!await ra(e,n,a))return x(`${t}Skipped ${e}.`),ps;let u=await is(e,{force:true,scope:a.scope});if(u!==0)return x(`${t}Could not remove ${e} from ${Yt(a)} \u2014 skipping rather than leaving it in an inconsistent state.`),u}}return o||x(`${t}Installing ${e}...`),ao([e],{scope:n,silent:o,force:i})}async function eu(e={}){if(!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY;if(e.extraPlugins){let i=MT(e.extraPlugins);if(i.length>0){let a=`--extra-plugins: unknown bundle(s) ${i.join(", ")} \u2014 valid values are ${Qc.join(", ")}`;return e.silent?fe({error:a}):v(a),1}}e.silent||LT();let r=e.scope;if(!r&&!e.silent&&t)try{r=await DT();}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
602
+ `),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<co.length;a++){let l=co[a],u=`[${a+1}/${co.length}] `,c=await Eh(l,u,o);c!==ps&&s.push(c);}let i=e.extraPlugins?Qc.filter(a=>e.extraPlugins.includes(a)):await _T(t,e.silent);for(let a=0;a<i.length;a++){let l=i[a],u=`[extra ${a+1}/${i.length}] `,c=await Eh(l,u,o);c!==ps&&s.push(c);}}catch(i){if(i instanceof Error&&i.message==="SIGINT")return process.stdout.write(`
603
+ `),130;throw i}return s.some(i=>i!==0)?1:0}var OT=b("cli:setup-workspace");function Ph(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}function UT(){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:
604
604
  `),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
605
605
  `),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
606
606
  `),process.stdout.write(` 3. Start the agent: eval "$(ssh-agent -s)"
@@ -608,14 +608,14 @@ ${nh}
608
608
  `),process.stdout.write(` 5. Copy the public key: pbcopy < ~/.ssh/id_ed25519.pub (macOS)
609
609
  `),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
610
610
  `),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
611
- `);}function BT(e){let t=`[${e.index+1}/${e.total}]`;if(e.status==="start"){process.stdout.write(` ${t} ${e.name}...
612
- `);return}process.stdout.write(` ${t} ${e.name}: ${Ch(e.status)}
613
- `);}function FT(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,Ch(r.outcome),r.error??""]);yr(["","Repo","Outcome","Detail"],t);}async function jT(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=ch(e,t.workspaceDirs,s);i==="appended"?b(`CLAUDE.md updated with an off-limits note for '${o}/'.`):i==="already-present"?b("CLAUDE.md already has the off-limits note \u2014 skipped."):i==="no-claude-md"&&b("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function ru(e={}){if(UT.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await Eh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:BT});if(e.json)return ge({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)b(`repos.yaml: ${a}`);if(r.sshBlocked)return NT(),1;if(r.skippedNoManifest)return b("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;FT(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 Y(`${n} cloned, ${o} updated, ${s} skipped`+(i>0?`, ${i} failed`:"")+(r.prunedCount>0?`, ${r.prunedCount} pruned`:"")),r.orphans.length>0&&b(`Orphan director${r.orphans.length===1?"y":"ies"} not in repos.yaml: ${r.orphans.join(", ")}. Re-run with --prune to remove.`),await jT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var KT=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ha({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>tu({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>ru({path:e})}];async function HT(e){return z(` Run ${e}? [y/N] `)}async function kh(e={}){if(!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??HT,n=!!e.yes||!t;!e.yes&&!t&&b("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let o=[];for(let s of KT){if(!(n||await r(s.label))){b(` \u2192 ${s.key} skipped.`);continue}o.push(await s.run(e.path));}return o.some(s=>s!==0)?1:0}var VT=">=2.9.0-beta.28 <2.10.2-beta.49";function WT(e){return tc.valid(e)?tc.satisfies(e,VT,{includePrerelease:true}):false}function Rh(e=ue){return WT(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.
611
+ `);}function NT(e){let t=`[${e.index+1}/${e.total}]`;if(e.status==="start"){process.stdout.write(` ${t} ${e.name}...
612
+ `);return}process.stdout.write(` ${t} ${e.name}: ${Ph(e.status)}
613
+ `);}function BT(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,Ph(r.outcome),r.error??""]);yr(["","Repo","Outcome","Detail"],t);}async function FT(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=lh(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 tu(e={}){if(OT.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=await vh({targetDir:e.path,prune:e.prune,isInteractive:t,onRepoProgress:e.json?void 0:NT});if(e.json)return fe({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 UT(),1;if(r.skippedNoManifest)return x("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;BT(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 Y(`${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 FT(e.path??process.cwd(),r,e.json,t),i>0?1:0}var jT=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ha({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>eu({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>tu({path:e})}];async function KT(e){return z(` Run ${e}? [y/N] `)}async function Ch(e={}){if(!await Z())return 1;let t=e.isInteractive??!!process.stdin.isTTY,r=e.confirmStep??KT,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 jT){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 HT=">=2.9.0-beta.28 <2.10.2-beta.49";function VT(e){return ec.valid(e)?ec.satisfies(e,HT,{includePrerelease:true}):false}function Ah(e=ge){return VT(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.
614
614
  Run: npm install -g @ciandt-flow/cli@latest
615
- Then re-run this command.`}:{blocked:false}}function zT(e){let t=["","All commands:",""];function r(n,o,s){if(n.name()==="help")return;let i=`${o} ${n.name()}`,a=" ".repeat(s);t.push(`${a}flow${i}${n.description()?" \u2014 "+n.description():""}`);for(let l of n.commands)r(l,i,s+1);}for(let n of e.commands)r(n,"",1);return t.push("","Without arguments, opens the interactive interface (TUI).","Use 'flow <command> --help' for details and examples on each command."),t.join(`
616
- `)}function XT(){let e=fileURLToPath(import.meta.url);return e.endsWith(".js")?{runner:"node",entry:le__default.join(le__default.dirname(e),"ctxa.js")}:{runner:"tsx",entry:le__default.join(le__default.dirname(e),"module/ctxa/cli.ts")}}function $h(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ue}`,"-V, --version","Display the CLI version").addHelpText("after",()=>zT(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",`
615
+ Then re-run this command.`}:{blocked:false}}function JT(e){let t=["","All commands:",""];function r(n,o,s){if(n.name()==="help")return;let i=`${o} ${n.name()}`,a=" ".repeat(s);t.push(`${a}flow${i}${n.description()?" \u2014 "+n.description():""}`);for(let l of n.commands)r(l,i,s+1);}for(let n of e.commands)r(n,"",1);return t.push("","Without arguments, opens the interactive interface (TUI).","Use 'flow <command> --help' for details and examples on each command."),t.join(`
616
+ `)}function Rh(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${ge}`,"-V, --version","Display the CLI version").addHelpText("after",()=>JT(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",`
617
617
  Examples:
618
- $ flow setup init`).action(async()=>{let c=await kc();_(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",`
618
+ $ flow setup init`).action(async()=>{let c=await Cc();O(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",`
619
619
  Examples:
620
620
  $ flow setup strategy
621
621
  $ flow setup strategy --dry-run
@@ -623,7 +623,7 @@ Examples:
623
623
  $ flow setup strategy --assistant claude-code
624
624
  $ flow setup strategy --docs-content
625
625
  $ flow setup strategy --docs-content --docs-lang en
626
- $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await ha({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant,docsContent:c.docsContent,docsLang:c.docsLang});_(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
626
+ $ flow setup strategy --json --path ./my-repo`).action(async c=>{let d=await ha({dryRun:c.dryRun,json:c.json,force:c.force,path:c.path,assistant:c.assistant,docsContent:c.docsContent,docsLang:c.docsLang});O(d);}),r.command("harness").description("Install the fixed set of Flow runbook bundles (tech, security, product, design, ops, common, quality)").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--silent","Output in JSON only",false).option("--force","Reinstall bundles already installed elsewhere without asking for confirmation",false).option("--extra-plugins <names>","Also install these opt-in auxiliary bundles (comma-separated: cit-tools, commons-claude). The only way to install them non-interactively or with --silent \u2014 an interactive run without this flag still asks per bundle, and passing it skips that prompt entirely.").addHelpText("after",`
627
627
  Examples:
628
628
  $ flow setup harness
629
629
  $ flow setup harness --scope project
@@ -639,11 +639,11 @@ here too without asking, leaving the bundle enabled in both places.
639
639
  After the 7 bundles, an interactive run also asks once per opt-in extra
640
640
  (cit-tools, commons-claude) unless --extra-plugins was passed, which installs
641
641
  exactly the named bundles with no prompt \u2014 required in --silent or
642
- non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await tu({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});_(d);}),r.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
642
+ non-interactive runs, since no prompt happens there either way.`).action(async c=>{let d=await eu({scope:c.scope,silent:c.silent,force:c.force,extraPlugins:c.extraPlugins?.split(",").map(m=>m.trim()).filter(Boolean)});O(d);}),r.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
643
643
  Examples:
644
644
  $ flow setup workspace
645
645
  $ flow setup workspace --prune
646
- $ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await ru({path:c.path,prune:c.prune,json:c.json});_(d);}),r.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
646
+ $ flow setup workspace --json --path ./my-workspace`).action(async c=>{let d=await tu({path:c.path,prune:c.prune,json:c.json});O(d);}),r.command("framework-strategy").description("Orchestrate strategy \u2192 harness \u2192 workspace, asking [y/N] before each step").option("--path <dir>","Target repository root (defaults to the current directory)").option("--yes","Skip every confirmation and run all 3 steps back to back",false).addHelpText("after",`
647
647
  Examples:
648
648
  $ flow setup framework-strategy
649
649
  $ flow setup framework-strategy --yes
@@ -652,13 +652,13 @@ Examples:
652
652
  Without --yes and with an interactive terminal, asks [y/N] before each of the
653
653
  3 steps (strategy, harness, workspace) \u2014 declining one skips just that step
654
654
  and moves to the next. Without an interactive terminal, runs all 3 steps
655
- without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await kh({path:c.path,yes:c.yes});_(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",`
655
+ without prompting even if --yes wasn't passed (there is no terminal to ask in).`).action(async c=>{let d=await Ch({path:c.path,yes:c.yes});O(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",`
656
656
  Examples:
657
657
  $ flow plugin list
658
658
  $ flow plugin list --available
659
659
  $ flow plugin list --outdated
660
660
  $ flow plugin list --json
661
- $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await rg(c);_(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",`
661
+ $ flow plugin list --available --source flow-harness`).action(async c=>{let d=await tg(c);O(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",`
662
662
  Examples:
663
663
  $ flow plugin install flow-adr-writer
664
664
  $ flow plugin install flow-adr-writer --scope project
@@ -672,11 +672,11 @@ Examples:
672
672
  A plugin already installed elsewhere (any scope, any project) prompts to
673
673
  move it here instead (uninstall there, install here) unless --force is
674
674
  passed, which installs here too without asking, leaving it enabled in
675
- both places.`).action(async(c,d)=>{let m=c.filter(g=>g.trim());if(m.length===0){v("No valid plugin names provided"),_(1);return}Je("cli",{verbose:d.verbose,silent:d.silent});let p=await ao(m,d);_(p);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
675
+ both places.`).action(async(c,d)=>{let m=c.filter(g=>g.trim());if(m.length===0){v("No valid plugin names provided"),O(1);return}We("cli",{verbose:d.verbose,silent:d.silent});let p=await ao(m,d);O(p);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
676
676
  Examples:
677
677
  $ flow plugin uninstall flow-adr-writer
678
678
  $ flow plugin uninstall flow-adr-writer --scope project
679
- $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await is(c,d);_(m);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
679
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await is(c,d);O(m);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
680
680
  Examples:
681
681
  $ flow plugin update flow-adr-writer
682
682
  $ flow plugin update flow-adr-writer --scope project
@@ -685,79 +685,79 @@ Examples:
685
685
  $ flow plugin update flow-adr-writer --verbose
686
686
  $ flow plugin update flow-adr-writer --silent
687
687
  $ flow plugin update
688
- $ flow plugin update --dry-run`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await ig(c??null,d);_(m);}),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",`
688
+ $ flow plugin update --dry-run`).action(async(c,d)=>{We("cli",{verbose:d.verbose,silent:d.silent});let m=await sg(c??null,d);O(m);}),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",`
689
689
  Examples:
690
690
  $ flow plugin enable flow-adr-writer
691
- $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await ng(c,d);_(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",`
691
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{We("cli");let m=await rg(c,d);O(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",`
692
692
  Examples:
693
693
  $ flow plugin disable flow-adr-writer
694
- $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Je("cli");let m=await og(c,d);_(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
694
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{We("cli");let m=await ng(c,d);O(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
695
695
  Examples:
696
696
  $ flow plugin export
697
- $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Fg(c);_(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",`
697
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Bg(c);O(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",`
698
698
  Examples:
699
699
  $ flow plugin import flow-plugins.json
700
700
  $ flow plugin import flow-plugins.json --scope user
701
701
  $ flow plugin import flow-plugins.json --force
702
702
  $ flow plugin import flow-plugins.json --dry-run
703
- $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await jg(c,d);_(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",`
703
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Fg(c,d);O(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",`
704
704
  Examples:
705
705
  $ flow plugin marketplace add anthropics/claude-code
706
706
  $ flow plugin marketplace add https://github.com/owner/repo
707
707
  $ flow plugin marketplace add anthropics/claude-code --force
708
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await cg(c,d);_(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",`
708
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{We("cli",{verbose:d.verbose,silent:d.silent});let m=await lg(c,d);O(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",`
709
709
  Examples:
710
710
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
711
711
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
712
712
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
713
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Je("cli",{verbose:m.verbose,silent:m.silent});let p=await Cm(c,d,m);_(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",`
713
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{We("cli",{verbose:m.verbose,silent:m.silent});let p=await Pm(c,d,m);O(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",`
714
714
  Examples:
715
715
  $ flow mcp remove notion
716
716
  $ flow mcp remove notion --scope project
717
- $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Je("cli",{verbose:d.verbose,silent:d.silent});let m=await km(c,d);_(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",`
717
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{We("cli",{verbose:d.verbose,silent:d.silent});let m=await Cm(c,d);O(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",`
718
718
  Examples:
719
719
  $ flow auth login
720
720
  $ flow auth login --jwt <token>
721
721
  $ flow auth login --jwt <token> --starter-kit dev
722
722
  $ flow auth login --jwt <token> --custom-email name@example.com
723
- $ flow auth login --verbose`).action(async c=>{Je("cli",{verbose:c.verbose});let d=await kc(c);_(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
723
+ $ flow auth login --verbose`).action(async c=>{We("cli",{verbose:c.verbose});let d=await Cc(c);O(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
724
724
  Examples:
725
725
  $ flow auth logout
726
- $ flow auth logout --force`).action(async c=>{let d=await Yf(c.force);_(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
726
+ $ flow auth logout --force`).action(async c=>{let d=await qf(c.force);O(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
727
727
  Examples:
728
- $ flow auth status`).action(async()=>{let c=await Zf();_(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",`
728
+ $ flow auth status`).action(async()=>{let c=await Yf();O(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",`
729
729
  Examples:
730
730
  $ flow skills add vercel-labs/agent-skills
731
731
  $ flow skills add owner/repo -g
732
732
  $ flow skills add owner/repo --skill pr-review commit
733
733
  $ flow skills add ./local/skills -y
734
- $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await _g(c,d);_(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
734
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Lg(c,d);O(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
735
735
  Examples:
736
736
  $ flow skills list
737
737
  $ flow skills list -g
738
- $ flow skills list --json`).action(async c=>{let d=await Og(c);_(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",`
738
+ $ flow skills list --json`).action(async c=>{let d=await Dg(c);O(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",`
739
739
  Examples:
740
740
  $ flow skills remove pr-review
741
- $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Ug(c,d);_(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",`
741
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Og(c,d);O(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",`
742
742
  Examples:
743
743
  $ flow bundle install "My React Kit"
744
744
  $ flow bundle install "Squad Setup Bundle"
745
- $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Je("cli",{verbose:d.verbose});let m=await ag(c);_(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",`
745
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{We("cli",{verbose:d.verbose});let m=await ig(c);O(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",`
746
746
  Examples:
747
747
  $ flow health
748
- $ flow health --fix`).action(async c=>{let d=await ug(c);_(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
748
+ $ flow health --fix`).action(async c=>{let d=await cg(c);O(d);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
749
749
  Examples:
750
750
  $ flow usage
751
- $ flow usage --json`).action(async c=>{let d=await hg(c);_(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await _c();_(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
751
+ $ flow usage --json`).action(async c=>{let d=await gg(c);O(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Lc();O(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
752
752
  Examples:
753
- $ flow modules list`).action(async()=>{let c=await _c();_(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
753
+ $ flow modules list`).action(async()=>{let c=await Lc();O(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
754
754
  Examples:
755
755
  $ flow modules install metrics
756
- $ flow modules install dashboard`).action(async c=>{let d=await Gg(c);_(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",`
756
+ $ flow modules install dashboard`).action(async c=>{let d=await Wg(c);O(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",`
757
757
  Examples:
758
758
  $ flow modules update
759
- $ flow modules update metrics`).action(async c=>{let d=await zg(c??null);_(d);}),t.addCommand(u),t.command("ctxa").description("Analyze Claude Code history/config and surface token-cost savings").helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to flow-ctxa").action(c=>{let{runner:d,entry:m}=XT(),p=spawnSync(d,[m,"ctxa",...c],{stdio:"inherit",env:process.env});_(p.status??1);});for(let c of ce)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Vg(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=Rh();if(m)throw new Error(p)}),t.hook("preAction",()=>{Ji();}),t}R();function ZT(){return le__default.join(Te__default.homedir(),".claude","settings.json")}function Lh(){let e=ZT();try{if(!ie__default.existsSync(e))return !0;let r=JSON.parse(ie__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var sP=x("updateChecker"),iP=promisify(execFile),aP=1440*60*1e3,_h=3e4;function lP(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"update.lock")}async function Dh(e){try{let{stdout:t}=await iP(er(),["view",e,"version"],{timeout:_h,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function cP(e){let t=new AbortController,r=setTimeout(()=>t.abort(),_h);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 uP(e){return e.versionCheck.type==="npm-registry"?Dh(e.versionCheck.package):cP(e.versionCheck.repo)}async function dP(){if(tc.prerelease(ue))return null;let e=await Dh("@ciandt-flow/cli");return e&&Ke(ue,e)?(Zi({currentVersion:ue,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function pP(){let e=nn().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=ce.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<aP)return;let s=await uP(r);try{await xt({...t,lastChecked:new Date().toISOString()});}catch(i){sP.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ke(t.installedVersion,s)&&Ys(r,"background").catch(()=>{});}));}async function ou(){let e=Lh();if(e===false)return;let t=lP();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r;try{r=await lw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await dP().catch(()=>null);n&&process.stdout.write(`
759
+ $ flow modules update metrics`).action(async c=>{let d=await Gg(c??null);O(d);}),t.addCommand(u);for(let c of ce)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Hg(c.alias,d);});return t.hook("preAction",(c,d)=>{if(d.name()==="help")return;let{blocked:m,message:p}=Ah();if(m)throw new Error(p)}),t.hook("preAction",()=>{Wi();}),t}R();function zT(){return le__default.join(Te__default.homedir(),".claude","settings.json")}function Mh(){let e=zT();try{if(!ie__default.existsSync(e))return !0;let r=JSON.parse(ie__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}R();var eP=b("updateChecker"),tP=promisify(execFile),rP=1440*60*1e3,Lh=3e4;function nP(){let e=process.env.FLOW_HOME??le__default.join(Te__default.homedir(),".flow");return le__default.join(e,"update.lock")}async function _h(e){try{let{stdout:t}=await tP(er(),["view",e,"version"],{timeout:Lh,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function oP(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Lh);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 sP(e){return e.versionCheck.type==="npm-registry"?_h(e.versionCheck.package):oP(e.versionCheck.repo)}async function iP(){let e=await _h("@ciandt-flow/cli");return e&&Ke(ge,e)?(Zi({currentVersion:ge,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function aP(){let e=nn().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=ce.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<rP)return;let s=await sP(r);try{await bt({...t,lastChecked:new Date().toISOString()});}catch(i){eP.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ke(t.installedVersion,s)&&Ys(r,"background").catch(()=>{});}));}async function nu(){let e=Mh();if(e===false)return;let t=nP();ie__default.mkdirSync(le__default.dirname(t),{recursive:true});let r;try{r=await aw.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await iP().catch(()=>null);n&&process.stdout.write(`
760
760
  \u26A0 @ciandt-flow/cli v${n} installing in background.
761
761
  Restart flow to apply the update.
762
762
 
763
- `);}await pP().catch(()=>{});}finally{await r().catch(()=>{});}}N();var fP=x("cli"),su=$h(async()=>{Je("tui"),Bu("tui"),Fu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();So("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();So("sigterm",t,r).finally(()=>process.exit(143));}),await ou().catch(()=>{}),await lp().catch(t=>{fP.error(`Failed to init catalog registry: ${String(t)}`);}),await Ff();let{waitUntilExit:e}=render(jsx(jf,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});su.hook("preAction",async(e,t)=>{t!==su&&await ou().catch(()=>{});});try{await su.parseAsync();}catch(e){v(e instanceof Error?e.message:String(e)),_(1);}
763
+ `);}await aP().catch(()=>{});}finally{await r().catch(()=>{});}}N();var cP=b("cli"),ou=Rh(async()=>{We("tui"),Nu("tui"),Bu(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();So("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();So("sigterm",t,r).finally(()=>process.exit(143));}),await nu().catch(()=>{}),await ap().catch(t=>{cP.error(`Failed to init catalog registry: ${String(t)}`);}),await Bf();let{waitUntilExit:e}=render(jsx(Ff,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});ou.hook("preAction",async(e,t)=>{t!==ou&&await nu().catch(()=>{});});try{await ou.parseAsync();}catch(e){v(e instanceof Error?e.message:String(e)),O(1);}