@ciandt-flow/cli 2.4.0-beta.254 → 2.4.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +157 -143
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
- import {execa}from'execa';import qc,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Bg,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as nn from'crypto';import {randomUUID,createHash}from'crypto';import*as Se from'fs';import Se__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as we from'path';import we__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as Te from'os';import Te__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as wa from'readline';import {createInterface}from'readline';import k from'chalk';import Ri from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import qf from'jsonwebtoken';import ug from'proper-lockfile';import $g from'ink-big-text';import Gu from'ink-spinner';import*as Lt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import Dh from'extract-zip';import {simpleGit}from'simple-git';import La from'semver';import sl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var Jm=Object.defineProperty;var hi=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Gm=(e,t)=>{for(var r in t)Jm(e,r,{get:t[r],enumerable:true});};function Tf(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 Bi(e){if(Ol.some(r=>r.test(e)))return true;let t=Tf(e);return !!(t&&Ol.some(r=>r.test(t)))}function Cf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function pr(e,t){let r=Cf(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Bi(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Ol,un=hi(()=>{"use strict";Ol=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function Mh(){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 zc(){return Wc??=Mh(),Wc}var Wc,Xc=hi(()=>{"use strict";});var Zc={};Gm(Zc,{GitRepoAdapter:()=>Sn});function Yc(e,t){if(!Rh.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Rh,Sn,ia=hi(()=>{"use strict";Xc();un();Rh=/^[a-zA-Z0-9_.-]+$/;Sn=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(Bi(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Yc(a,"owner"),Yc(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 qc.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 qc.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 zc();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}}};});var On="FLOW",Z="flow-skills",yi="flow-cli",Un="internal",Qr="external",en={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"}},gl={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},wi=new Set(["internal","external"]),Nn={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},ie="flow-claude-md-setup",Ge=5,Kt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,tn=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,rn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)";var hl=new Set(["skill","mcp","bundle"]),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(hl),origins:new Set(wi)},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(hl)},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(wi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var ko="aes-256-gcm",zm=16,yl=16,Bn=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=nn.randomBytes(zm),n=nn.createCipheriv(ko,this.key,r,{authTagLength:yl}),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:ko}}decrypt(t){if(t.algorithm!==ko)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=nn.createDecipheriv(ko,this.key,Buffer.from(t.iv,"hex"),{authTagLength:yl});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var Xm=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,qm=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Ym=/[A-Za-z0-9+/]{40,}={0,2}/g;function Si(e){return e.replace(Xm,"Bearer ***").replace(qm,"***").replace(Ym,"***").replace(/\r\n|\r|\n/g,"\\n")}var $r=".claude",Ao=".flow";function wl(e,t){return Ii(Z,e,t)}function xi(e){return we.join(Te.homedir(),$r,"plugins","marketplaces",Z,"plugins","native",e)}function $o(){return we.join(Te.homedir(),$r,"plugins","marketplaces",Z,".claude-plugin","marketplace.json")}function Lo(){return we.join(Te.homedir(),$r,"plugins","known_marketplaces.json")}function Sl(){return we.join(Te.homedir(),$r,"plugins","marketplaces",Z)}function xl(){return we.join(Te.homedir(),Ao,"cache","install.lock")}function Il(){return we.join(Te.homedir(),Ao,"logs","flowsetup.log")}function Ii(e,t,r){return we.join(Te.homedir(),$r,"plugins","cache",e,t,r)}function Lr(e){let t=e==="global"?Te.homedir():process.cwd();return we.join(t,".claude","skills")}function Fn(e){let t=e==="global"?Te.homedir():process.cwd();return we.join(t,".claude","skills-lock.json")}function Mo(e="user"){return e==="project"?we.join(process.cwd(),".opencode","plugins"):we.join(Te.homedir(),".config","opencode","plugins")}function bl(){return we.join(Te.homedir(),Ao,"flow-catalogs.json")}function vl(){let e=process.env.FLOW_HOME??we.join(Te.homedir(),Ao);return we.join(e,"config.json")}function Ro(e="user"){return e==="project"||e==="local"?we.join(process.cwd(),$r,"agents"):we.join(Te.homedir(),$r,"agents")}var Zm=5*1024*1024,Qm=3,_o=class{filePath;constructor(){this.filePath=Il(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
- `;try{Se.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=we.dirname(this.filePath);Se.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(Se.statSync(this.filePath).size>Zm){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);Se.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=we.dirname(this.filePath),r=we.basename(this.filePath,".log"),n=Se.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Qm))Se.unlinkSync(we.join(t,o));}catch{}}};var Do=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 Oo=class{write(t){process.stdout.write(t.message+`
5
- `);}};var Uo=[],bi=new Set;function vi(){return Uo}function Pl(e){return bi.add(e),()=>{bi.delete(e);}}var No=class{write(t){Uo.push(t),Uo.length>100&&Uo.shift();for(let r of bi)r();}};var on={debug:0,info:1,warn:2,error:3},Rr={context:"cli",transports:[],minLevel:"warn",debugModules:null};function ef(){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 Ue(e,t){if(e==="tui"){let r=ef();Rr={context:e,transports:[new No,new _o],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Rr={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Rr={context:e,transports:[new Do("cli")],minLevel:"debug",debugModules:null}:Rr={context:e,transports:[new Oo],minLevel:"info",debugModules:null};}function El(){return Rr.transports}function Tl(e,t){let{debugModules:r,minLevel:n}=Rr;return Rr.context==="tui"&&r&&r!=="all"?r.has(t)?on[e]>=on.debug:on[e]>=on.warn:on[e]>=on[n]}var Cl=new Map;function Bo(e,t,r){if(!Tl(e,t))return;let n={level:e,module:t,message:Si(r),timestamp:new Date};for(let o of El())o.write(n);}function x(e){let t=Cl.get(e);if(t)return t;let r={debug:n=>Bo("debug",e,n),info:n=>Bo("info",e,n),warn:n=>Bo("warn",e,n),error:n=>Bo("error",e,n)};return Cl.set(e,r),r}var Pi=x("encryption"),Ei="__encrypted__";function tf(e){return typeof e=="object"&&e!==null&&Ei in e&&e[Ei]===true}function Ti(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[Ei]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Pi.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(tf(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Pi.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Pi.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Ci=promisify(execFile),of=promisify(exec),ct=x("encryption:macos-keyvault"),sn=class{static async isAvailable(){try{let{stdout:t}=await of("command -v security");return ct.debug(`security binary found at: ${t.trim()}`),!0}catch{return ct.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{ct.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ci("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return ct.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return ct.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{ct.debug(`Storing secret: service=${t}, account=${r}`),await Ci("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),ct.debug("security add-generic-password succeeded");}catch(o){let s=o;throw ct.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return ct.debug(`Deleting secret: service=${t}, account=${r}`),await Ci("security",["delete-generic-password","-a",r,"-s",t]),ct.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return ct.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function ae(e){process.stdout.write(k.green(` \u2713 ${y(e)}
6
- `));}function P(e){process.stderr.write(k.red(` \u2717 ${y(e)}
7
- `));}function T(e){process.stdout.write(k.cyan(` \u2139 ${y(e)}
8
- `));}function an(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(c=>(c[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,c)=>l.padEnd(o[c])).join(" ");process.stdout.write(`
9
- `),process.stdout.write(` ${k.bold(i(e))}
10
- `),process.stdout.write(` ${k.dim(s)}
2
+ import {execa}from'execa';import fu,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Qg,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as en from'crypto';import {randomUUID,createHash}from'crypto';import*as me from'fs';import me__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as pe from'path';import pe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as ve from'os';import ve__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as Pa from'readline';import {createInterface}from'readline';import C from'chalk';import Ni from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import ug from'jsonwebtoken';import bg from'proper-lockfile';import Jg from'ink-big-text';import ud from'ink-spinner';import*as Et from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Xh from'unzipper';import {simpleGit}from'simple-git';import Ua from'semver';import wl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var sf=Object.defineProperty;var Ii=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var af=(e,t)=>{for(var r in t)sf(e,r,{get:t[r],enumerable:true});};function Ff(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 Ji(e){if(ql.some(r=>r.test(e)))return true;let t=Ff(e);return !!(t&&ql.some(r=>r.test(t)))}function jf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function or(e,t){let r=jf(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Ji(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var ql,an=Ii(()=>{"use strict";ql=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function Gh(){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 pu(){return du??=Gh(),du}var du,mu=Ii(()=>{"use strict";});var hu={};af(hu,{GitRepoAdapter:()=>wn});function gu(e,t){if(!Wh.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Wh,wn,pa=Ii(()=>{"use strict";mu();an();Wh=/^[a-zA-Z0-9_.-]+$/;wn=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(Ji(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return gu(a,"owner"),gu(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 fu.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 fu.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 pu();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}}};});var Er="FLOW",W="flow-skills",bi="flow-cli",Dn="internal",qr="external",Yr={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"}},kl={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},vi=new Set(["internal","external"]),On={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},te="flow-claude-md-setup",Je=5,Dt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Al="https://flow.ciandt.com",Zr=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,Qr="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)";var $l=new Set(["skill","mcp","bundle"]),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($l),origins:new Set(vi)},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($l)},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(vi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var Lo="aes-256-gcm",cf=16,Ll=16,Un=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=en.randomBytes(cf),n=en.createCipheriv(Lo,this.key,r,{authTagLength:Ll}),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:Lo}}decrypt(t){if(t.algorithm!==Lo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=en.createDecipheriv(Lo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Ll});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var uf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,df=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,pf=/[A-Za-z0-9+/]{40,}={0,2}/g;function Pi(e){return e.replace(uf,"Bearer ***").replace(df,"***").replace(pf,"***").replace(/\r\n|\r|\n/g,"\\n")}var Tr=".claude",Mo=".flow";function Ml(e,t){return Ti(W,e,t)}function Ei(e){return pe.join(ve.homedir(),Tr,"plugins","marketplaces",W,"plugins","native",e)}function Ro(){return pe.join(ve.homedir(),Tr,"plugins","marketplaces",W,".claude-plugin","marketplace.json")}function _o(){return pe.join(ve.homedir(),Tr,"plugins","known_marketplaces.json")}function Rl(){return pe.join(ve.homedir(),Tr,"plugins","marketplaces",W)}function _l(){return pe.join(ve.homedir(),Mo,"cache","install.lock")}function Dl(){return pe.join(ve.homedir(),Mo,"logs","flowsetup.log")}function Ti(e,t,r){return pe.join(ve.homedir(),Tr,"plugins","cache",e,t,r)}function Cr(e){let t=e==="global"?ve.homedir():process.cwd();return pe.join(t,".claude","skills")}function Nn(e){let t=e==="global"?ve.homedir():process.cwd();return pe.join(t,".claude","skills-lock.json")}function Do(e="user"){return e==="project"?pe.join(process.cwd(),".opencode","plugins"):pe.join(ve.homedir(),".config","opencode","plugins")}function Ol(){return pe.join(ve.homedir(),Mo,"flow-catalogs.json")}function Ul(){let e=process.env.FLOW_HOME??pe.join(ve.homedir(),Mo);return pe.join(e,"config.json")}function Oo(e="user"){return e==="project"||e==="local"?pe.join(process.cwd(),Tr,"agents"):pe.join(ve.homedir(),Tr,"agents")}var mf=5*1024*1024,ff=3,Uo=class{filePath;constructor(){this.filePath=Dl(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
3
+ `;try{me.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=pe.dirname(this.filePath);me.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(me.statSync(this.filePath).size>mf){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);me.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=pe.dirname(this.filePath),r=pe.basename(this.filePath,".log"),n=me.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(ff))me.unlinkSync(pe.join(t,o));}catch{}}};var No=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 Bo=class{write(t){process.stdout.write(t.message+`
5
+ `);}};var Fo=[],Ci=new Set;function ki(){return Fo}function Nl(e){return Ci.add(e),()=>{Ci.delete(e);}}var jo=class{write(t){Fo.push(t),Fo.length>100&&Fo.shift();for(let r of Ci)r();}};var tn={debug:0,info:1,warn:2,error:3},Ar={context:"cli",transports:[],minLevel:"warn",debugModules:null};function gf(){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 De(e,t){if(e==="tui"){let r=gf();Ar={context:e,transports:[new jo,new Uo],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Ar={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Ar={context:e,transports:[new No("cli")],minLevel:"debug",debugModules:null}:Ar={context:e,transports:[new Bo],minLevel:"info",debugModules:null};}function Bl(){return Ar.transports}function Fl(e,t){let{debugModules:r,minLevel:n}=Ar;return Ar.context==="tui"&&r&&r!=="all"?r.has(t)?tn[e]>=tn.debug:tn[e]>=tn.warn:tn[e]>=tn[n]}var jl=new Map;function Ko(e,t,r){if(!Fl(e,t))return;let n={level:e,module:t,message:Pi(r),timestamp:new Date};for(let o of Bl())o.write(n);}function x(e){let t=jl.get(e);if(t)return t;let r={debug:n=>Ko("debug",e,n),info:n=>Ko("info",e,n),warn:n=>Ko("warn",e,n),error:n=>Ko("error",e,n)};return jl.set(e,r),r}var Ai=x("encryption"),$i="__encrypted__";function hf(e){return typeof e=="object"&&e!==null&&$i in e&&e[$i]===true}function Li(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[$i]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Ai.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(hf(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Ai.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Ai.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Mi=promisify(execFile),Sf=promisify(exec),it=x("encryption:macos-keyvault"),rn=class{static async isAvailable(){try{let{stdout:t}=await Sf("command -v security");return it.debug(`security binary found at: ${t.trim()}`),!0}catch{return it.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{it.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Mi("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return it.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return it.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{it.debug(`Storing secret: service=${t}, account=${r}`),await Mi("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),it.debug("security add-generic-password succeeded");}catch(o){let s=o;throw it.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return it.debug(`Deleting secret: service=${t}, account=${r}`),await Mi("security",["delete-generic-password","-a",r,"-s",t]),it.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return it.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function re(e){process.stdout.write(C.green(` \u2713 ${y(e)}
6
+ `));}function T(e){process.stderr.write(C.red(` \u2717 ${y(e)}
7
+ `));}function k(e){process.stdout.write(C.cyan(` \u2139 ${y(e)}
8
+ `));}function nn(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
9
+ `),process.stdout.write(` ${C.bold(i(e))}
10
+ `),process.stdout.write(` ${C.dim(s)}
11
11
  `);for(let a of r)process.stdout.write(` ${i(a)}
12
12
  `);process.stdout.write(`
13
- `);}function lr(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
- `);}function Ne(e){process.stdout.write(JSON.stringify(e)+`
15
- `);}function ze(e){process.stderr.write(JSON.stringify(e)+`
16
- `);}function X(e){return e instanceof Error?e.message:String(e)}function vt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var ki=promisify(execFile),Ai=promisify(exec),cf=[{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"}],Q=x("encryption:linux-keyvault");async function uf(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 df(e){let t=wa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var cr=class e{static async isAvailable(){try{let{stdout:t}=await Ai("command -v secret-tool");Q.debug(`secret-tool found at: ${t.trim()}`);}catch{return Q.debug("secret-tool binary not found in PATH"),false}try{return await ki("secret-tool",["lookup","service","__flow_connectivity_check__"]),Q.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(Q.debug(`Secret Service D-Bus not available: ${n}`),false):(Q.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of cf)try{return await Ai(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;Q.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 Q.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await df(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return Q.info(`Running: ${t.command}`),await uf("Installing secret-tool...",()=>Ai(t.command)),e.isAvailable()}catch{return Q.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{Q.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await ki("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return Q.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return Q.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){Q.debug(`Storing secret: service=${t}, account=${r}`),Q.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),Q.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),Q.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?(Q.debug("secret-tool store succeeded"),o()):(Q.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=>{Q.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return Q.debug(`Deleting secret: service=${t}, account=${r}`),await ki("secret-tool",["clear","service",t,"account",r]),Q.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return Q.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var ff=promisify(execFile),ut=x("encryption:windows-keyvault"),$i=1,gf=1,hf=2,yf=3;function Li(e,t){return `${e}:${t}`}var Mi=`
13
+ `);}function er(e){process.stdout.write(JSON.stringify(e,null,2)+`
14
+ `);}function Oe(e){process.stdout.write(JSON.stringify(e)+`
15
+ `);}function Ge(e){process.stderr.write(JSON.stringify(e)+`
16
+ `);}function V(e){return e instanceof Error?e.message:String(e)}function wt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var Ri=promisify(execFile),_i=promisify(exec),vf=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],z=x("encryption:linux-keyvault");async function Pf(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 Ef(e){let t=Pa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var tr=class e{static async isAvailable(){try{let{stdout:t}=await _i("command -v secret-tool");z.debug(`secret-tool found at: ${t.trim()}`);}catch{return z.debug("secret-tool binary not found in PATH"),false}try{return await Ri("secret-tool",["lookup","service","__flow_connectivity_check__"]),z.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(z.debug(`Secret Service D-Bus not available: ${n}`),false):(z.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of vf)try{return await _i(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;z.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return z.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await Ef(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return z.info(`Running: ${t.command}`),await Pf("Installing secret-tool...",()=>_i(t.command)),e.isAvailable()}catch{return z.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{z.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Ri("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return z.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return z.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){z.debug(`Storing secret: service=${t}, account=${r}`),z.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),z.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),z.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(z.debug("secret-tool store succeeded"),o()):(z.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{z.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return z.debug(`Deleting secret: service=${t}, account=${r}`),await Ri("secret-tool",["clear","service",t,"account",r]),z.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return z.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var kf=promisify(execFile),at=x("encryption:windows-keyvault"),Di=1,Af=1,$f=2,Lf=3;function Oi(e,t){return `${e}:${t}`}var Ui=`
17
17
  using System;
18
18
  using System.Runtime.InteropServices;
19
19
  using System.Text;
@@ -49,7 +49,7 @@ public class FlowCredManager {
49
49
 
50
50
  public static string Read(string target) {
51
51
  IntPtr credPtr;
52
- if (!CredRead(target, ${$i}, 0, out credPtr)) return "";
52
+ if (!CredRead(target, ${Di}, 0, out credPtr)) return "";
53
53
  try {
54
54
  var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
55
55
  if (cred.CredentialBlobSize <= 0) return "";
@@ -63,7 +63,7 @@ public class FlowCredManager {
63
63
  byte[] bytes = Encoding.UTF8.GetBytes(secret);
64
64
  IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
65
65
  IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
66
- int[] persistLevels = new int[] { ${hf}, ${yf}, ${gf} };
66
+ int[] persistLevels = new int[] { ${$f}, ${Lf}, ${Af} };
67
67
  int lastErr = 0;
68
68
  try {
69
69
  foreach (int persist in persistLevels) {
@@ -71,7 +71,7 @@ public class FlowCredManager {
71
71
  try {
72
72
  Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
73
73
  var cred = new CREDENTIAL();
74
- cred.Type = ${$i};
74
+ cred.Type = ${Di};
75
75
  cred.TargetName = targetPtr;
76
76
  cred.CredentialBlobSize = bytes.Length;
77
77
  cred.CredentialBlob = blobPtr;
@@ -89,162 +89,174 @@ public class FlowCredManager {
89
89
  }
90
90
 
91
91
  public static bool Delete(string target) {
92
- return CredDelete(target, ${$i}, 0);
92
+ return CredDelete(target, ${Di}, 0);
93
93
  }
94
94
  }
95
- `;function Kn(e){return e.replace(/'/g,"''")}function Fo(e){return ["-NoProfile","-NonInteractive","-Command",e]}function wf(e){return `Add-Type -TypeDefinition @'
96
- ${Mi}
95
+ `;function Fn(e){return e.replace(/'/g,"''")}function Vo(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Mf(e){return `Add-Type -TypeDefinition @'
96
+ ${Ui}
97
97
  '@
98
- [FlowCredManager]::Read('${Kn(e)}')`}function Sf(e,t,r){return `Add-Type -TypeDefinition @'
99
- ${Mi}
98
+ [FlowCredManager]::Read('${Fn(e)}')`}function Rf(e,t,r){return `Add-Type -TypeDefinition @'
99
+ ${Ui}
100
100
  '@
101
- [FlowCredManager]::Write('${Kn(e)}', '${Kn(t)}', '${Kn(r)}')`}function xf(e){return `Add-Type -TypeDefinition @'
102
- ${Mi}
101
+ [FlowCredManager]::Write('${Fn(e)}', '${Fn(t)}', '${Fn(r)}')`}function _f(e){return `Add-Type -TypeDefinition @'
102
+ ${Ui}
103
103
  '@
104
- [FlowCredManager]::Delete('${Kn(e)}')`}async function jo(e){return ff("powershell.exe",e)}var ln=class{static async isAvailable(){try{let{stdout:t}=await jo(Fo('Write-Output "ok"')),r=t.trim()==="ok";return ut.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
- `)[0]:"unknown error";return ut.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Li(t,r);ut.debug(`Looking up secret: target=${n}`);let o=wf(n),{stdout:s}=await jo(Fo(o)),i=s.trim();return ut.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
- `)[0]:"unknown error";return ut.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Li(t,r);ut.debug(`Storing secret: target=${o}`);let s=Sf(o,n,r),{stdout:i}=await jo(Fo(s)),a=i.trim();if(a.startsWith("OK:")){let c=a.split(":")[1];ut.debug(`CredWrite succeeded (persist=${c})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
107
- `)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw ut.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Li(t,r);ut.debug(`Deleting secret: target=${n}`);let o=xf(n),{stdout:s}=await jo(Fo(o)),i=s.trim()==="True";return ut.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
- `)[0]:"unknown error";return ut.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var If=32,bf="flow-plugins-cli-fallback",_i="flow-plugins-cli-fallback",vf={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function Pf(){let e=`${Te.hostname()}${Te.userInfo().username}`;return nn.scryptSync(e,bf,If)}function Ef(){let e=Pf(),t=new Bn(e),r=Ti(t);return new Ri({projectName:_i,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var Vo=null;function Ko(){return Vo||(Vo=Ef()),Vo}var Be=class{warned=false;async getSecret(t,r){return Ko().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=vf[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
104
+ [FlowCredManager]::Delete('${Fn(e)}')`}async function Jo(e){return kf("powershell.exe",e)}var on=class{static async isAvailable(){try{let{stdout:t}=await Jo(Vo('Write-Output "ok"')),r=t.trim()==="ok";return at.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
105
+ `)[0]:"unknown error";return at.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=Oi(t,r);at.debug(`Looking up secret: target=${n}`);let o=Mf(n),{stdout:s}=await Jo(Vo(o)),i=s.trim();return at.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
106
+ `)[0]:"unknown error";return at.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=Oi(t,r);at.debug(`Storing secret: target=${o}`);let s=Rf(o,n,r),{stdout:i}=await Jo(Vo(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];at.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 at.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Oi(t,r);at.debug(`Deleting secret: target=${n}`);let o=_f(n),{stdout:s}=await Jo(Vo(o)),i=s.trim()==="True";return at.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
108
+ `)[0]:"unknown error";return at.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var Df=32,Of="flow-plugins-cli-fallback",Bi="flow-plugins-cli-fallback",Uf={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function Nf(){let e=`${ve.hostname()}${ve.userInfo().username}`;return en.scryptSync(e,Of,Df)}function Bf(){let e=Nf(),t=new Un(e),r=Li(t);return new Ni({projectName:Bi,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var Go=null;function Ho(){return Go||(Go=Bf()),Go}var Ue=class{warned=false;async getSecret(t,r){return Ho().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Uf[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
109
109
  using a machine-derived key. For stronger security, ${o}.
110
- `),this.warned=true;}Ko().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ko(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Ko().path}static hasExistingData(){try{let t=new Ri({projectName:_i});return Se.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Ri({projectName:_i});Se.rmSync(t.path,{force:!0});}catch{}Vo=null;}};async function Di(){if(Be.hasExistingData())return new Be;switch(process.platform){case "darwin":return await sn.isAvailable()?new sn:new Be;case "linux":return await cr.isAvailable()?new cr:await cr.ensureInstalled()?new cr:new Be;case "win32":return await ln.isAvailable()?new ln:new Be;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Ml=x("config:credentials"),Vt="flow-plugins-cli",Oi="credentials",Ui="token-cache",Ni="user-info",Go=null;async function ur(){return Go||(Go=Di()),Go}function Wo(){Go=null;}async function ee(){let t=await(await ur()).getSecret(Vt,Oi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ht(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 Ml.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await ur()).setSecret(Vt,Oi,JSON.stringify(e));}async function Rl(){let e=await ur();await e.deleteSecret(Vt,Oi),await e.deleteSecret(Vt,Ui),await e.deleteSecret(Vt,Ni);}async function _l(){return (await ur()).getStoragePath()}async function Dl(e){await(await ur()).setSecret(Vt,Ui,JSON.stringify(e));}async function zo(){let t=await(await ur()).getSecret(Vt,Ui);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Xo(e){await(await ur()).setSecret(Vt,Ni,JSON.stringify(e));}async function qo(){let t=await(await ur()).getSecret(Vt,Ni);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function dr(){let e=await zo();return e?new Date(e.expiresAt)>new Date:false}function Pt(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/`,Ml.debug(`[customUrl] Service URLs overridden to base: ${t}`);}function cn(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}un();var Fi=x("api:auth");function $f(e){if(!Kt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ul={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 Lf(e){if(e instanceof HTTPError){let t=e.response.status;Fi.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&&Ul[r]?new Error(Ul[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?(Fi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Fi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function _r(e){let t=pr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");$f(e.tenant);let r;try{r=await qc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Lf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Ht(e),await Dl({accessToken:r.access_token,expiresAt:n});let o=cn(r.access_token);await Xo({sub:o.sub,name:o.name,email:o.email});}var Nl=x("lib:tokenProvider");async function Et(){if(await dr()){let n=await zo();if(n)return n.accessToken}Nl.debug("Token expired or missing, re-authenticating...");let t=await ee();if(!t)throw new Error("Not authenticated. Run: flow auth login");Be.clearFallbackFile(),Wo(),await _r(t);let r=await zo();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Nl.debug("Token refreshed successfully"),r.accessToken}un();var Yo=x("api:metrics");function Bl(){return pr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Fl(e,t,r){return qc.post(e,{json:t,headers:r})}async function Rf(e){let t=await qo();if(t)return t;let r=cn(e),n={sub:r.sub,name:r.name,email:r.email};return await Xo(n),n}async function b(e,t){let r=await Et(),n=await Rf(r),o=await ee();if(!Kt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:yi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Fl(Bl(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Yo.debug(`Metrics event sent: ${e}`);}catch(i){throw Yo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function jl(e,t,r){try{let n=r&&Kt.test(r)?r:"unknown",o={action:e,booster:yi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Fl(Bl(),o,{FlowTenant:n}),Yo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Yo.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var I={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var _f={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},dt={..._f};function Kl(e){let t=Date.now();dt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Dr(e){dt.currentStep=e,dt.stepStart=Date.now();}function q(){return {...dt}}function Jt(){return dt.sessionStart===0?0:Date.now()-dt.sessionStart}function Or(){return dt.stepStart===0?0:Date.now()-dt.stepStart}function Vl(){dt.tuiSessionStart=Date.now();}function Hl(){return dt.tuiSessionStart===0?0:Date.now()-dt.tuiSessionStart}var Df=3e3,Of=x("abandonment");async function Zo(e){let{currentStep:t,sessionStart:r}=q();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Jt()};try{await Promise.race([b(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Df))]);}catch(o){Of.warn(`Abandonment event failed: ${String(o)}`);}}function Jl(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Uf=3e3,Nf=x("session-end");async function Hn(e,t,r){let n=Hl(),s=[b(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Zo(e));try{await Jl(Promise.all(s).then(()=>{}),Uf);}catch(i){Nf.warn(`Session end event failed: ${String(i)}`);}}var Kf=2e3;function Wl(){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),Hn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Kf);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Gf=16;function zl({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,c)=>{if(c.backspace){let u=i.current.slice(0,-1);i.current=u,r(u);}else if(l&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let u=i.current+l;i.current=u,r(u);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Gf)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}var Xe=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Ur(){return we__default.join(Te__default.homedir(),".claude","settings.json")}function zn(){let e=Ur();if(!Se__default.existsSync(e))return {status:"missing"};let t=Se__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 Qo(e){let t=Ur();Se__default.mkdirSync(we__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function ql(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function Vi(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var Yf=3600,Nr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Zf(e){return qf.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Yf})}function es(e,t={}){let r=zn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Nr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Vi(r.settings):null,s=Zf(e),i=ql(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function ts(e){Qo(e.merged);}function Yl(){let e=zn();return e.status!=="ok"?false:Vi(e.settings)!==null}var Zl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Zl=e.version);}catch{}var le=Zl;function tg(){let e=vl();if(!Se__default.existsSync(e))return {};try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return {}}}var Hi=null;function rg(){return Hi===null&&(Hi=tg()),Hi}function mr(){return !!rg().ENABLE_EXPERIMENTAL_BETAS}function ig(){return ne.filter(e=>e.platforms[process.platform]?.status==="supported")}function ec(e){let t=ig();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var rs={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=we__default.join(Te__default.homedir(),".claude","settings.json"),r=Se__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(e.customUrl&&t.push("--custom-url",e.customUrl),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return [t]},onDemand:null,mode:"non-interactive"}},ag={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},ne=mr()?[rs,ag]:[rs];var dg=x("moduleState");function os(){let e=process.env.FLOW_HOME??we__default.join(Te__default.homedir(),".flow");return we__default.join(e,"modules.json")}var pg={retries:5,minTimeout:50};async function tc(e,t){Se__default.mkdirSync(we__default.dirname(e),{recursive:true});let r=await ug.lock(e+".lock",{realpath:false,retries:pg});try{return await t()}finally{await r();}}function rc(){let e=os();if(!Se__default.existsSync(e))return [];try{let t=JSON.parse(Se__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(dg.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),Se__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return Se__default.rmSync(e,{force:true}),[]}}function Br(){return rc()}function nc(e){let t=os();Se__default.mkdirSync(we__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Se__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function qe(e){return Br().find(t=>t.alias===e)??null}async function pt(e){let t=os();await tc(t,async()=>{let r=rc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,nc(r);});}async function Fr(){let e=os();Se__default.existsSync(e)||await tc(e,async()=>{Se__default.existsSync(e)||nc([]);});}var gg=promisify(execFile);function fr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Ct(e){let t=process.platform==="win32"?"where":"which";try{return await gg(t,[e]),!0}catch{return false}}function Gt(){return process.platform==="win32"?"npm.cmd":"npm"}var oc=promisify(execFile),dn=class{type="npm";async isAvailable(){return Ct("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=fr(t,"npm");if(!r)return null;try{let{stdout:n}=await oc(Gt(),["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=fr(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 oc(Gt(),["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 ss=promisify(execFile),xg=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,is=class{type="homebrew";async isAvailable(){return Ct("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=fr(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=fr(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 ss("brew",["tap",o.tap]),await ss("brew",["trust",o.tap])),await ss("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 ss("brew",["list","--versions",t]),n=r.trim().match(xg);return n?n[2]:null}catch{return null}}};var pn=promisify(execFile),ic=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function ac(){let e=process.env.FLOW_HOME??we__default.join(Te__default.homedir(),".flow");return we__default.join(e,"bin")}var as=class{type="curl";async isAvailable(){return Ct("curl")}async install(t){let r=Date.now(),n=fr(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=we__default.join(ac(),we__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await pn(n,["--version"]),s=o.match(ic);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=we__default.join(Te__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await pn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{Se__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return Se__default.chmodSync(s,448),await pn("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{Se__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=ac(),i=we__default.join(s,we__default.basename(n.binaryName)),a=false;try{if(Se__default.mkdirSync(s,{recursive:!0}),a=!0,await pn("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return Se__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}Se__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await pn(i,["--version"]),u=c.match(ic);l=u?u[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{Se__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=we__default.join(Te__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await pn("curl",["-L","--fail","-o",n,r]);let o=Se__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=Se__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{Se__default.unlinkSync(n);}catch{}}}};var ve=x("moduleInstaller");function At(e){switch(e){case "npm":return new dn;case "homebrew":return new is;case "curl":return new as}}async function Xn(e,t,r){try{await b(I.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){ve.warn(`Failed to emit install failed event: ${String(n)}`);}}async function hr(e,t,r,n){let o=Date.now(),s=e.platforms[process.platform];if(!s)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-o};if(s.status==="experimental"){ve.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let c={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Xn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(s.status!=="supported"){let c={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Xn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(!s.strategies.some(c=>c.type===r)){let c={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Xn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}let i=At(r),a=false;try{a=await i.isAvailable();}catch(c){ve.warn(`${r} availability check failed: ${String(c)}`);}if(!a){let c={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Xn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}try{await b(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,trigger:t});}catch(c){ve.warn(`Failed to emit install started event: ${String(c)}`);}let l;try{l=await i.install(e);}catch(c){let u=c instanceof Error?c.message:String(c);ve.warn(`${r} install threw: ${u}`),l={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-o};}if(l.success){await pt({alias:e.alias,name:e.name,installedVersion:l.version??null,installMethod:l.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await b(I.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:l.version??"unknown",duration_ms:l.durationMs,os:process.platform,trigger:t});}catch(d){ve.warn(`Failed to emit install completed event: ${String(d)}`);}let{pendingCmd:c,failed:u}=await Eg(e,t,n);return c?{...l,pendingInteractiveSetup:c}:u?{...l,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...l,configCheckFailed:true}:l}return await Xn(e,t,l.error??{code:"UNKNOWN",message:"unknown error"}),l}async function Eg(e,t,r){if(!e.postInstall)return {pendingCmd:null,failed:false};let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return {pendingCmd:null,failed:false};let o;if(typeof n=="function"){let i=await ee(),a={credentials:i?{clientId:i.clientId,clientSecret:i.clientSecret,tenant:i.tenant}:null,customUrl:r??null};try{o=n(a);}catch(l){return ve.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else o=n;if(o.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:o[0]??null,failed:false};let s=false;for(let i=0;i<o.length;i++){let a=o[i];if(a.length===0)continue;let l=spawnSync(a[0],a.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,ve.warn(`postInstall "${a.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&ve.warn(l.stderr);let c=o.slice(i+1).filter(u=>u.length>0);c.length>0&&ve.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function ls(e,t){let r=Date.now(),n=qe(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=At(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await b(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,trigger:"command"});}catch(a){ve.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);ve.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await pt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await b(I.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){ve.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await b(I.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){ve.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await b(I.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){ve.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var cs=x("flowAiObsSetup");async function qn(e){try{if(!await new dn().isAvailable().catch(()=>!1))return cs.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let n=await hr(rs,"onboarding","npm",e);return n.success?n.postInstallFailed||n.configCheckFailed?(cs.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(cs.warn(`flow-ai-obs install failed: ${n.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(t){return cs.warn(`installFlowAiObs threw: ${String(t)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}var lc=x("AuthSetup");function Cg(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 $t=["clientId","clientSecret","tenant"],kg={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function cc(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,c]=useState(false),[u,d]=useState("fields"),[m,p]=useState(null),[f,h]=useState(null),[g,w]=useState("confirm"),[v,O]=useState(""),_=useRef(""),[E,L]=useState(false),K=useRef(0),H=useRef(false),{setCredentials:de,setJustAuthenticated:C}=Xe(),N=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),G=()=>{d("fields"),p(null),t(A=>({...A,clientSecret:""})),n("clientSecret");},B=async()=>{H.current=true;let A={...N(),customUrl:f??void 0};try{await Ht(A);}catch(lt){a(lt instanceof Error?lt.message:"Failed to persist credentials"),G(),H.current=false;return}let{clientSecret:R,...V}=A;de(V),C(true),b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Jt(),interface:"tui"}).catch(()=>{}),await qn(f).catch(lt=>lc.warn(`installFlowAiObs threw unexpectedly: ${String(lt)}`)),Yn({starterKit:V.starterKit});},be=async A=>{H.current=true;let R={...N(),customUrl:f??void 0};try{ts(A),await Ht(R);}catch(Zr){a(Zr instanceof Error?Zr.message:"Failed to persist credentials"),G(),H.current=false;return}let{clientSecret:V,...lt}=R;de(lt),C(true),b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Jt(),interface:"tui"}).catch(()=>{}),await qn(f).catch(Zr=>lc.warn(`installFlowAiObs threw unexpectedly: ${String(Zr)}`)),Yn({starterKit:lt.starterKit});},jt=A=>{try{return es(N(),{allowOverwriteMalformed:A})}catch(R){return R instanceof Nr?(d("malformedConfirm"),null):(a(R instanceof Error?R.message:"Failed to read settings.json"),d("fields"),null)}};useInput((A,R)=>{if(!(l||H.current)){if(u==="preview"){R.return&&m?be(m):R.escape?B():A==="q"&&G();return}if(u==="malformedConfirm"){if(R.return){let V=jt(true);V&&(p(V),be(V));}else R.escape&&G();return}if(u==="customUrl"){if(g==="confirm")A==="y"||A==="Y"?w("input"):(A==="n"||A==="N"||R.return)&&U(null);else if(R.escape)_.current="",O(""),w("confirm");else if(R.return){let V=_.current.trim();V.length>0&&tn.test(V)?(L(false),U(V)):V.length>0&&L(true);}else R.backspace||R.delete?(_.current=_.current.slice(0,-1),O(_.current)):A&&!R.ctrl&&!R.meta&&(_.current=_.current+A,O(_.current),L(false));return}if(R.shift&&R.tab){let V=$t.indexOf(r);V>0&&n($t[V-1]);}else if(R.tab){let V=$t.indexOf(r);V<$t.length-1&&n($t[V+1]);}else if(R.return)if(r==="tenant")$();else {let V=$t.indexOf(r);n($t[V+1]);}}},{isActive:true});let $=()=>{let A={};for(let R of $t)e[R].trim()||(A[R]="This field is required");if(Object.keys(A).length>0){s(A);let R=$t.find(V=>A[V]);R&&n(R);return}w("confirm"),_.current="",O(""),L(false),d("customUrl");},U=async(A=f)=>{h(A),c(true),a(null),K.current+=1,A&&Pt(A);try{await _r(N());let R=jt(!1);R&&(p(R),d("preview"));}catch(R){let V=R instanceof Error?R.message:"Authentication failed";a(V),jl(I.CLI_AUTH_FAILED,{error_code:Cg(R),attempt:K.current},e.tenant.trim()).catch(()=>{}),t(lt=>({...lt,clientSecret:""})),d("fields");}finally{c(false);}},W=A=>R=>{t(V=>({...V,[A]:R})),o[A]&&s(V=>({...V,[A]:void 0}));};return u==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[On," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!l&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!l&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),E&&jsx(Text,{color:"red",children:rn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[On," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:m.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),m.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[On," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[On," \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:$t.map(A=>jsx(Box,{marginBottom:1,children:jsx(zl,{label:kg[A],value:e[A],onChange:W(A),masked:A==="clientSecret",isActive:r===A&&!l,error:o[A]})},A))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function mn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx($g,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",le]})})]})}var mc=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],te=mr()?mc:mc.slice(0,3);function Lg(e){return te.findIndex(t=>t.id===e)}function Wi(e,t,r){let n=Lg(r.activeTab);if(t.rightArrow||t.tab){let o=te[(n+1)%te.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=te[(n-1+te.length)%te.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:te[n]?.focus??"list"}]:[]}var hc={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function yc({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:te.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${hc[r]} (${e})`:hc[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Fe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Sc(){let e=S(i=>i.focus),t=Fe(i=>i.query),r=Fe(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var Dg=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...en[e]})),Og=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...gl[e]}));function xc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Dg.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"]})]}),Og.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function Ic({type:e}){let{label:t,color:r}=en[e];return jsx(Text,{color:r,children:t})}function Pc({origin:e}){return e===Un?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var ds=Bg.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(Ic,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Pc,{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 ",vt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function fn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Cc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(fn,{message:t});let n=Math.max(0,r-Math.floor(Ge/2)),o=Math.min(e.length,n+Ge);o===e.length&&(n=Math.max(0,o-Ge));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,c)=>jsx(ds,{item:l,isSelected:n+c===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function $c({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function Mc({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(fn,{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(Ge/2)),c=Math.min(n.length,l+Ge);c===n.length&&(l=Math.max(0,c-Ge));let u=n.slice(l,c),d=l,m=n.length-c;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),u.map(p=>p.kind==="header"?jsx($c,{label:p.label,pathHint:p.pathHint},p.key):jsx(ds,{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 Wg={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function zg({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Sc,{}),jsx(xc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Wg[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(Mc,{groups:n,emptyMessage:r}):jsx(Cc,{items:e,emptyMessage:r})]})}function Rc({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(zg,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Yg={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 ps(){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:[Yg[e],t?" | Ctrl+D: debug log":""]})})}function _c({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ms({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gu,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function ea(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Nc=20;function fs(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Nc),s="\u2588".repeat(o)+"\u2591".repeat(Nc-o),i=`${ea(e)} / ${ea(t)}`;return {bar:s,percent:n,label:i}}function gs({received:e,total:t}){let{bar:r,percent:n,label:o}=fs(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function hs({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 Ye({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,c)=>{c.upArrow?a(u=>u>0?u-1:u):c.downArrow?a(u=>u<t.length-1?u+1:u):c.return?n(t[i]):c.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,c)=>jsxs(Box,{children:[jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},c))})]})}var oa=Object.entries(Nn),Kc=[...oa.map(([,e])=>e.actionLabel),"Cancel"],Vc=Object.fromEntries(oa.map(([,e])=>[e.actionLabel,e.description]));function Hc(e){let t=oa.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var ph=x("provider.registry"),mh=3e4,ws=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()+mh}),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"&&ph.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 fh={user:"global",project:"project",local:"local"};function Ss(e){return e?fh[e]:"global"}var je=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},wr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};un();function ht(){return qc.create({prefix:pr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await Et();e.headers.set("Authorization",`Bearer ${t}`);let r=await ee();r?.tenant&&Kt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var hh=x("catalog.registry"),xs=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);hh.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Ph={retries:5,minTimeout:50};async function sa(e,t){mkdirSync(dirname(e),{recursive:true});let r=await ug.lock(e+".lock",{realpath:false,retries:Ph});try{return await t()}finally{await r();}}var Is=class{filePath;constructor(t){this.filePath=t??bl();}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 sa(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 sa(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await sa(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var Eh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function eo(e){if(!e||!Eh.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var Th=/^[^@]+@[^@]+$/;function hn(e){return Th.test(e)}function yn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Ch=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function kh(e){if(!Ch.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 wn(e,t){let r=yn(e);kh(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Ah=/^[\w./:@?&=+#%-]+$/;function bs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Ah.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var $h=x("catalog.flow-api"),vs=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await ht().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){eo(t);try{return await ht().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await ht().head("v1/plugins/catalog"),$h.debug("ping ok"),!0}catch{return false}}};var pe=new xs,zt=new Is;pe.register(new vs);var Qc=false;async function eu(){if(Qc)return;Qc=true;let e=await zt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ia(),Zc));for(let r of e)pe.register(new t(r.id,r.name,r.source));}var tu=2;async function Sr(){return pe.fetchAll()}async function ru(){return pe.fetchAllWithErrors()}async function xn(e){eo(e);try{return await ht().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function nu(e,t){eo(e);try{let r=await ht().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),c=[],u=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(u+=m.byteLength,i&&u>s*tu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*tu}`);c.push(m),i&&t?.(u,s);}return Buffer.concat(c)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function Ps(){try{let{profiles:e}=await ht().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function ou(e,t){let r=we.resolve(t);await Lt.mkdir(r,{recursive:true});let n=we.join(we.dirname(r),`${randomUUID()}.zip`);try{await Lt.writeFile(n,e),await Dh(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=we.resolve(r,o.fileName);if(process.platform==="win32"&&i.length>=260)throw new Error(`Path too long: "${i}" (${i.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.`);let a=we.normalize(r+we.sep);if(!i.startsWith(a)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(we.resolve(we.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Lt.unlink(n);}catch{}}}async function aa(e){await Lt.rm(e,{recursive:true,force:true});}async function xr(){let e=xl();await Lt.mkdir(we.dirname(e),{recursive:true});try{await Lt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await ug.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Nh(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:Z,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function au(){let e=$o();if(!Se__default.existsSync(e))return null;try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return null}}function Bh(){let e=au();if(e)return e;let t=Nh(),r=$o();return Se__default.mkdirSync(we__default.dirname(r),{recursive:true}),la(t),t}function la(e){let t=$o(),r=`${t}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function Fh(){let e=Lo(),t={};try{Se__default.existsSync(e)&&(t=JSON.parse(Se__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[Z])return;t[Z]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:Sl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,e);}function lu(e,t){yt(e.name),Fh();let r=xi(e.name);Se__default.mkdirSync(we__default.dirname(r),{recursive:true});try{Se__default.lstatSync(r),Se__default.rmSync(r,{recursive:!0,force:!0});}catch{}Se__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Bh();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),la(n));}function ca(e){yt(e);let t=xi(e);try{Se__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=au();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&la(r);}var Kh=x("mcpConfigReader"),Vh=500,Hh=512;function Jh(){return we__default.join(Te__default.homedir(),".claude.json")}function Gh(){return we__default.join(process.cwd(),".mcp.json")}function uu(e){if(!Se__default.existsSync(e))return null;try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return Kh.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function to(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ua(e){if(!to(e))return {};let t=e.mcpServers;return to(t)?t:{}}function da(e,t){return Object.keys(e).slice(0,Vh).map(n=>({name:y(n.slice(0,Hh)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function pu(){let e=[],t=Jh(),r=uu(t);if(to(r)){let a=r,l=ua(a);e.push(...da(l,"user"));let c=process.cwd();if(to(a.projects)){let u=a.projects[c];if(to(u)){let d=ua(u);e.push(...da(d,"local"));}}}let n=Gh(),o=uu(n),s=ua(o);e.push(...da(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var Ze=x("storage");async function zh(e,t,r){try{await b(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:q().interfaceType});}catch(n){Ze.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Xh(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:q().interfaceType}).catch(o=>Ze.warn(`Failed to send ${t} metrics: ${String(o)}`));}function ga(){return we__default.join(Te__default.homedir(),".claude","plugins","installed_plugins.json")}function qh(){return we__default.join(Te__default.homedir(),".claude","plugins")}function mu(e){let t=we__default.resolve(e),r=we__default.resolve(qh()),n=we__default.resolve(we__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+we__default.sep)||t===r,s=t.startsWith(n+we__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function fu(e="user"){return e==="local"?we__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?we__default.join(process.cwd(),".claude","settings.json"):we__default.join(Te__default.homedir(),".claude","settings.json")}function et(){let e=ga();if(!Se__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function ha(){let e=ga();try{let t=await Se__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Yh(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function gu(e,t){try{Se__default.mkdirSync(we__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,e);}catch(r){throw Yh(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Qe(e){gu(ga(),e);}function ro(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Zh(e,t){let r=we__default.join(e,".claude-plugin"),n=we__default.join(r,"plugin.json");if(Se__default.existsSync(n))try{return JSON.parse(Se__default.readFileSync(n,"utf-8"))}catch{return null}let o=we__default.join(r,"marketplace.json");if(Se__default.existsSync(o))try{let s=JSON.parse(Se__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ya(e="user"){let t=fu(e);if(!Se__default.existsSync(t))return {};try{return JSON.parse(Se__default.readFileSync(t,"utf-8"))}catch{return {}}}function hu(e,t="user"){gu(fu(t),e);}function Qh(e,t){let{name:r,marketplace:n}=ro(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>ro(i).name===r)[0],!o)throw Ze.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function ey(e,t){let{name:r,marketplace:n}=ro(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>ro(i).name===r)[0],o?{key:o,name:r}:null}function pa(e="user"){return ya(e).enabledPlugins??{}}function ma(e,t="user"){let r=ya(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,hu(r,t);}function no(e,t,r="user"){let n=ya(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},hu(n,r);}function ty(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function oe(){let e=et(),t=pa(),r=pa("project"),n=pa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=ro(c),p=u.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return ty(p).map(h=>{let g=Zh(h.installPath,d),v=(o[h.scope]??t)[c];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:v===false?"disabled":"enabled"}})}),i=pu(),a=new Set(s.map(c=>`${c.name}@${c.scope}`)),l=i.filter(c=>!a.has(`${c.name}@${c.scope}`));return [...s,...l]}async function oo(e,t){Ze.debug(`[${e}] Acquiring lock to uninstall`);let r=await xr();try{let n=et(),o=ey(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`);Ze.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),mu(l.installPath);let c=we__default.dirname(l.installPath);Ze.debug(`[${i}] Removing directory: ${c}`),Se__default.rmSync(c,{recursive:!0,force:!0});let u=a.filter(d=>d.scope!==t);if(u.length===0){let{[s]:d,...m}=n.plugins;Qe({...n,plugins:m}),ma(s,t),ca(i);}else n.plugins[s]=u,Qe(n),ma(s,t);}else {Ze.debug(`[${i}] Resolved key: ${s}`);for(let u of a){mu(u.installPath);let d=we__default.dirname(u.installPath);Ze.debug(`[${i}] Removing directory: ${d}`),Se__default.rmSync(d,{recursive:!0,force:!0}),ma(s,u.scope);}ca(i);let{[s]:l,...c}=n.plugins;Qe({...n,plugins:c});}await zh(i,a[0].origin??"internal",a[0].type??"skill"),Ze.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function so(e,t,r){Ze.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await xr();try{let o=et(),{key:s,name:i}=Qh(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";Ze.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),no(s,t==="enabled",l),Xh(i,t,c),Ze.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var ry=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ny=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function yt(e){if(!ry.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function oy(e){if(!ny.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 Ir=x("installer");function sy(e,t){let r=`${e}@${Z}`,o=et().plugins[r];if(o&&!t)throw new je(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function iy(e,t,r){r&&await aa(t);try{Ir.debug(`[${t}] Extracting archive...`),await ou(e,t);}catch(n){throw await aa(t),n}}function ay(e,t,r,n,o,s="claude-code",i){let a=et(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},c=a.plugins[e]??[];a.plugins[e]=[...c.filter(u=>u.scope!==n),l],Qe(a),no(e,true,n);}async function ly(e,t,r,n,o,s){try{await b(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:q().interfaceType});}catch(i){Ir.warn(`Failed to send install metrics: ${String(i)}`);}}async function cy(e,t,r,n){try{await b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:q().interfaceType});}catch(o){Ir.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function $e(e,t={}){let r=Date.now(),n=null;try{Ir.debug(`[${e}] Acquiring lock...`),n=await xr();let{pluginKey:o,alreadyInstalled:s}=sy(e,t.force);Ir.debug(`[${e}] Fetching manifest...`);let i=await xn(e);yt(i.name),oy(i.version),Ir.debug(`[${e}] Downloading archive...`);let a=await nu(e,t.onDownloadProgress),l=t.scope??"user",c=t.type??"skill",u=wl(i.name,i.version);await iy(a,u,!!s&&!!t.force),ay(o,u,i.version,l,"internal",t.providerId,c),lu(i,u);let d=Date.now()-r;Ir.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:u,duration_ms:d};return t.skipMetrics||await ly(i.name,i.version,d,Ss(l),"internal",c),m}catch(o){throw await cy(e,o,"internal",t.type??"skill"),Ir.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var uy=x("commands:helpers");async function ce(){let e=await ee();if(!e)return P("Not authenticated. Run: flow auth login"),false;e.customUrl&&Pt(e.customUrl);try{await Et();}catch(t){return uy.debug(`Token validation failed: ${String(t)}`),P("Session expired. Run: flow auth login"),false}return true}async function Mt(e){let t=wa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function yu(e){let t=wa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var In=x("claudeProxy"),va="claude ",wu="flow ",Sa=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},xa=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";}},dy=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,py=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,my=/^(flow|claude)\s+auth\s+login(\s|$)/,Su=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function xu(e){return Su.test(e.trim())}function fy(e){return Su.exec(e.trim())?.[2]??""}async function Iu(e){let t=fy(e),r=Date.now();In.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 Pa(n)?new Ia:n}}function gy(e){bu(e);let t=e.slice(va.length);if(!dy.test(t))throw new xa(e)}var Es=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Ia=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function bu(e){if(!e||!/^claude /.test(e))throw new Sa(e)}async function Pe(e){bu(e);let t=e.slice(va.length).split(/\s+/).filter(Boolean),r=hy(t);In.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 In.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 Pa(o)?new Es:o}}function hy(e){return e.length>=3?e[2]:e.join(" ")}function Pa(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function yy(e){return e.startsWith(wu)?va+e.slice(wu.length):e}function wy(e){return py.test(e)||my.test(e)}function Sy(e){let t=0;for(;t<e.length&&wy(e[t]);)t++;return e.slice(t)}var xy=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Iy(e,t){return !t||e.includes("--scope")||!xy.test(e)?e:`${e} --scope ${t}`}async function io(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Sy(r).map(i=>yy(i)).map(i=>Iy(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)gy(i);In.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Pe(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Pe(o[i]),s.exitCode!==0)return s;return s}async function Ts(e,t,r){let n=yn(e),o=t?.trim();if(!o&&(o=(await yu(`Plugin "${n}" could not be installed.
111
- If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=bs(o),r?.(),In.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"}`);In.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Pa(s)?new Es:s}}var Ty=6e4,br=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function Rt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Ty}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm$1(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new br("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new br(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new br(`Failed to clone ${e}: ${i}`,e,false,false)}}async function _t(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 Gr(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 ky(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Ay(e){return typeof e=="object"&&e!==null&&e.source==="url"}function $y(e){return typeof e=="object"&&e!==null&&e.source==="github"}function bn(e,t){let r=e.source;if(ky(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(Ay(r))return {cloneUrl:r.url,subPath:"."};if($y(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 tt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Dt=x("claude-code.adapter");function Ry(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=Lo();if(!Se__default.existsSync(s))return r;try{let i=JSON.parse(Se__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 Au(e,t){let r=e.catalogId?pe.getAdapter(e.catalogId):void 0,n=bn(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=Ry(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ii(s,e.name,"external"):a=join(Lr(i==="user"?"global":"project"),e.name);let l=null;try{yt(e.name),l=await Rt(n.cloneUrl,n.ref);let c=n.subPath==="."?l:join(l,n.subPath);if(Se__default.existsSync(a)&&Se__default.rmSync(a,{recursive:!0,force:!0}),Se__default.mkdirSync(dirname(a),{recursive:!0}),Se__default.cpSync(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await ha(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[u]??[];d.plugins[u]=[...p.filter(f=>f.scope!==i),m],Qe(d),no(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return Dt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await _t(l).catch(()=>{});}}async function Ea(e,t,r,n){try{await b(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Ss(n),version:"unknown",duration_ms:t,interface:q().interfaceType});}catch(o){Dt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Cu(e,t,r){try{await b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:q().interfaceType});}catch(n){Dt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var _y={async install(e,t){if(e.origin===Qr&&!e.installCommand&&!hn(e.name))return Au(e,t);if(e.origin===Qr&&e.installCommand){let r=e.type??"skill",n=await io(e.installCommand,t.scope);return n.exitCode===0?(await Ea(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Cu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(hn(e.name)){let r=e.type??"skill",n=wn(e.name,t.scope);Dt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Pe(n);if(o.exitCode===0)return await Ea(e.name,o.duration_ms,r,t.scope),{success:true};Dt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ts(e.name,t.marketplaceSource,()=>{});let s=await Pe(n);return s.exitCode===0?(await Ea(e.name,s.duration_ms,r,t.scope),{success:true}):(await Cu(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 $e(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Dt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await oo(e,t);},getInstallPath(e,t){return ""}};function ku(e){return {async install(t,r){if(t.origin===Qr&&!t.installCommand&&!hn(t.name))return Au(t,r);if(!t.installCommand)try{let o=await $e(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Dt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Dt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await io(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=et(),o=`${t}@${Z}`;if(n.plugins[o]){await oo(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 Dy(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!Se__default.existsSync(t))continue;let r=Se__default.readdirSync(t).filter(n=>n.endsWith(".md")&&Se__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Ta(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,Ta(r)]))}function $u(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(Ta(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Ta(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=$u(s,o):r[n]=o;}return r}async function Lu(e,t,r,n){let o=await ha(),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],Qe(o);}var Oy={async install(e,t){let r=t.scope??"user",n=e.catalogId?pe.getAdapter(e.catalogId):void 0,o=bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{yt(e.name),s=await Rt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Dy(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Ro(r);Se__default.mkdirSync(l,{recursive:!0});let c=tt(e.name);if(a.length===1)Se__default.copyFileSync(a[0],join(l,`${c}.md`));else for(let d of a){let m=tt(basename(d,".md"));Se__default.copyFileSync(d,join(l,`${c}--${m}.md`));}let u=a.length===1?join(l,`${c}.md`):l;return await Lu(e.name,r,u,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Dt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await _t(s).catch(()=>{});}},async uninstall(e,t){let r=Ro(t),n=tt(e);if(Se__default.existsSync(r))for(let a of Se__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))Se__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=et(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Qe({...s,plugins:l});}else Qe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Ro(t),`${tt(e)}.md`)}},Uy={async install(e,t){let r=t.scope??"user",n=e.catalogId?pe.getAdapter(e.catalogId):void 0,o=bn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{yt(e.name),s=await Rt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!Se__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(Se__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let c=l.hooks;if(!c||typeof c!="object"||Array.isArray(c))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let u=zn();if(u.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=u.status==="ok"?u.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=$u(m,c);return Qo({...d,hooks:p}),await Lu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Dt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await _t(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Cs=class{id="claude-code";name="Claude Code";async isAvailable(){return Gr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:_y,skill:ku("skill"),mcp:ku("mcp"),agent:Oy,hook:Uy}};function ks(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 By=new Set(["gh"]),Fy=ks(By,"use: gh copilot mcp remove <name>"),As=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Gr("gh",["--version"])?Gr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Fy}};var jy=new Set(["opencode"]),Ky=ks(jy,"use: opencode config remove mcp <name>");function Vy(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
112
- `)}function Mu(){return {async install(e,t){try{yt(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?pe.getAdapter(e.catalogId):void 0,n=bn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Rt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Mo(t.scope??"user"),a=join(s,".opencode","plugins");if(Se__default.existsSync(a)){let l=Se__default.readdirSync(a).filter(c=>c.endsWith(".js")||c.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};Se__default.mkdirSync(i,{recursive:!0}),Se__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);Se__default.existsSync(l)&&Se__default.rmSync(l,{recursive:!0,force:!0}),Se__default.mkdirSync(l,{recursive:!0}),Se__default.cpSync(s,l,{recursive:!0}),Se__default.mkdirSync(i,{recursive:!0}),Se__default.writeFileSync(join(i,`${e.name}.js`),Vy(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 _t(o).catch(()=>{});}},async uninstall(e,t){yt(e);let r=Mo(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);Se__default.existsSync(n)&&Se__default.rmSync(n,{force:true}),Se__default.existsSync(o)&&Se__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Mo(t),`${e}.js`)}}}var $s=class{id="opencode";name="OpenCode";async isAvailable(){return Gr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Ky,skill:Mu(),bundle:Mu()}};var Ot=new ws;Ot.register(new Cs);mr()&&(Ot.register(new As),Ot.register(new $s));function Ru({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,c]=useState([]),[u,d]=useState(void 0);useEffect(()=>{Ot.getAvailableProviders(t??"bundle").then(c).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(v=>v.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Hc(g);w?r(w,u):s(false);},[r,u]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(Ye,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(Ye,{itemName:`${e} \u2014 Choose scope`,actions:Kc,descriptions:Vc,onAction:f,onClose:h},"scope"):jsx(Ye,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Du({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),c=(t?.artifact.artifacts??[]).filter(f=>f.available),u=t!==void 0&&c.length===0,d=useMemo(()=>u?["Cancel"]:["Confirm Install","Cancel"],[u]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[c.length," artifact",c.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:c.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(Ye,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Rs({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function Nu({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=Rs({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(c)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(Ye,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?u():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function ju({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Rs({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(Ye,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var En=x("bundle:installer"),Ku=/already exists/i;async function Yy(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(xu(t)){let r=await Iu(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Ku.test(n))return;throw new Error(n)}}else {let r=await io(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Ku.test(n))return;throw new Error(n)}}}async function Zy(e,t){try{await b(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){En.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Qy(e,t,r){try{await b(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){En.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Vu(e,t,r,n){try{await b(I.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){En.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function ew(e,t,r,n,o){try{await b(I.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){En.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Os(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 Zy(i,o.length);let l=[],c=0,u=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){En.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await Vu(i,h,g,"unknown artifact type"),r?.({index:p+1,total:u,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Yy(f),c++,await Qy(i,h,g),r?.({index:p+1,total:u,artifact:f,success:!0});}catch(w){let v=w instanceof Error?w.message:String(w);En.error(`Failed to install artifact "${h}": ${v}`),l.push({name:h,type:g,reason:v}),await Vu(i,h,g,v),r?.({index:p+1,total:u,artifact:f,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await ew(i,c,m,s,d),{bundleTitle:e.title,total:n.length,installed:c,skipped:s,failed:m,failures:l}}function Wu({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Os(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",c=e.artifact.artifacts,u=c.filter(d=>d.available);s({bundleTitle:e.title,total:c.length,installed:0,skipped:c.length-u.length,failed:u.length,failures:u.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(Gu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Gu,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var me=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:oe()})}));function zu({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,c=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),c&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",vt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function Xu({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:c,stored:u}=e,d=c.removable!==false,m=u?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",u?.lastUpdated?` \xB7 Updated ${vt(u.lastUpdated)}`:""]})}),u&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function qu(e){return e.adapter.removable!==false?4:2}function Yu({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((c,u)=>{if(u.escape){n();return}if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(i.length-1,d+1));return}u.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((c,u)=>jsxs(Box,{children:[jsx(Text,{color:u===a?"cyan":void 0,children:u===a?"\u203A ":" "}),jsx(Text,{bold:u===a,color:c.danger?"yellow":void 0,dimColor:u!==a,children:c.label})]},c.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Qu({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 ed({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(E=>r.has(`${E.name}@${o}`)),i=t.filter(E=>!r.has(`${E.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((E,L)=>{if(L.escape){n();return}if(L.return){d(a[l]??null);return}if(L.upArrow){c(K=>Math.max(0,K-1));return}L.downArrow&&c(K=>Math.min(a.length-1,K+1));},{isActive:u===null}),u!==null)return jsx(Yu,{item:u,adapterName:e.adapter.name,isInstalled:r.has(`${u.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Ge/2)),p=Math.min(a.length,m+Ge);p===a.length&&(m=Math.max(0,p-Ge));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,v=p>s.length,O=f.filter(E=>r.has(`${E.name}@${o}`)),_=f.filter(E=>!r.has(`${E.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:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),O.map(E=>jsx(Qu,{item:E,isSelected:a.indexOf(E)===l,isInstalled:true},E.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(E=>jsx(Qu,{item:E,isSelected:a.indexOf(E)===l,isInstalled:false},E.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ia();var aw=/^https?:\/\/.+/;function lw(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function cw(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function od(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[c,u]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),u(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!aw.test(g)){u("URL must start with http:// or https://");return}u(null),o("adding");let v=randomUUID(),O=new Sn(v,w,g);try{await O.fetchItems(),await zt.add({id:v,name:w,source:g}),pe.register(new Sn(v,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(_){let E=lw(_)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":cw(_)?_.message:_ instanceof Error?`Could not reach catalog URL: ${_.message}`:"Failed to validate catalog URL";t(E,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function sd(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await zt.remove(o),pe.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function ad(){let e=S($=>$.focus),t=S($=>$.setFocus),r=S($=>$.showNotification),n=me($=>$.installedItems),[o,s]=useState(()=>pe.listAdapters().map($=>({adapter:$,stored:null}))),[i,a]=useState(0),[l,c]=useState("list"),[u,d]=useState(0),[m,p]=useState(null),[f,h]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&h("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let $=pe.listAdapters(),U=await zt.read(),W=new Map(U.map(A=>[A.id,A]));s($.map(A=>({adapter:A,stored:W.get(A.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let $=g.current[i-1];if(!$)return;let U=false;return p({items:[],loading:true,error:null}),$.adapter.fetchItems().then(W=>{U||p({items:W,loading:false,error:null});}).catch(W=>{U||p({items:[],loading:false,error:W instanceof Error?W.message:"Failed to load catalog"});}),()=>{U=true;}},[i]);let v=od(w),O=useCallback(()=>{w(),a(0),c("list"),p(null),h("main");},[w]),{handleRemove:_}=sd(O),E=useCallback(async $=>{h("removing"),await _($);},[_]),L=useCallback(async $=>{try{let U=await $.adapter.fetchItems();if(p({items:U,loading:!1,error:null}),$.stored){let W=new Date().toISOString();await zt.updateField($.stored.id,{lastUpdated:W}),w();}r("Marketplace updated","success");}catch(U){r(U instanceof Error?U.message:"Update failed","error");}},[w,r]),K=useCallback(async $=>{if(!$.stored)return;let U=$.stored.autoUpdate!==false;await zt.updateField($.stored.id,{autoUpdate:!U}),w();},[w]),H=useCallback(()=>h("browse"),[]),de=useCallback($=>{let U=o[i-1];if(!U)return;let W=U.adapter.removable!==false;[H,()=>{L(U);},...W?[()=>{K(U);},()=>{E(U.adapter.id);}]:[]][$]?.();},[o,i,H,L,K,E]),C=useCallback(()=>h("main"),[]),N=useCallback(()=>{let $=o[i-1];$&&L($);},[o,i,L]),G=useCallback(()=>{let $=o[i-1];$&&K($);},[o,i,K]),B=useCallback(()=>{let $=o[i-1];$&&E($.adapter.id);},[o,i,E]);if(useInput(($,U)=>{if(U.upArrow){a(W=>Math.max(0,W-1));return}if(U.downArrow){a(W=>Math.min(o.length,W+1));return}(U.return||U.tab)&&(i===0?v.startAdd():(c("detail"),d(0)));},{isActive:f==="main"&&v.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput(($,U)=>{if(U.escape||U.tab){c("list");return}if(U.upArrow){d(W=>Math.max(0,W-1));return}if(U.downArrow){let W=o[i-1],A=W?qu(W)-1:0;d(R=>Math.min(R+1,A));return}U.return&&de(u);},{isActive:f==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(v.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let $=o[i-1];if(!$)return jsx(Box,{});let U=$.adapter.id??"default",W=new Set(n.filter(A=>A.marketplace===$.adapter.name).map(A=>`${A.name}@${U}`));return jsx(ed,{entry:$,items:m?.items??[],installedKeys:W,onBack:C})}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 be=o[i-1]??null,jt=be?n.filter($=>$.marketplace===be.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(zu,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&be?jsx(Xu,{entry:be,detailData:m,installedCount:jt,focusPanel:l,actionIndex:u,onBrowse:H,onUpdate:N,onToggleAutoUpdate:G,onRemove:B}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:be?"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 ld(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=te.findIndex(i=>i.id===r.activeTab),s=te[(o-1+te.length)%te.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=te.findIndex(i=>i.id===r.activeTab),s=te[(o+1)%te.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=te.findIndex(i=>i.id===r.activeTab),s=te[(o+1)%te.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==="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 cd(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function ud(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 fw=new Set(te.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:c}=Fe.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+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 dd({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Fe(h=>h.query),a=Fe(h=>h.setQuery),l=Fe(h=>h.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Fe.getState();g(h.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();yo(Wi(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();yo(Wi("",g,{activeTab:w}));},{isActive:fw.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();yo(ld(h,g,{activeTab:w,selectedIndex:v},c.current));},{isActive:t==="list"}),useInput((h,g)=>{yo(cd(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=ud(h,g,Fe.getState().query),v=w.queryUpdate;if(yo(w.actions),v==="reset")l(),d("");else if(v!==null){let{query:O,cursorPosition:_,setCursorPosition:E}=Fe.getState();if("backspace"in v)_>0&&(a(O.slice(0,_-1)+O.slice(_)),E(_-1));else if("append"in v)a(O.slice(0,_)+v.append+O.slice(_)),E(_+v.append.length);else if("cursorMove"in v){let L=_+v.cursorMove;L>=0&&L<=O.length&&E(L);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();h===0?g(0):w>=h&&g(h-1);},[]),f=useCallback(h=>{if(!u)return c.current=h.length,h;let g=u.toLowerCase(),w=h.filter(v=>v.name.toLowerCase().includes(g)||v.description?.toLowerCase().includes(g));return c.current=w.length,w},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function md(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Xe(a=>a.justAuthenticated),o=Xe(a=>a.credentials),s=Xe(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 Re(e,t,r=false){return r?true:!La.valid(e)||!La.valid(t)?false:La.gt(t,e)}var Yt=x("updater");async function gw(e,t,r,n,o,s){try{await b(I.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:q().interfaceType});}catch(i){Yt.warn(`Failed to send update metrics: ${String(i)}`);}}function hw(e){let t=et(),r=`${e}@${Z}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Fs(e,t={}){let r=Date.now(),n=null;try{Yt.debug(`[${e}] Acquiring lock...`),n=await xr();let o=hw(e);if(!o)throw Yt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Yt.debug(`[${e}] Fetching manifest...`);let c=(await xn(e)).version;if(!i||!Re(i,c,t.force))throw Yt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new wr(e,i??"unknown");Yt.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await $e(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await gw(u.name,i,u.version,d,s.origin??"internal",s.type??"skill"),Yt.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){Yt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await xr();let d=et(),m=`${e}@${Z}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Qe(d),Yt.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var js=x("dispatcher");async function yw(e,t,r,n,o){let s=yn(e);return js.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Ts(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),js.debug(`[${e}] Retrying install after marketplace add`),Pe(t)}async function fd(e,t,r,n){let o=wn(e,n),s=yn(e);r?.onStatus?.(`Installing ${s}...`),js.debug(`[${e}] Attempting install: ${o}`);let i=await Pe(o);if(i.exitCode===0)return i;js.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return yw(e,o,a,t,r)}async function gd(e,t,r){let n=e.type??"bundle",o=await Ot.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 hd(){let e=me(i=>i.installedItems),t=me(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await gd(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=oe().find(p=>p.name===i),c=l?.providerId??"claude-code",u=Ot.getAdapter(c);if(!u)throw new Error(`Provider "${c}" not found`);let d=l?.type??"bundle",m=u.installers[d];if(!m)throw new Error(`Provider "${c}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let c=e.find(u=>u.name===i)?.status==="enabled"?"disabled":"enabled";await so(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Fs(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var Vs=x("mcp");function wo(e,t){e.silent?ze({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):P(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function wd(e,t){e.silent?Ne({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ae(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&T(t.stdout));}function ww(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 Ma(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 Sd(e,t,r){if(!await ce())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return wo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Vs.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=ww(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Mt(`Install external MCP "${s}"?
110
+ `),this.warned=true;}Ho().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ho(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Ho().path}static hasExistingData(){try{let t=new Ni({projectName:Bi});return me.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Ni({projectName:Bi});me.rmSync(t.path,{force:!0});}catch{}Go=null;}};async function Fi(){if(Ue.hasExistingData())return new Ue;switch(process.platform){case "darwin":return await rn.isAvailable()?new rn:new Ue;case "linux":return await tr.isAvailable()?new tr:await tr.ensureInstalled()?new tr:new Ue;case "win32":return await on.isAvailable()?new on:new Ue;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Gl=x("config:credentials"),Ot="flow-plugins-cli",ji="credentials",Ki="token-cache",Vi="user-info",Xo=null;async function rr(){return Xo||(Xo=Fi()),Xo}function qo(){Xo=null;}async function X(){let t=await(await rr()).getSecret(Ot,ji);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Ut(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 Gl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await rr()).setSecret(Ot,ji,JSON.stringify(e));}async function Wl(){let e=await rr();await e.deleteSecret(Ot,ji),await e.deleteSecret(Ot,Ki),await e.deleteSecret(Ot,Vi);}async function zl(){return (await rr()).getStoragePath()}async function Xl(e){await(await rr()).setSecret(Ot,Ki,JSON.stringify(e));}async function Yo(){let t=await(await rr()).getSecret(Ot,Ki);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Zo(e){await(await rr()).setSecret(Ot,Vi,JSON.stringify(e));}async function Qo(){let t=await(await rr()).getSecret(Ot,Vi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function nr(){let e=await Yo();return e?new Date(e.expiresAt)>new Date:false}function St(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/`,Gl.debug(`[customUrl] Service URLs overridden to base: ${t}`);}function sn(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")}}an();var Hi=x("api:auth");function Jf(e){if(!Dt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Yl={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 Hf(e){if(e instanceof HTTPError){let t=e.response.status;Hi.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&&Yl[r]?new Error(Yl[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?(Hi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Hi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function sr(e){let t=or("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Jf(e.tenant);let r;try{r=await fu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Hf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Ut(e),await Xl({accessToken:r.access_token,expiresAt:n});let o=sn(r.access_token);await Zo({sub:o.sub,name:o.name,email:o.email});}var Zl=x("lib:tokenProvider");async function xt(){if(await nr()){let n=await Yo();if(n)return n.accessToken}Zl.debug("Token expired or missing, re-authenticating...");let t=await X();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ue.clearFallbackFile(),qo(),await sr(t);let r=await Yo();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Zl.debug("Token refreshed successfully"),r.accessToken}an();var es=x("api:metrics");function Ql(){return or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ec(e,t,r){return fu.post(e,{json:t,headers:r})}async function Wf(e){let t=await Qo();if(t)return t;let r=sn(e),n={sub:r.sub,name:r.name,email:r.email};return await Zo(n),n}async function E(e,t){let r=await xt(),n=await Wf(r),o=await X();if(!Dt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:bi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await ec(Ql(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),es.debug(`Metrics event sent: ${e}`);}catch(i){throw es.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function tc(e,t,r){try{let n=r&&Dt.test(r)?r:"unknown",o={action:e,booster:bi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ec(Ql(),o,{FlowTenant:n}),es.debug(`Anonymous metrics event sent: ${e}`);}catch(n){es.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var v={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var zf={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},lt={...zf};function rc(e){let t=Date.now();lt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function $r(e){lt.currentStep=e,lt.stepStart=Date.now();}function J(){return {...lt}}function ir(){return lt.sessionStart===0?0:Date.now()-lt.sessionStart}function Lr(){return lt.stepStart===0?0:Date.now()-lt.stepStart}function nc(){lt.tuiSessionStart=Date.now();}function oc(){return lt.tuiSessionStart===0?0:Date.now()-lt.tuiSessionStart}var Xf=3e3,qf=x("abandonment");async function ts(e){let{currentStep:t,sessionStart:r}=J();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:ir()};try{await Promise.race([E(v.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Xf))]);}catch(o){qf.warn(`Abandonment event failed: ${String(o)}`);}}function sc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var Yf=3e3,Zf=x("session-end");async function Kn(e,t,r){let n=oc(),s=[E(v.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(ts(e));try{await sc(Promise.all(s).then(()=>{}),Yf);}catch(i){Zf.warn(`Session end event failed: ${String(i)}`);}}var rg=2e3;function ac(){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),Kn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},rg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var ig=16;function lc({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(ig)}),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]})})]})}function cc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Er," \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)"}),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"})]})]})}function uc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[Er," \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 We=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function ar(){return pe__default.join(ve__default.homedir(),".claude","settings.json")}function Xn(){let e=ar();if(!me__default.existsSync(e))return {status:"missing"};let t=me__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 ns(e){let t=ar();me__default.mkdirSync(pe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function pc(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function Xi(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var dg=3600,_r=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function qn(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(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function pg(e){return ug.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:dg})}function os(e,t={}){let r=Xn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new _r;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Xi(r.settings):null,s=t.jwtOverride??pg(e),i=pc(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function ss(e){ns(e.merged);}function mc(){let e=Xn();return e.status!=="ok"?false:Xi(e.settings)!==null}function mg(){let e=Ul();if(!me__default.existsSync(e))return {};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {}}}var qi=null;function fg(){return qi===null&&(qi=mg()),qi}function lr(){return !!fg().ENABLE_EXPERIMENTAL_BETAS}function wg(){return Z.filter(e=>e.platforms[process.platform]?.status==="supported")}function gc(e){let t=wg();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var is={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=pe__default.join(ve__default.homedir(),".claude","settings.json"),r=me__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??Al),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return [t]},onDemand:null,mode:"non-interactive"}},Sg={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},Z=lr()?[is,Sg]:[is];var vg=x("moduleState");function ls(){let e=process.env.FLOW_HOME??pe__default.join(ve__default.homedir(),".flow");return pe__default.join(e,"modules.json")}var Pg={retries:5,minTimeout:50};async function hc(e,t){me__default.mkdirSync(pe__default.dirname(e),{recursive:true});let r=await bg.lock(e+".lock",{realpath:false,retries:Pg});try{return await t()}finally{await r();}}function yc(){let e=ls();if(!me__default.existsSync(e))return [];try{let t=JSON.parse(me__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(vg.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),me__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return me__default.rmSync(e,{force:true}),[]}}function Dr(){return yc()}function wc(e){let t=ls();me__default.mkdirSync(pe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};me__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function ze(e){return Dr().find(t=>t.alias===e)??null}async function ct(e){let t=ls();await hc(t,async()=>{let r=yc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,wc(r);});}async function Or(){let e=ls();me__default.existsSync(e)||await hc(e,async()=>{me__default.existsSync(e)||wc([]);});}var Cg=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 Cg(t,[e]),!0}catch{return false}}function Nt(){return process.platform==="win32"?"npm.cmd":"npm"}var Sc=promisify(execFile),cn=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 Sc(Nt(),["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 Sc(Nt(),["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 cs=promisify(execFile),Mg=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,us=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 cs("brew",["tap",o.tap]),await cs("brew",["trust",o.tap])),await cs("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 cs("brew",["list","--versions",t]),n=r.trim().match(Mg);return n?n[2]:null}catch{return null}}};var un=promisify(execFile),Ic=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function bc(){let e=process.env.FLOW_HOME??pe__default.join(ve__default.homedir(),".flow");return pe__default.join(e,"bin")}var ds=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=pe__default.join(bc(),pe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await un(n,["--version"]),s=o.match(Ic);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=pe__default.join(ve__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await un("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{me__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return me__default.chmodSync(s,448),await un("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{me__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=bc(),i=pe__default.join(s,pe__default.basename(n.binaryName)),a=false;try{if(me__default.mkdirSync(s,{recursive:!0}),a=!0,await un("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return me__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}me__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await un(i,["--version"]),c=u.match(Ic);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{me__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=pe__default.join(ve__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await un("curl",["-L","--fail","-o",n,r]);let o=me__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=me__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{me__default.unlinkSync(n);}catch{}}}};var vc="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(vc=e.version);}catch{}var se=vc;var ye=x("moduleInstaller");function Pt(e){switch(e){case "npm":return new cn;case "homebrew":return new us;case "curl":return new ds}}async function Yn(e,t,r){try{await E(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){ye.warn(`Failed to emit install failed event: ${String(n)}`);}}async function dr(e,t,r,n,o){let s=Date.now(),i=e.platforms[process.platform];if(!i)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(i.status==="experimental"){ye.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let c={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Yn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}if(i.status!=="supported"){let c={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Yn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}if(!i.strategies.some(c=>c.type===r)){let c={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Yn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}let a=Pt(r),l=false;try{l=await a.isAvailable();}catch(c){ye.warn(`${r} availability check failed: ${String(c)}`);}if(!l){let c={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Yn(e,t,c),{success:false,error:c,durationMs:Date.now()-s}}try{await E(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:se,trigger:t});}catch(c){ye.warn(`Failed to emit install started event: ${String(c)}`);}let u;try{u=o?.forceLatest?await a.update(e,"unknown"):await a.install(e);}catch(c){let d=c instanceof Error?c.message:String(c);ye.warn(`${r} install threw: ${d}`),u={success:false,error:{code:"INSTALL_THREW",message:d},durationMs:Date.now()-s};}if(u.success){await ct({alias:e.alias,name:e.name,installedVersion:u.version??null,installMethod:u.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await E(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:u.version??"unknown",duration_ms:u.durationMs,os:process.platform,trigger:t});}catch(m){ye.warn(`Failed to emit install completed event: ${String(m)}`);}let{pendingCmd:c,failed:d}=await Bg(e,t,n);return c?{...u,pendingInteractiveSetup:c}:d?{...u,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...u,configCheckFailed:true}:u}return await Yn(e,t,u.error??{code:"UNKNOWN",message:"unknown error"}),u}async function Bg(e,t,r){if(!e.postInstall)return {pendingCmd:null,failed:false};let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return {pendingCmd:null,failed:false};let o;if(typeof n=="function"){let i=await X(),a={credentials:i?{clientId:i.clientId,clientSecret:i.clientSecret,tenant:i.tenant}:null,customUrl:r??null};try{o=n(a);}catch(l){return ye.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else o=n;if(o.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:o[0]??null,failed:false};let s=false;for(let i=0;i<o.length;i++){let a=o[i];if(a.length===0)continue;let l=spawnSync(a[0],a.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,ye.warn(`postInstall "${a.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&ye.warn(l.stderr);let u=o.slice(i+1).filter(c=>c.length>0);u.length>0&&ye.debug(`continuing with remaining postInstall steps: ${u.map(c=>c.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function ps(e,t){let r=Date.now(),n=ze(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Pt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await E(v.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:se,trigger:"command"});}catch(a){ye.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);ye.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await ct({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await E(v.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){ye.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await E(v.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){ye.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await E(v.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){ye.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var ms=x("flowAiObsSetup");async function Zn(e){try{if(!await new cn().isAvailable().catch(()=>!1))return ms.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let n=await dr(is,"onboarding","npm",e,{forceLatest:!0});return n.success?n.postInstallFailed||n.configCheckFailed?(ms.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ms.warn(`flow-ai-obs install failed: ${n.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(t){return ms.warn(`installFlowAiObs threw: ${String(t)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}function Pc(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 Ec=x("useAuthSetup");function Tc(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),[o,s]=useState(),[i,a]=useState(null),[l,u]=useState(false),[c,d]=useState("fields"),[m,p]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:w}=We(),I=()=>{d("fields"),p(null),t(""),r.current=null,n.current=null;},R=()=>{E(v.CLI_SESSION_STARTED,{cli_version:se,os:process.platform,node_version:process.version,duration_ms:ir(),interface:"tui"}).catch(()=>{});},B=async()=>{g.current=true;let b={...r.current,customUrl:n.current??void 0};try{await Ut(b);}catch(D){a(D instanceof Error?D.message:"Failed to persist credentials"),I(),g.current=false;return}let{clientSecret:$,...F}=b;h(F),w(true),R(),await Zn(n.current).catch(D=>Ec.warn(`installFlowAiObs threw unexpectedly: ${String(D)}`)),Qn({starterKit:F.starterKit});},P=async b=>{g.current=true;let $={...r.current,customUrl:n.current??void 0};try{ss(b),await Ut($);}catch(ue){a(ue instanceof Error?ue.message:"Failed to persist credentials"),I(),g.current=false;return}let{clientSecret:F,...D}=$;h(D),w(true),R(),await Zn(n.current).catch(ue=>Ec.warn(`installFlowAiObs threw unexpectedly: ${String(ue)}`)),Qn({starterKit:D.starterKit});},A=b=>{try{return os(r.current,{allowOverwriteMalformed:b,jwtOverride:e.trim()})}catch($){return $ instanceof _r?(d("malformedConfirm"),null):(a($ instanceof Error?$.message:"Failed to read settings.json"),d("fields"),null)}};return {jwtValue:e,jwtError:o,authError:i,isSubmitting:l,step:c,plan:m,isCommittingRef:g,setJwtValue:t,setJwtError:s,cancelToFields:I,handleSubmit:async()=>{let b=e.trim();if(!b){s("This field is required");return}let $;try{$=qn(b);}catch(F){s(F instanceof Error?F.message:"Invalid JWT");return}s(void 0),r.current=$,d("customUrl");},handleAuthenticate:async b=>{n.current=b,b&&St(b),u(true),a(null),f.current+=1;try{await sr(r.current);let $=A(!1);$&&(p($),d("preview"));}catch($){let F=$ instanceof Error?$.message:"Authentication failed";a(F),tc(v.CLI_AUTH_FAILED,{error_code:Pc($),attempt:f.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,d("fields");}finally{u(false);}},commitAndProceed:P,skipJwtAndProceed:B,planPersistOverwrite:()=>{let b=A(true);b&&(p(b),P(b));}}}function Cc(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,handleAuthenticate:d,commitAndProceed:m,skipJwtAndProceed:p,planPersistOverwrite:f}=Tc(),[g,h]=useState("confirm"),[w,I]=useState(""),R=useRef(""),[B,P]=useState(false);return useEffect(()=>{o==="customUrl"&&(h("confirm"),R.current="",I(""),P(false));},[o]),useInput((A,_)=>{if(!(n||i.current)){if(o==="preview"){_.return&&s?m(s):_.escape?p():A==="q"&&u();return}if(o==="malformedConfirm"){_.return?f():_.escape&&u();return}if(o==="customUrl"){if(g==="confirm")A==="y"||A==="Y"?h("input"):(A==="n"||A==="N"||_.return)&&d(null);else if(_.escape)R.current="",I(""),h("confirm");else if(_.return){let j=R.current.trim();j.length>0&&Zr.test(j)?(P(false),d(j)):j.length>0&&P(true);}else _.backspace||_.delete?(R.current=R.current.slice(0,-1),I(R.current)):A&&!_.ctrl&&!_.meta&&(R.current=R.current+A,I(R.current),P(false));return}_.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:[Er," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="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:w}),jsx(Text,{color:"cyan",children:"\u2588"})]}),B&&jsx(Text,{color:"red",children:Qr}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="preview"&&s?jsx(cc,{plan:s}):o==="malformedConfirm"?jsx(uc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[Er," \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(lc,{label:"JWT",value:e,onChange:A=>{a(A),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function pn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Jg,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",se]})})]})}var Lc=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],q=lr()?Lc:Lc.slice(0,3);function Hg(e){return q.findIndex(t=>t.id===e)}function Qi(e,t,r){let n=Hg(r.activeTab);if(t.rightArrow||t.tab){let o=q[(n+1)%q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=q[(n-1+q.length)%q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:q[n]?.focus??"list"}]:[]}var _c={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Dc({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:q.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${_c[r]} (${e})`:_c[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ne=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Uc(){let e=S(i=>i.focus),t=Ne(i=>i.query),r=Ne(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var Xg=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Yr[e]})),qg=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...kl[e]}));function Nc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Xg.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"]})]}),qg.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function Bc({type:e}){let{label:t,color:r}=Yr[e];return jsx(Text,{color:r,children:t})}function Kc({origin:e}){return e===Dn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var hs=Qg.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(Bc,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Kc,{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 ",wt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function mn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Hc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(mn,{message:t});let n=Math.max(0,r-Math.floor(Je/2)),o=Math.min(e.length,n+Je);o===e.length&&(n=Math.max(0,o-Je));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(hs,{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 zc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function qc({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(mn,{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(Je/2)),u=Math.min(n.length,l+Je);u===n.length&&(l=Math.max(0,u-Je));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(zc,{label:p.label,pathHint:p.pathHint},p.key):jsx(hs,{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 ah={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function lh({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Uc,{}),jsx(Nc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:ah[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(qc,{groups:n,emptyMessage:r}):jsx(Hc,{items:e,emptyMessage:r})]})}function Yc({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(lh,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var dh={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 ys(){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:[dh[e],t?" | Ctrl+D: debug log":""]})})}function Zc({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function ws({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ud,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function ia(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var ru=20;function Ss(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*ru),s="\u2588".repeat(o)+"\u2591".repeat(ru-o),i=`${ia(e)} / ${ia(t)}`;return {bar:s,percent:n,label:i}}function xs({received:e,total:t}){let{bar:r,percent:n,label:o}=Ss(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Is({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 Xe({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}var ua=Object.entries(On),iu=[...ua.map(([,e])=>e.actionLabel),"Cancel"],au=Object.fromEntries(ua.map(([,e])=>[e.actionLabel,e.description]));function lu(e){let t=ua.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var Th=x("provider.registry"),Ch=3e4,vs=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()+Ch}),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"&&Th.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 kh={user:"global",project:"project",local:"local"};function Ps(e){return e?kh[e]:"global"}var Be=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},mr=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};an();function pt(){return fu.create({prefix:or("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await xt();e.headers.set("Authorization",`Bearer ${t}`);let r=await X();r?.tenant&&Dt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var $h=x("catalog.registry"),Es=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);$h.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Nh={retries:5,minTimeout:50};async function da(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bg.lock(e+".lock",{realpath:false,retries:Nh});try{return await t()}finally{await r();}}var Ts=class{filePath;constructor(t){this.filePath=t??Ol();}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 da(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 da(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await da(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var Bh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function ro(e){if(!e||!Bh.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var Fh=/^[^@]+@[^@]+$/;function gn(e){return Fh.test(e)}function hn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var jh=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Kh(e){if(!jh.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 yn(e,t){let r=hn(e);Kh(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Vh=/^[\w./:@?&=+#%-]+$/;function Cs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Vh.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Jh=x("catalog.flow-api"),ks=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await pt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){ro(t);try{return await pt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await pt().head("v1/plugins/catalog"),Jh.debug("ping ok"),!0}catch{return false}}};var ie=new Es,jt=new Ts;ie.register(new ks);var yu=false;async function wu(){if(yu)return;yu=true;let e=await jt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(pa(),hu));for(let r of e)ie.register(new t(r.id,r.name,r.source));}var Su=2;async function fr(){return ie.fetchAll()}async function xu(){return ie.fetchAllWithErrors()}async function Sn(e){ro(e);try{return await pt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function Iu(e,t){ro(e);try{let r=await pt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),u=[],c=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(c+=m.byteLength,i&&c>s*Su)throw await l.cancel(),new Error(`Download exceeded expected size: received ${c} bytes, expected at most ${s*Su}`);u.push(m),i&&t?.(c,s);}return Buffer.concat(u)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function As(){try{let{profiles:e}=await pt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function bu(e,t){let r=pe.resolve(t);await Et.mkdir(r,{recursive:true});let n=pe.join(pe.dirname(r),`${randomUUID()}.zip`);try{await Et.writeFile(n,e);let o=await Xh.Open.file(n),s=pe.normalize(r+pe.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=pe.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(pe.resolve(pe.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 Et.unlink(n);}catch{}}}async function ma(e){await Et.rm(e,{recursive:true,force:true});}async function gr(){let e=_l();await Et.mkdir(pe.dirname(e),{recursive:true});try{await Et.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await bg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Zh(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:W,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Eu(){let e=Ro();if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return null}}function Qh(){let e=Eu();if(e)return e;let t=Zh(),r=Ro();return me__default.mkdirSync(pe__default.dirname(r),{recursive:true}),fa(t),t}function fa(e){let t=Ro(),r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function ey(){let e=_o(),t={};try{me__default.existsSync(e)&&(t=JSON.parse(me__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[W])return;t[W]={source:{source:"github",repo:"cit-flow/flow-skills"},installLocation:Rl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,e);}function Tu(e,t){mt(e.name),ey();let r=Ei(e.name);me__default.mkdirSync(pe__default.dirname(r),{recursive:true});try{me__default.lstatSync(r),me__default.rmSync(r,{recursive:!0,force:!0});}catch{}me__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Qh();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),fa(n));}function ga(e){mt(e);let t=Ei(e);try{me__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Eu();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&fa(r);}var ry=x("mcpConfigReader"),ny=500,oy=512;function sy(){return pe__default.join(ve__default.homedir(),".claude.json")}function iy(){return pe__default.join(process.cwd(),".mcp.json")}function ku(e){if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return ry.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function no(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ha(e){if(!no(e))return {};let t=e.mcpServers;return no(t)?t:{}}function ya(e,t){return Object.keys(e).slice(0,ny).map(n=>({name:y(n.slice(0,oy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function $u(){let e=[],t=sy(),r=ku(t);if(no(r)){let a=r,l=ha(a);e.push(...ya(l,"user"));let u=process.cwd();if(no(a.projects)){let c=a.projects[u];if(no(c)){let d=ha(c);e.push(...ya(d,"local"));}}}let n=iy(),o=ku(n),s=ha(o);e.push(...ya(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var qe=x("storage");async function ly(e,t,r){try{await E(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:J().interfaceType});}catch(n){qe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function cy(e,t,r){let n=t==="enabled"?v.CLI_TOOL_ENABLED:v.CLI_TOOL_DISABLED;E(n,{tool_id:e,source:r,interface:J().interfaceType}).catch(o=>qe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ia(){return pe__default.join(ve__default.homedir(),".claude","plugins","installed_plugins.json")}function uy(){return pe__default.join(ve__default.homedir(),".claude","plugins")}function Lu(e){let t=pe__default.resolve(e),r=pe__default.resolve(uy()),n=pe__default.resolve(pe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+pe__default.sep)||t===r,s=t.startsWith(n+pe__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Mu(e="user"){return e==="local"?pe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?pe__default.join(process.cwd(),".claude","settings.json"):pe__default.join(ve__default.homedir(),".claude","settings.json")}function Ze(){let e=Ia();if(!me__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function ba(){let e=Ia();try{let t=await me__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function dy(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ru(e,t){try{me__default.mkdirSync(pe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,e);}catch(r){throw dy(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Ye(e){Ru(Ia(),e);}function oo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function py(e,t){let r=pe__default.join(e,".claude-plugin"),n=pe__default.join(r,"plugin.json");if(me__default.existsSync(n))try{return JSON.parse(me__default.readFileSync(n,"utf-8"))}catch{return null}let o=pe__default.join(r,"marketplace.json");if(me__default.existsSync(o))try{let s=JSON.parse(me__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function va(e="user"){let t=Mu(e);if(!me__default.existsSync(t))return {};try{return JSON.parse(me__default.readFileSync(t,"utf-8"))}catch{return {}}}function _u(e,t="user"){Ru(Mu(t),e);}function my(e,t){let{name:r,marketplace:n}=oo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>oo(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 fy(e,t){let{name:r,marketplace:n}=oo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>oo(i).name===r)[0],o?{key:o,name:r}:null}function wa(e="user"){return va(e).enabledPlugins??{}}function Sa(e,t="user"){let r=va(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,_u(r,t);}function so(e,t,r="user"){let n=va(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},_u(n,r);}function gy(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function Q(){let e=Ze(),t=wa(),r=wa("project"),n=wa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=oo(u),p=c.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return gy(p).map(g=>{let h=py(g.installPath,d),I=(o[g.scope]??t)[u];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:I===false?"disabled":"enabled"}})}),i=$u(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function io(e,t){qe.debug(`[${e}] Acquiring lock to uninstall`);let r=await gr();try{let n=Ze(),o=fy(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);qe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Lu(l.installPath);let u=pe__default.dirname(l.installPath);qe.debug(`[${i}] Removing directory: ${u}`),me__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;Ye({...n,plugins:m}),Sa(s,t),ga(i);}else n.plugins[s]=c,Ye(n),Sa(s,t);}else {qe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Lu(c.installPath);let d=pe__default.dirname(c.installPath);qe.debug(`[${i}] Removing directory: ${d}`),me__default.rmSync(d,{recursive:!0,force:!0}),Sa(s,c.scope);}ga(i);let{[s]:l,...u}=n.plugins;Ye({...n,plugins:u});}await ly(i,a[0].origin??"internal",a[0].type??"skill"),qe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function ao(e,t,r){qe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await gr();try{let o=Ze(),{key:s,name:i}=my(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}`),so(s,t==="enabled",l),cy(i,t,u),qe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var hy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,yy=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function mt(e){if(!hy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function wy(e){if(!yy.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 hr=x("installer");function Sy(e,t){let r=`${e}@${W}`,o=Ze().plugins[r];if(o&&!t)throw new Be(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function xy(e,t,r){r&&await ma(t);try{hr.debug(`[${t}] Extracting archive...`),await bu(e,t);}catch(n){throw await ma(t),n}}function Iy(e,t,r,n,o,s="claude-code",i){let a=Ze(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],Ye(a),so(e,true,n);}async function by(e,t,r,n,o,s){try{await E(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:J().interfaceType});}catch(i){hr.warn(`Failed to send install metrics: ${String(i)}`);}}async function vy(e,t,r,n){try{await E(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(o){hr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function ke(e,t={}){let r=Date.now(),n=null;try{hr.debug(`[${e}] Acquiring lock...`),n=await gr();let{pluginKey:o,alreadyInstalled:s}=Sy(e,t.force);hr.debug(`[${e}] Fetching manifest...`);let i=await Sn(e);mt(i.name),wy(i.version),hr.debug(`[${e}] Downloading archive...`);let a=await Iu(e,t.onDownloadProgress),l=t.scope??"user",u=t.type??"skill",c=Ml(i.name,i.version);await xy(a,c,!!s&&!!t.force),Iy(o,c,i.version,l,"internal",t.providerId,u),Tu(i,c);let d=Date.now()-r;hr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:c,duration_ms:d};return t.skipMetrics||await by(i.name,i.version,d,Ps(l),"internal",u),m}catch(o){throw await vy(e,o,"internal",t.type??"skill"),hr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var Py=x("commands:helpers");async function ne(){let e=await X();if(!e)return T("Not authenticated. Run: flow auth login"),false;e.customUrl&&St(e.customUrl);try{await xt();}catch(t){return Py.debug(`Token validation failed: ${String(t)}`),T("Session expired. Run: flow auth login"),false}return true}async function Tt(e){let t=Pa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Du(e){let t=Pa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var xn=x("claudeProxy"),Aa="claude ",Ou="flow ",Ea=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Ta=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";}},Ey=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Ty=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Cy=/^(flow|claude)\s+auth\s+login(\s|$)/,Uu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Nu(e){return Uu.test(e.trim())}function ky(e){return Uu.exec(e.trim())?.[2]??""}async function Bu(e){let t=ky(e),r=Date.now();xn.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 $a(n)?new Ca:n}}function Ay(e){Fu(e);let t=e.slice(Aa.length);if(!Ey.test(t))throw new Ta(e)}var $s=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},Ca=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Fu(e){if(!e||!/^claude /.test(e))throw new Ea(e)}async function Se(e){Fu(e);let t=e.slice(Aa.length).split(/\s+/).filter(Boolean),r=$y(t);xn.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 xn.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 $a(o)?new $s:o}}function $y(e){return e.length>=3?e[2]:e.join(" ")}function $a(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Ly(e){return e.startsWith(Ou)?Aa+e.slice(Ou.length):e}function My(e){return Ty.test(e)||Cy.test(e)}function Ry(e){let t=0;for(;t<e.length&&My(e[t]);)t++;return e.slice(t)}var _y=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Dy(e,t){return !t||e.includes("--scope")||!_y.test(e)?e:`${e} --scope ${t}`}async function lo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Ry(r).map(i=>Ly(i)).map(i=>Dy(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Ay(i);xn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Se(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Se(o[i]),s.exitCode!==0)return s;return s}async function Ls(e,t,r){let n=hn(e),o=t?.trim();if(!o&&(o=(await Du(`Plugin "${n}" could not be installed.
111
+ If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Cs(o),r?.(),xn.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"}`);xn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw $a(s)?new $s:s}}var Fy=6e4,yr=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 Ct(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Fy}}).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 yr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new yr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new yr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function kt(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 Kr(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 Ky(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Vy(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Jy(e){return typeof e=="object"&&e!==null&&e.source==="github"}function In(e,t){let r=e.source;if(Ky(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(Vy(r))return {cloneUrl:r.url,subPath:"."};if(Jy(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 Qe(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var At=x("claude-code.adapter");function Wy(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=_o();if(!me__default.existsSync(s))return r;try{let i=JSON.parse(me__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 Wu(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=In(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=Wy(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ti(s,e.name,"external"):a=join(Cr(i==="user"?"global":"project"),e.name);let l=null;try{mt(e.name),l=await Ct(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(me__default.existsSync(a)&&me__default.rmSync(a,{recursive:!0,force:!0}),me__default.mkdirSync(dirname(a),{recursive:!0}),me__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await ba(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],Ye(d),so(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return At.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await kt(l).catch(()=>{});}}async function La(e,t,r,n){try{await E(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Ps(n),version:"unknown",duration_ms:t,interface:J().interfaceType});}catch(o){At.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Hu(e,t,r){try{await E(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(n){At.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var zy={async install(e,t){if(e.origin===qr&&!e.installCommand&&!gn(e.name))return Wu(e,t);if(e.origin===qr&&e.installCommand){let r=e.type??"skill",n=await lo(e.installCommand,t.scope);return n.exitCode===0?(await La(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Hu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(gn(e.name)){let r=e.type??"skill",n=yn(e.name,t.scope);At.debug(`[${e.name}] Attempting install: ${n}`);let o=await Se(n);if(o.exitCode===0)return await La(e.name,o.duration_ms,r,t.scope),{success:true};At.debug(`[${e.name}] First attempt failed, adding marketplace`),await Ls(e.name,t.marketplaceSource,()=>{});let s=await Se(n);return s.exitCode===0?(await La(e.name,s.duration_ms,r,t.scope),{success:true}):(await Hu(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return At.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await io(e,t);},getInstallPath(e,t){return ""}};function Gu(e){return {async install(t,r){if(t.origin===qr&&!t.installCommand&&!gn(t.name))return Wu(t,r);if(!t.installCommand)try{let o=await ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return At.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}At.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await lo(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=Ze(),o=`${t}@${W}`;if(n.plugins[o]){await io(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 Xy(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!me__default.existsSync(t))continue;let r=me__default.readdirSync(t).filter(n=>n.endsWith(".md")&&me__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Ma(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,Ma(r)]))}function zu(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(Ma(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Ma(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=zu(s,o):r[n]=o;}return r}async function Xu(e,t,r,n){let o=await ba(),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],Ye(o);}var qy={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=In(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{mt(e.name),s=await Ct(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Xy(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Oo(r);me__default.mkdirSync(l,{recursive:!0});let u=Qe(e.name);if(a.length===1)me__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=Qe(basename(d,".md"));me__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Xu(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return At.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await kt(s).catch(()=>{});}},async uninstall(e,t){let r=Oo(t),n=Qe(e);if(me__default.existsSync(r))for(let a of me__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))me__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ze(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Ye({...s,plugins:l});}else Ye({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Oo(t),`${Qe(e)}.md`)}},Yy={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=In(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{mt(e.name),s=await Ct(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!me__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(me__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=Xn();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=zu(m,u);return ns({...d,hooks:p}),await Xu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return At.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await kt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Ms=class{id="claude-code";name="Claude Code";async isAvailable(){return Kr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:zy,skill:Gu("skill"),mcp:Gu("mcp"),agent:qy,hook:Yy}};function Rs(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 Qy=new Set(["gh"]),ew=Rs(Qy,"use: gh copilot mcp remove <name>"),_s=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Kr("gh",["--version"])?Kr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:ew}};var tw=new Set(["opencode"]),rw=Rs(tw,"use: opencode config remove mcp <name>");function nw(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
112
+ `)}function qu(){return {async install(e,t){try{mt(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=In(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Ct(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Do(t.scope??"user"),a=join(s,".opencode","plugins");if(me__default.existsSync(a)){let l=me__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/"};me__default.mkdirSync(i,{recursive:!0}),me__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);me__default.existsSync(l)&&me__default.rmSync(l,{recursive:!0,force:!0}),me__default.mkdirSync(l,{recursive:!0}),me__default.cpSync(s,l,{recursive:!0}),me__default.mkdirSync(i,{recursive:!0}),me__default.writeFileSync(join(i,`${e.name}.js`),nw(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 kt(o).catch(()=>{});}},async uninstall(e,t){mt(e);let r=Do(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);me__default.existsSync(n)&&me__default.rmSync(n,{force:true}),me__default.existsSync(o)&&me__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Do(t),`${e}.js`)}}}var Ds=class{id="opencode";name="OpenCode";async isAvailable(){return Kr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:rw,skill:qu(),bundle:qu()}};var $t=new vs;$t.register(new Ms);lr()&&($t.register(new _s),$t.register(new Ds));function Yu({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(()=>{$t.getAvailableProviders(t??"bundle").then(u).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let w=l.find(I=>I.name===h);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let w=lu(h);w?r(w,c):s(false);},[r,c]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(w=>w.name),"Cancel"];return jsx(Xe,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(Xe,{itemName:`${e} \u2014 Choose scope`,actions:iu,descriptions:au,onAction:f,onClose:g},"scope"):jsx(Xe,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Qu({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,g)=>{g.upArrow?a(h=>Math.max(0,h-1)):g.downArrow?a(h=>Math.min(d.length-1,h+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.map(f=>{let g=y(f.name??f.flowId),h=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",f]})},f))})]}):jsx(Xe,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Ns({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function rd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Ns({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(Xe,{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 sd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Ns({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(Xe,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var Pn=x("bundle:installer"),id=/already exists/i;async function dw(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Nu(t)){let r=await Bu(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(id.test(n))return;throw new Error(n)}}else {let r=await lo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(id.test(n))return;throw new Error(n)}}}async function pw(e,t){try{await E(v.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Pn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function mw(e,t,r){try{await E(v.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Pn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function ad(e,t,r,n){try{await E(v.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Pn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function fw(e,t,r,n,o){try{await E(v.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Pn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function js(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 pw(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){Pn.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await ad(i,g,h,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await dw(f),u++,await mw(i,g,h),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let I=w instanceof Error?w.message:String(w);Pn.error(`Failed to install artifact "${g}": ${I}`),l.push({name:g,type:h,reason:I}),await ad(i,g,h,I),r?.({index:p+1,total:c,artifact:f,success:false,error:I});}}let d=Date.now()-a,m=l.length;return await fw(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}function dd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,js(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(ud,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(ud,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ae=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Q()})}));function pd({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 ",wt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function md({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${wt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((g,h)=>{let w=h===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:g.danger?"yellow":void 0,dimColor:!w,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function fd(e){return e.adapter.removable!==false?4:2}function gd({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function yd({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 wd({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,A)=>{if(A.escape){n();return}if(A.return){d(a[l]??null);return}if(A.upArrow){u(_=>Math.max(0,_-1));return}A.downArrow&&u(_=>Math.min(a.length-1,_+1));},{isActive:c===null}),c!==null)return jsx(gd,{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(Je/2)),p=Math.min(a.length,m+Je);p===a.length&&(m=Math.max(0,p-Je));let f=a.slice(m,p),g=m,h=a.length-p,w=s.length>0&&m<s.length,I=p>s.length,R=f.filter(P=>r.has(`${P.name}@${o}`)),B=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),R.map(P=>jsx(yd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),I&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),B.map(P=>jsx(yd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.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"})})]})}pa();var Iw=/^https?:\/\/.+/;function bw(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function vw(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function bd(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,w=d.current;if(!Iw.test(h)){c("URL must start with http:// or https://");return}c(null),o("adding");let I=randomUUID(),R=new wn(I,w,h);try{await R.fetchItems(),await jt.add({id:I,name:w,source:h}),ie.register(new wn(I,w,h)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(B){let P=bw(B)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":vw(B)?B.message:B instanceof Error?`Could not reach catalog URL: ${B.message}`:"Failed to validate catalog URL";t(P,"error"),o("add-url");}},[e,t,r]);return useInput((h,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!w.ctrl&&!w.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,w)=>{if(w.escape){o("add-name");return}if(w.return){g();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),c(null);return}h&&!w.ctrl&&!w.meta&&(m.current=m.current+h,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function vd(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await jt.remove(o),ie.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 Ed(){let e=S(L=>L.focus),t=S(L=>L.setFocus),r=S(L=>L.showNotification),n=ae(L=>L.installedItems),[o,s]=useState(()=>ie.listAdapters().map(L=>({adapter:L,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,d]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&g("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let L=ie.listAdapters(),N=await jt.read(),H=new Map(N.map(be=>[be.id,be]));s(L.map(be=>({adapter:be,stored:H.get(be.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let L=h.current[i-1];if(!L)return;let N=false;return p({items:[],loading:true,error:null}),L.adapter.fetchItems().then(H=>{N||p({items:H,loading:false,error:null});}).catch(H=>{N||p({items:[],loading:false,error:H instanceof Error?H.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let I=bd(w),R=useCallback(()=>{w(),a(0),u("list"),p(null),g("main");},[w]),{handleRemove:B}=vd(R),P=useCallback(async L=>{g("removing"),await B(L);},[B]),A=useCallback(async L=>{try{let N=await L.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),L.stored){let H=new Date().toISOString();await jt.updateField(L.stored.id,{lastUpdated:H}),w();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[w,r]),_=useCallback(async L=>{if(!L.stored)return;let N=L.stored.autoUpdate!==false;await jt.updateField(L.stored.id,{autoUpdate:!N}),w();},[w]),j=useCallback(()=>g("browse"),[]),fe=useCallback(L=>{let N=o[i-1];if(!N)return;let H=N.adapter.removable!==false;[j,()=>{A(N);},...H?[()=>{_(N);},()=>{P(N.adapter.id);}]:[]][L]?.();},[o,i,j,A,_,P]),b=useCallback(()=>g("main"),[]),$=useCallback(()=>{let L=o[i-1];L&&A(L);},[o,i,A]),F=useCallback(()=>{let L=o[i-1];L&&_(L);},[o,i,_]),D=useCallback(()=>{let L=o[i-1];L&&P(L.adapter.id);},[o,i,P]);if(useInput((L,N)=>{if(N.upArrow){a(H=>Math.max(0,H-1));return}if(N.downArrow){a(H=>Math.min(o.length,H+1));return}(N.return||N.tab)&&(i===0?I.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&I.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((L,N)=>{if(N.escape||N.tab){u("list");return}if(N.upArrow){d(H=>Math.max(0,H-1));return}if(N.downArrow){let H=o[i-1],be=H?fd(H)-1:0;d($o=>Math.min($o+1,be));return}N.return&&fe(c);},{isActive:f==="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(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let L=o[i-1];if(!L)return jsx(Box,{});let N=L.adapter.id??"default",H=new Set(n.filter(be=>be.marketplace===L.adapter.name).map(be=>`${be.name}@${N}`));return jsx(wd,{entry:L,items:m?.items??[],installedKeys:H,onBack:b})}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 ue=o[i-1]??null,Xr=ue?n.filter(L=>L.marketplace===ue.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(pd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&ue?jsx(md,{entry:ue,detailData:m,installedCount:Xr,focusPanel:l,actionIndex:c,onBrowse:j,onUpdate:$,onToggleAutoUpdate:F,onRemove:D}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:ue?"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 Td(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=q.findIndex(i=>i.id===r.activeTab),s=q[(o-1+q.length)%q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=q.findIndex(i=>i.id===r.activeTab),s=q[(o+1)%q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=q.findIndex(i=>i.id===r.activeTab),s=q[(o+1)%q.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==="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 Cd(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function kd(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 kw=new Set(q.filter(e=>e.focus!=="list").map(e=>e.focus));function So(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}=Ne.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 Ad({listLength:e}){let t=S(g=>g.focus),r=S(g=>g.selectedIndex),n=S(g=>g.actionMenuOpen),o=S(g=>g.setFocus),s=S(g=>g.setActionMenuOpen),i=Ne(g=>g.query),a=Ne(g=>g.setQuery),l=Ne(g=>g.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Ne.getState();h(g.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();So(Qi(g,h,{activeTab:w}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();So(Qi("",h,{activeTab:w}));},{isActive:kw.has(t)}),useInput((g,h)=>{let{activeTab:w,selectedIndex:I,actionMenuOpen:R}=S.getState();So(Td(g,h,{activeTab:w,selectedIndex:I},u.current));},{isActive:t==="list"}),useInput((g,h)=>{So(Cd(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let w=kd(g,h,Ne.getState().query),I=w.queryUpdate;if(So(w.actions),I==="reset")l(),d("");else if(I!==null){let{query:R,cursorPosition:B,setCursorPosition:P}=Ne.getState();if("backspace"in I)B>0&&(a(R.slice(0,B-1)+R.slice(B)),P(B-1));else if("append"in I)a(R.slice(0,B)+I.append+R.slice(B)),P(B+I.append.length);else if("cursorMove"in I){let A=B+I.cursorMove;A>=0&&A<=R.length&&P(A);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:w}=S.getState();g===0?h(0):w>=g&&h(g-1);},[]),f=useCallback(g=>{if(!c)return u.current=g.length,g;let h=c.toLowerCase(),w=g.filter(I=>I.name.toLowerCase().includes(h)||I.description?.toLowerCase().includes(h));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Ld(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=We(a=>a.justAuthenticated),o=We(a=>a.credentials),s=We(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 Le(e,t,r=false){return r?true:!Ua.valid(e)||!Ua.valid(t)?false:Ua.gt(t,e)}var Jt=x("updater");async function Aw(e,t,r,n,o,s){try{await E(v.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:J().interfaceType});}catch(i){Jt.warn(`Failed to send update metrics: ${String(i)}`);}}function $w(e){let t=Ze(),r=`${e}@${W}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Hs(e,t={}){let r=Date.now(),n=null;try{Jt.debug(`[${e}] Acquiring lock...`),n=await gr();let o=$w(e);if(!o)throw Jt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Jt.debug(`[${e}] Fetching manifest...`);let u=(await Sn(e)).version;if(!i||!Le(i,u,t.force))throw Jt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new mr(e,i??"unknown");Jt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await ke(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Aw(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Jt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Jt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await gr();let d=Ze(),m=`${e}@${W}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Ye(d),Jt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}var Gs=x("dispatcher");async function Lw(e,t,r,n,o){let s=hn(e);return Gs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Ls(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Gs.debug(`[${e}] Retrying install after marketplace add`),Se(t)}async function Md(e,t,r,n){let o=yn(e,n),s=hn(e);r?.onStatus?.(`Installing ${s}...`),Gs.debug(`[${e}] Attempting install: ${o}`);let i=await Se(o);if(i.exitCode===0)return i;Gs.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Lw(e,o,a,t,r)}async function Rd(e,t,r){let n=e.type??"bundle",o=await $t.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 _d(){let e=ae(i=>i.installedItems),t=ae(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Rd(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=Q().find(p=>p.name===i),u=l?.providerId??"claude-code",c=$t.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 ao(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Hs(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var zs=x("mcp");function xo(e,t){e.silent?Ge({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):T(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Od(e,t){e.silent?Oe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(re(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&k(t.stdout));}function Mw(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 Na(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 Ud(e,t,r){if(!await ne())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return xo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}zs.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Mw(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Tt(`Install external MCP "${s}"?
113
113
  This will run: ${i}
114
- [y/N] `))return Vs.debug(`[${e}] Installation cancelled by user`),T("Operation cancelled."),0}let o=r.silent?void 0:sl({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await Pe(n);return o?.stop(),s.exitCode!==0?(wo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&T(`stdout: ${s.stdout}`),1):(wd(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),wo(r,{name:e,action:"add",message:X(s)}),1}}async function xd(e,t){if(!await ce())return 1;Vs.debug(`[${e}] Starting MCP remove`);let r=Ma(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await Mt(`Remove MCP "${o}"?
114
+ [y/N] `))return zs.debug(`[${e}] Installation cancelled by user`),k("Operation cancelled."),0}let o=r.silent?void 0:wl({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await Se(n);return o?.stop(),s.exitCode!==0?(xo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&k(`stdout: ${s.stdout}`),1):(Od(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),xo(r,{name:e,action:"add",message:V(s)}),1}}async function Nd(e,t){if(!await ne())return 1;zs.debug(`[${e}] Starting MCP remove`);let r=Na(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await Tt(`Remove MCP "${o}"?
115
115
  This will run: ${s}
116
- [y/N] `))return Vs.debug(`[${e}] Removal cancelled by user`),T("Operation cancelled."),0}let n=t.silent?void 0:sl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await Pe(r);return n?.stop(),o.exitCode!==0?(wo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&T(`stdout: ${o.stdout}`),1):(wd(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),wo(t,{name:e,action:"remove",message:X(o)}),1}}function Id({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(E=>E.setLoading),c=S(E=>E.setDownloadProgress),{install:u,uninstall:d,toggle:m,update:p}=hd(),f=async(E,L,K)=>{l(true,E),n();try{await L(),o(r.length),s(K,"success");}catch(H){let de=H instanceof Error?H.message:"Something went wrong";i.error(`[withLoading] ${E} failed: ${de}`),s(de,"error");}finally{l(false);}};return {handleInstall:(E,L)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>u(t,{scope:E,...L!==void 0?{providerId:L}:{},onDownloadProgress:(K,H)=>{let de=Date.now();(de-a.current>100||K>=H)&&(a.current=de,c(K,H));}}),"\u2713 Installed successfully"));},handleUninstall:E=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,E),"\u2713 Uninstalled");},handleToggleStatus:E=>{if(!e)return;let L=e.status==="enabled";f(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,E),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let E=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${E}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${E}`,"success");}catch(K){if(K instanceof wr)s(K.message,"info");else {let H=K instanceof Error?K.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${H}`),s(H,"error");}}finally{l(false);}})();},handleBatchUpdate:E=>{if(E.length===0)return;let L=E.length;(async()=>{l(true,`Updating ${L} plugin${L>1?"s":""}...`),n();try{let H=[];for(let N of E)H.push(await p(N.name).then(()=>({status:"fulfilled",value:void 0}),G=>({status:"rejected",reason:G})));let de=H.filter(N=>N.status==="fulfilled").length,C=H.map((N,G)=>N.status==="rejected"?E[G].name:null).filter(N=>N!==null);o(r.length),C.length===0?s(`\u2713 Updated ${de}/${L} plugin${L>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${C.join(", ")}`),s(`Updated ${de}/${L}; failed: ${C.join(", ")}`,de>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:E=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let L=Ma(e.name,E),K=await Pe(L);if(K.exitCode!==0)throw new Error(K.stderr||"MCP removal failed");me.getState().loadFromDisk();},"\u2713 MCP removed");}}}var So=x("api:bundle"),$n=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},xo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Iw=/^[a-zA-Z0-9_-]{1,128}$/;async function vd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw So.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new $n(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new xo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw So.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Pd(e){if(!Iw.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);So.debug(`Fetching bundle by flowId "${e}"`);try{return await ht().get(`v1/use-cases/${t}`).json()}catch(r){return vd(r,e)}}async function Hs(e){let t=encodeURIComponent(e);So.debug(`Fetching bundle by name "${e}"`);let r;try{r=await ht().get(`v1/use-cases/by-name/${t}`).json(),So.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return vd(n,e)}if(r.length===0)throw new $n(e);return r[0]}var bw=x("tui:bundle-flow");function Ed({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:c,setBundleInstallFlow:u}=S.getState(),d=l?.trim();bw.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),c(true,"Loading bundle..."),(d?Pd(d):Hs(a)).then(p=>{c(false),S.getState().actionMenuOpen&&u({phase:"detail",bundle:p});}).catch(p=>{c(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(),me.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var Io=["local","project","user"],vw=new Set(["--transport","--scope","-s"]);function Td(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(vw.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function zr(e,t){return t?`${e}::${t}`:e}function Ra(e){return e===Z?Un:Qr}function Cd(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??Un,flowId:e.flowId}}function _a(e,t){let r=Ra(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function kd(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 Io.filter(r=>t.has(r)).map(r=>({scope:r,label:Nn[r].label,pathHint:Nn[r].pathHint,items:t.get(r)??[]}))}function Ad(e){let t=r=>{if(!r)return 1/0;let n=Io.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function $d({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>zr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(zr(g.name,g.author?.name))??h.get(g.name),v=w?.version,O=!!v&&!!g.version&&Re(g.version,v);return {...g,updateAvailable:O,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(zr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Td(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>Cd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>_a(f,f.catalogItem)):a.map(f=>_a(f,f.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(f=>{let h=f.type??"bundle";if(!n.types.has(h))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),u=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${u} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(zr(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Da(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=S(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await ru();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,b(I.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{u();},[u,c]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:u}}function Ld(){return {items:me(t=>t.installedItems)}}var kw=x("catalog");function Rd(){let e=S(z=>z.bundleInstallFlow),t=S(z=>z.activeTab),r=S(z=>z.notification),n=S(z=>z.loading),o=S(z=>z.loadingMessage),s=S(z=>z.downloadProgress),i=S(z=>z.downloadTotal),a=S(z=>z.catalogError),l=S(z=>z.setCatalogError),c=S(z=>z.catalogFilters),u=Fe(z=>z.query),{catalog:d,isLoading:m,error:p,refetch:f}=Da(),{items:h}=Ld(),g=me(z=>z.loadFromDisk),{items:w,emptyMessage:v,getSelectedCatalogItem:O,outdatedCount:_}=$d({catalog:d,installedItems:h,activeTab:t,catalogFilters:c,searchQuery:u}),{actionMenuOpen:E,closeMenu:L,selectedIndex:K,clampIndex:H,filteredItems:de}=dd({listLength:w.length}),C=de(w),N=useMemo(()=>t!=="installed"&&t!=="updates"?C:Ad(C),[t,C]),G=useMemo(()=>t==="installed"||t==="updates"?kd(N):[],[t,N]),B=N[K]??null,be=useMemo(()=>O(B),[O,B]),{notify:jt}=md(),{handleInstall:$,handleUninstall:U,handleToggleStatus:W,handleUpdate:A,handleBatchUpdate:R,handleMcpConfigUninstall:V}=Id({selectedItem:B,selectedCatalogItem:be,items:w,closeMenu:L,clampIndex:H,notify:jt}),{handleBundleInstallStart:lt,handleBundleDetailConfirm:Zr,handleBundleDetailBack:Km,handleBundleInstallComplete:Vm}=Ed({closeMenu:L,notify:jt}),Hm=useCallback(()=>R(N),[R,N]);return useEffect(()=>{g();},[]),useEffect(()=>{H(N.length);},[N.length,H]),useEffect(()=>{p&&(kw.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(mn,{}),jsx(yc,{outdatedCount:_}),t==="marketplaces"&&mr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(ad,{})}):jsx(Rc,{filteredItems:N,groups:G,emptyMessage:v,onBatchUpdate:Hm}),(n||m)&&jsxs(Fragment,{children:[jsx(ms,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(gs,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(hs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(_c,{message:r.message,type:r.type}),E&&B&&(t==="discover"?be?.type==="bundle"?e?.phase==="installing"?jsx(Wu,{bundle:e.bundle,onComplete:Vm}):jsx(Du,{itemName:B.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>lt(B.name,B.flowId),onConfirm:Zr,onClose:e?.phase==="detail"?Km:L}):jsx(Ru,{itemName:B.name,itemType:be?.type,onInstall:$,onClose:L}):B.type==="mcp"?jsx(ju,{itemName:B.name,itemScope:B.scope??"user",onUninstall:V,onClose:L}):jsx(Nu,{itemName:B.name,itemScope:B.scope??"user",itemStatus:B.status??"enabled",updateAvailable:B.updateAvailable??false,catalogVersion:be?.version,onUninstall:U,onToggleStatus:z=>W(z),onUpdate:A,onClose:L})),jsx(ps,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(me.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"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"})}));var Rw=3;function Dd(){let e=M(u=>u.setStarterKits),t=M(u=>u.setIsLoadingStarterKits),r=M(u=>u.setStarterKitsError),n=M(u=>u.setPluginStatus),o=M(u=>u.setPluginDownloadProgress),s=M(u=>u.setStep),i=M(u=>u.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let u=await Ps();e(u);}catch(u){r(u instanceof Error?u.message:String(u));}finally{t(false);}},[t,r,e]);useEffect(()=>{me.getState().loadFromDisk(),a();},[a]);let l=useRef(0),c=useCallback(async()=>{let u=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of u){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=Rw;h++)try{await $e(m.name,{onDownloadProgress:(g,w)=>{let v=Date.now();(v-l.current>100||g>=w)&&(l.current=v,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof je){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:q().interfaceType}).catch(()=>{}));}let d=Or();Dr("summary_review"),b(I.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),me.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:c}}var bo={cursorDelta:0,confirm:false,back:false};function Od(e,t){return t.upArrow?{...bo,cursorDelta:-1}:t.downArrow?{...bo,cursorDelta:1}:t.escape?{...bo,back:true}:t.return?{...bo,confirm:true}:bo}var _w={cursorDelta:0,select:false};function Ud(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:_w}var Nd=Bg.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var Ka=5;function Bd({onRetry:e}){let t=M(u=>u.starterKits),r=M(u=>u.selectedStarterKitIndex),n=M(u=>u.isLoadingStarterKits),o=M(u=>u.starterKitsError);if(n)return jsx(ms,{message:"Loading Starter Kits..."});if(o)return jsx(hs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(fn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Ka/2)),i=Math.min(t.length,s+Ka);i===t.length&&(s=Math.max(0,i-Ka));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(Nd,{starterKit:u,isSelected:s+d===r},u.slug)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var jd=Bg.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Ja=8;function Kd(){let e=M(u=>u.selectedStarterKit),t=M(u=>u.plugins),r=M(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(I.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,s=Math.max(0,r-Math.floor(Ja/2)),i=Math.min(t.length,s+Ja);i===t.length&&(s=Math.max(0,i-Ja));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(jd,{plugin:u,isCursor:s+d===r},u.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var Vw=["Retry failed","Continue anyway"];function Vd({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(gs,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Hd({onComplete:e,onRetry:t}){let r=M(c=>c.plugins),n=M(c=>c.step),o=M(c=>c.successCount),s=M(c=>c.failedCount),i=M(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(Vd,{name:c.name,status:c.status,error:c.error,downloadProgress:c.downloadProgress,downloadTotal:c.downloadTotal},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(Vd,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Vw.map((c,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",c]})},c))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Jd(){let e=M(C=>C.step),t=M(C=>C.starterKits),r=M(C=>C.selectedStarterKitIndex),n=M(C=>C.setSelectedStarterKitIndex),o=M(C=>C.selectStarterKit),s=M(C=>C.plugins),i=M(C=>C.pluginCursorIndex),a=M(C=>C.setPluginCursorIndex),l=M(C=>C.setStep),c=M(C=>C.summaryActionIndex),u=M(C=>C.setSummaryActionIndex),d=M(C=>C.failedCount),m=M(C=>C.resetForRetry),p=M(C=>C.goBackToList),f=S(C=>C.setScreen),h=S(C=>C.setFocus),g=S(C=>C.focus),w=Xe(C=>C.setJustAuthenticated),v=Xe(C=>C.justAuthenticated),{loadStarterKits:O,installSelected:_}=Dd(),E=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),E.current||(E.current=true,Dr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let L=useCallback(async()=>{let C=M.getState().selectedStarterKit;if(C){let G=await ee();G&&await Ht({...G,starterKit:C.slug});}b(I.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Or()}).catch(()=>{});let{successCount:N}=M.getState();b(I.CLI_ONBOARDING_COMPLETED,{duration_ms:Jt(),tools_installed_count:N}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),K=useCallback(()=>{m(),_();},[m,_]),H=useCallback(()=>{O();},[O]),de=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((C,N)=>{if(N.escape)Zo("esc"),de();else if(N.upArrow&&r>0)n(r-1);else if(N.downArrow&&r<t.length-1)n(r+1);else if(N.return&&t.length>0){let G=Or();o(t[r]),Dr("kit_display"),b(I.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:G}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((C,N)=>{let G=Od(C,N);if(G.cursorDelta!==0){let B=i+G.cursorDelta;B>=0&&B<s.length&&a(B);}if(G.confirm){let B=M.getState().selectedStarterKit;B&&(async()=>(await ee())?.starterKit!==B.slug&&b(I.CLI_KIT_ACCEPTED,{bundle_slug:B.slug}).catch(()=>{}))();let be=Or();Dr("kit_confirmation"),b(I.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:be}).catch(()=>{});let jt=Or();Dr("tool_installation"),b(I.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:jt}).catch(()=>{}),l("installing"),_();}if(G.back){let B=M.getState().selectedStarterKit;B&&b(I.CLI_KIT_REJECTED,{bundle_slug:B.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((C,N)=>{if(d===0)return;let G=Ud(C,N);if(G.cursorDelta!==0){let B=c+G.cursorDelta;B>=0&&B<=1&&u(B);}G.select&&(c===0?K():L());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(mn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!v&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(Bd,{onRetry:H}),e==="starterKitDetail"&&jsx(Kd,{}),(e==="installing"||e==="summary")&&jsx(Hd,{onComplete:L,onRetry:K})]}),jsx(ps,{})]})}var zd=null;function Xd(){return zd}async function Zs(){let t=Br().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=ne.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await qd(n);(o||s)&&await pt({...r,installedVersion:o,installMethod:s});}}async function qd(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 At(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Mn(e){let t=await Promise.all(e.map(r=>Gw(r)));return zd=t,t}async function Gw(e){let t=Gd(e.versionCommand);t==="permission-denied"&&(Ww(e.versionCommand[0]),t=Gd(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 At(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!qe(e.alias)){let{installedVersion:l,installMethod:c}=await qd(e);await pt({alias:e.alias,name:e.name,installedVersion:l,installMethod:c,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Gd(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 Ww(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=Se__default.realpathSync(r),{mode:o}=Se__default.statSync(n);Se__default.chmodSync(n,o|73);}catch{}}function qw(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 tp(e,t){let[r,n]=useState(()=>qw(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),c=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,h=m.upArrow||d==="[A",g=m.downArrow||d==="[B";if(h||g)h&&p>0?s(p-1):g&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let v=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),O=w.availableStrategies[(v+1)%w.availableStrategies.length];n(_=>_.map(E=>E.module.alias===w.module.alias?{...E,selectedStrategy:O}:E));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function np({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}=tp(e,r==="moduleSetup"),c=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),u=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),c();},[l,t,c]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let h=f===a,g=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(Ye,{itemName:m,actions:d,onAction:u,onClose:c})]})}var tS=/^https?:\/\/.+/;function op({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,c)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||c.return){e(null);return}}if(t==="input"){if(c.escape){a.current="",o(""),r("confirm");return}if(c.return){let u=a.current.trim();u.length>0&&tS.test(u)?(i(false),e(u)):u.length>0&&i(true);return}if(c.backspace||c.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!c.ctrl&&!c.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 nS(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 ap(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=nS(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 hr(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]),c=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:c,skippedCount:u}}function lp({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function pp({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:c}=ap(e,t),u=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Fr().catch(()=>{}),n("list");let w=oe().some(v=>v.name===ie);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!u&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,u,p]),useInput((w,v)=>{v.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,h=a-f,g=[];return h>0&&g.push(jsxs(Text,{color:"green",children:[h," installed"]},"i")),f>0&&g.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&g.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),c>0&&g.push(jsxs(Text,{dimColor:true,children:[c," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(lp,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,v,O)=>(O>0&&w.push(jsx(Text,{children:" | "},`sep-${O}`)),w.push(v),w),[])}),jsx(Box,{paddingX:1,children:l>0||u?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function fp(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),c=S(p=>p.setScreen),u=useCallback(p=>{if(ec(p)){Fr().catch(()=>{}),l("list");let h=oe().some(g=>g.name===ie);c(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,c]);useEffect(()=>{let p=Xd();if(p){u(p);return}Mn(ne).then(u).catch(()=>{n([]),t("selection");});},[u]);let d=useCallback(p=>{s(p);let f=p.some(h=>h.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(np,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(op,{onConfirm:m}),e==="installation"&&jsx(pp,{confirmedItems:o,customUrl:i})]})}var mS=x("ClaudeMdSuggestion"),fS=[`Install ${ie}`,"Skip for now"],gS=["Retry","Skip for now"];function yp(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{b(I.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,b(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await $e(ie),o("installed");}catch(m){if(m instanceof je){o("installed");return}mS.warn(`Failed to install ${ie}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?gS:fS;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?c():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),u()):c());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(mn,{}),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(hp,{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(Gu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ie,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ie," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",ie]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ie]}),jsx(hp,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function hp({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 SS=promisify(execFile),ni="@ciandt-flow/cli";async function wp(){let e=le;if(La.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ni};try{let t=await fetch(`https://registry.npmjs.org/${ni}/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:ni}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ni}}}async function oi(e){try{return await SS(Gt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function xS(e){let t=qe(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await At(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await pt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Sp(e){let t=await xS(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 xp(e,t){let r=qe(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await At(r.installMethod).update(e,t.currentVersion??"");return o.success?(await pt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Ip(e){let r=qe(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 bp(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ne.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([wp(),Mn(ne),Promise.all(ne.map(l=>Sp(l)))]);if(Zs(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await oi(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=ne.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await xp(c,l);u.success?r(l.moduleAlias,{status:"updated",detail:`v${u.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:Ip(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await Fr(),t(l=>({...l,outcome:"done"}));}catch{await Fr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function TS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Gu,{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 CS({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 vp(){let{outcome:e,items:t}=bp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=oe().some(i=>i.name===ie);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(TS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(CS,{outcome:e})})]})}var LS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Pp=10;function Ep(){let[e,t]=useState(vi());useEffect(()=>Pl(()=>{t([...vi()]);}),[]);let r=e.slice(-Pp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Pp,") \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:LS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var DS=x("app"),OS={auth:cc,starterKitSetup:Jd,moduleSetup:fp,claudeMdSuggestion:yp,verify:vp,main:Rd};function kp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Yn(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Ap(){b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Jt(),interface:"tui"}).catch(()=>{});}async function Lp(){let e=await ee();if(e&&Yl()&&await dr()){e.customUrl&&Pt(e.customUrl);let{clientSecret:n,...o}=e;Xe.getState().setCredentials(o),Ap(),Yn(e);return}if(!e){kp();return}try{e.customUrl&&Pt(e.customUrl),await Et();}catch(n){DS.debug(`Token validation failed: ${String(n)}`),kp();return}Ap();let{clientSecret:t,...r}=e;Xe.getState().setCredentials(r),Yn(e);}function Mp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=OS[r],{pendingExit:o}=Wl(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Ep,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function nl(e,t={}){let r=es({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return ts(r),await Ht(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var It=x("auth");function _p(){Be.clearFallbackFile(),Wo();}var US=3,Rp=3,Dp=` \u2139 The data collected during setup is used solely to improve
116
+ [y/N] `))return zs.debug(`[${e}] Removal cancelled by user`),k("Operation cancelled."),0}let n=t.silent?void 0:wl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await Se(r);return n?.stop(),o.exitCode!==0?(xo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&k(`stdout: ${o.stdout}`),1):(Od(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),xo(t,{name:e,action:"remove",message:V(o)}),1}}function Bd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(P=>P.setLoading),u=S(P=>P.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=_d(),f=async(P,A,_)=>{l(true,P),n();try{await A(),o(r.length),s(_,"success");}catch(j){let fe=j instanceof Error?j.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${fe}`),s(fe,"error");}finally{l(false);}};return {handleInstall:(P,A)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:P,...A!==void 0?{providerId:A}:{},onDownloadProgress:(_,j)=>{let fe=Date.now();(fe-a.current>100||_>=j)&&(a.current=fe,u(_,j));}}),"\u2713 Installed successfully"));},handleUninstall:P=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let A=e.status==="enabled";f(A?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,P),A?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${P}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(_){if(_ instanceof mr)s(_.message,"info");else {let j=_ instanceof Error?_.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${j}`),s(j,"error");}}finally{l(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let A=P.length;(async()=>{l(true,`Updating ${A} plugin${A>1?"s":""}...`),n();try{let j=[];for(let $ of P)j.push(await p($.name).then(()=>({status:"fulfilled",value:void 0}),F=>({status:"rejected",reason:F})));let fe=j.filter($=>$.status==="fulfilled").length,b=j.map(($,F)=>$.status==="rejected"?P[F].name:null).filter($=>$!==null);o(r.length),b.length===0?s(`\u2713 Updated ${fe}/${A} plugin${A>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${b.join(", ")}`),s(`Updated ${fe}/${A}; failed: ${b.join(", ")}`,fe>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:P=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let A=Na(e.name,P),_=await Se(A);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");ae.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Io=x("api:bundle"),An=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},bo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Dw=/^[a-zA-Z0-9_-]{1,128}$/;async function jd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Io.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new An(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new bo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Io.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Kd(e){if(!Dw.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Io.debug(`Fetching bundle by flowId "${e}"`);try{return await pt().get(`v1/use-cases/${t}`).json()}catch(r){return jd(r,e)}}async function Xs(e){let t=encodeURIComponent(e);Io.debug(`Fetching bundle by name "${e}"`);let r;try{r=await pt().get(`v1/use-cases/by-name/${t}`).json(),Io.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return jd(n,e)}if(r.length===0)throw new An(e);return r[0]}var Ow=x("tui:bundle-flow");function Vd({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();Ow.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Kd(d):Xs(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(),ae.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var vo=["local","project","user"],Uw=new Set(["--transport","--scope","-s"]);function Jd(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(Uw.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Jr(e,t){return t?`${e}::${t}`:e}function Ba(e){return e===W?Dn:qr}function Hd(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??Dn,flowId:e.flowId}}function Fa(e,t){let r=Ba(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Gd(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 vo.filter(r=>t.has(r)).map(r=>({scope:r,label:On[r].label,pathHint:On[r].pathHint,items:t.get(r)??[]}))}function Wd(e){let t=r=>{if(!r)return 1/0;let n=vo.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function zd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Jr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[Jr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let w=f.get(Jr(h.name,h.author?.name))??g.get(h.name),I=w?.version,R=!!I&&!!h.version&&Le(h.version,I);return {...h,updateAvailable:R,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Jr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?Jd(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>Hd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>Fa(f,f.catalogItem)):a.map(f=>Fa(f,f.catalogItem)),[r,e,s,i,a]),u=useMemo(()=>l.filter(f=>{let g=f.type??"bundle";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(h=>[Jr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Jr(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function ja(){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 xu();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,E(v.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Xd(){return {items:ae(t=>t.installedItems)}}var Kw=x("catalog");function Yd(){let e=S(K=>K.bundleInstallFlow),t=S(K=>K.activeTab),r=S(K=>K.notification),n=S(K=>K.loading),o=S(K=>K.loadingMessage),s=S(K=>K.downloadProgress),i=S(K=>K.downloadTotal),a=S(K=>K.catalogError),l=S(K=>K.setCatalogError),u=S(K=>K.catalogFilters),c=Ne(K=>K.query),{catalog:d,isLoading:m,error:p,refetch:f}=ja(),{items:g}=Xd(),h=ae(K=>K.loadFromDisk),{items:w,emptyMessage:I,getSelectedCatalogItem:R,outdatedCount:B}=zd({catalog:d,installedItems:g,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:P,closeMenu:A,selectedIndex:_,clampIndex:j,filteredItems:fe}=Ad({listLength:w.length}),b=fe(w),$=useMemo(()=>t!=="installed"&&t!=="updates"?b:Wd(b),[t,b]),F=useMemo(()=>t==="installed"||t==="updates"?Gd($):[],[t,$]),D=$[_]??null,ue=useMemo(()=>R(D),[R,D]),{notify:Xr}=Ld(),{handleInstall:L,handleUninstall:N,handleToggleStatus:H,handleUpdate:be,handleBatchUpdate:$o,handleMcpConfigUninstall:Qm}=Bd({selectedItem:D,selectedCatalogItem:ue,items:w,closeMenu:A,clampIndex:j,notify:Xr}),{handleBundleInstallStart:ef,handleBundleDetailConfirm:tf,handleBundleDetailBack:rf,handleBundleInstallComplete:nf}=Vd({closeMenu:A,notify:Xr}),of=useCallback(()=>$o($),[$o,$]);return useEffect(()=>{h();},[]),useEffect(()=>{j($.length);},[$.length,j]),useEffect(()=>{p&&(Kw.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(pn,{}),jsx(Dc,{outdatedCount:B}),t==="marketplaces"&&lr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Ed,{})}):jsx(Yc,{filteredItems:$,groups:F,emptyMessage:I,onBatchUpdate:of}),(n||m)&&jsxs(Fragment,{children:[jsx(ws,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(xs,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Is,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Zc,{message:r.message,type:r.type}),P&&D&&(t==="discover"?ue?.type==="bundle"?e?.phase==="installing"?jsx(dd,{bundle:e.bundle,onComplete:nf}):jsx(Qu,{itemName:D.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>ef(D.name,D.flowId),onConfirm:tf,onClose:e?.phase==="detail"?rf:A}):jsx(Yu,{itemName:D.name,itemType:ue?.type,onInstall:L,onClose:A}):D.type==="mcp"?jsx(sd,{itemName:D.name,itemScope:D.scope??"user",onUninstall:Qm,onClose:A}):jsx(rd,{itemName:D.name,itemScope:D.scope??"user",itemStatus:D.status??"enabled",updateAvailable:D.updateAvailable??false,catalogVersion:ue?.version,onUninstall:N,onToggleStatus:K=>H(K),onUpdate:be,onClose:A})),jsx(ys,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ae.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"})}));var Ww=3;function Qd(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await As();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{ae.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let g=1;g<=Ww;g++)try{await ke(m.name,{onDownloadProgress:(h,w)=>{let I=Date.now();(I-l.current>100||h>=w)&&(l.current=I,o(m.name,h,w));}}),n(m.name,"success"),f=!0;break}catch(h){if(h instanceof Be){n(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(n(m.name,"failed",p),E(v.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:J().interfaceType}).catch(()=>{}));}let d=Lr();$r("summary_review"),E(v.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),ae.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var Po={cursorDelta:0,confirm:false,back:false};function ep(e,t){return t.upArrow?{...Po,cursorDelta:-1}:t.downArrow?{...Po,cursorDelta:1}:t.escape?{...Po,back:true}:t.return?{...Po,confirm:true}:Po}var zw={cursorDelta:0,select:false};function tp(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:zw}var rp=Qg.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var za=5;function np({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(ws,{message:"Loading Starter Kits..."});if(o)return jsx(Is,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(mn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(za/2)),i=Math.min(t.length,s+za);i===t.length&&(s=Math.max(0,i-za));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(rp,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var sp=Qg.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var Ya=8;function ip(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,E(v.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(c=>c.installed).length,s=Math.max(0,r-Math.floor(Ya/2)),i=Math.min(t.length,s+Ya);i===t.length&&(s=Math.max(0,i-Ya));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(sp,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var nS=["Retry failed","Continue anyway"];function ap({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ud,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(xs,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function lp({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(ap,{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(ap,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:nS.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 cp(){let e=M(b=>b.step),t=M(b=>b.starterKits),r=M(b=>b.selectedStarterKitIndex),n=M(b=>b.setSelectedStarterKitIndex),o=M(b=>b.selectStarterKit),s=M(b=>b.plugins),i=M(b=>b.pluginCursorIndex),a=M(b=>b.setPluginCursorIndex),l=M(b=>b.setStep),u=M(b=>b.summaryActionIndex),c=M(b=>b.setSummaryActionIndex),d=M(b=>b.failedCount),m=M(b=>b.resetForRetry),p=M(b=>b.goBackToList),f=S(b=>b.setScreen),g=S(b=>b.setFocus),h=S(b=>b.focus),w=We(b=>b.setJustAuthenticated),I=We(b=>b.justAuthenticated),{loadStarterKits:R,installSelected:B}=Qd(),P=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),P.current||(P.current=true,$r("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let A=useCallback(async()=>{let b=M.getState().selectedStarterKit;if(b){let F=await X();F&&await Ut({...F,starterKit:b.slug});}E(v.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Lr()}).catch(()=>{});let{successCount:$}=M.getState();E(v.CLI_ONBOARDING_COMPLETED,{duration_ms:ir(),tools_installed_count:$}).catch(()=>{}),w(false),g("verify"),f("verify");},[w,g,f]),_=useCallback(()=>{m(),B();},[m,B]),j=useCallback(()=>{R();},[R]),fe=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((b,$)=>{if($.escape)ts("esc"),fe();else if($.upArrow&&r>0)n(r-1);else if($.downArrow&&r<t.length-1)n(r+1);else if($.return&&t.length>0){let F=Lr();o(t[r]),$r("kit_display"),E(v.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:F}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((b,$)=>{let F=ep(b,$);if(F.cursorDelta!==0){let D=i+F.cursorDelta;D>=0&&D<s.length&&a(D);}if(F.confirm){let D=M.getState().selectedStarterKit;D&&(async()=>(await X())?.starterKit!==D.slug&&E(v.CLI_KIT_ACCEPTED,{bundle_slug:D.slug}).catch(()=>{}))();let ue=Lr();$r("kit_confirmation"),E(v.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:ue}).catch(()=>{});let Xr=Lr();$r("tool_installation"),E(v.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Xr}).catch(()=>{}),l("installing"),B();}if(F.back){let D=M.getState().selectedStarterKit;D&&E(v.CLI_KIT_REJECTED,{bundle_slug:D.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((b,$)=>{if(d===0)return;let F=tp(b,$);if(F.cursorDelta!==0){let D=u+F.cursorDelta;D>=0&&D<=1&&c(D);}F.select&&(u===0?_():A());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(pn,{}),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(np,{onRetry:j}),e==="starterKitDetail"&&jsx(ip,{}),(e==="installing"||e==="summary")&&jsx(lp,{onComplete:A,onRetry:_})]}),jsx(ys,{})]})}var pp=null;function mp(){return pp}async function ni(){let t=Dr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=Z.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await fp(n);(o||s)&&await ct({...r,installedVersion:o,installMethod:s});}}async function fp(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 Pt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Ln(e){let t=await Promise.all(e.map(r=>iS(r)));return pp=t,t}async function iS(e){let t=up(e.versionCommand);t==="permission-denied"&&(aS(e.versionCommand[0]),t=up(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 Pt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ze(e.alias)){let{installedVersion:l,installMethod:u}=await fp(e);await ct({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function up(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 aS(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=me__default.realpathSync(r),{mode:o}=me__default.statSync(n);me__default.chmodSync(n,o|73);}catch{}}function uS(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 Sp(e,t){let[r,n]=useState(()=>uS(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let I=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),R=w.availableStrategies[(I+1)%w.availableStrategies.length];n(B=>B.map(P=>P.module.alias===w.module.alias?{...P,selectedStrategy:R}:P));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}function Ip({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}=Sp(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(Xe,{itemName:m,actions:d,onAction:c,onClose:u})]})}var gS=/^https?:\/\/.+/;function bp({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&&gS.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 yS(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 Ep(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=yS(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 dr(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}}function Tp({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ud,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function $p({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=Ep(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Or().catch(()=>{}),n("list");let w=Q().some(I=>I.name===te);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,I)=>{I.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,g=a-f,h=[];return g>0&&h.push(jsxs(Text,{color:"green",children:[g," installed"]},"i")),f>0&&h.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),u>0&&h.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(Tp,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((w,I,R)=>(R>0&&w.push(jsx(Text,{children:" | "},`sep-${R}`)),w.push(I),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Mp(){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(gc(p)){Or().catch(()=>{}),l("list");let g=Q().some(h=>h.name===te);u(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=mp();if(p){c(p);return}Ln(Z).then(c).catch(()=>{n([]),t("selection");});},[c]);let d=useCallback(p=>{s(p);let f=p.some(g=>g.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Ip,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(bp,{onConfirm:m}),e==="installation"&&jsx($p,{confirmedItems:o,customUrl:i})]})}var CS=x("ClaudeMdSuggestion"),kS=[`Install ${te}`,"Skip for now"],AS=["Retry","Skip for now"];function Dp(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{E(v.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,E(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ke(te),o("installed");}catch(m){if(m instanceof Be){o("installed");return}CS.warn(`Failed to install ${te}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?AS:kS;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(pn,{}),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(_p,{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(ud,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",te,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",te," 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:["/",te]})]}),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 ",te]}),jsx(_p,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function _p({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 RS=promisify(execFile),li="@ciandt-flow/cli";async function Op(){let e=se;if(Ua.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:li};try{let t=await fetch(`https://registry.npmjs.org/${li}/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:li}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:li}}}async function ci(e){try{return await RS(Nt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function _S(e){let t=ze(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Pt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await ct({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Up(e){let t=await _S(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 Np(e,t){let r=ze(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Pt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ct({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Bp(e){let r=ze(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Fp(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...Z.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([Op(),Ln(Z),Promise.all(Z.map(l=>Up(l)))]);if(ni(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await ci(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=Z.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 Np(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:Bp(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Or(),t(l=>({...l,outcome:"done"}));}catch{await Or(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function FS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(ud,{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 jS({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 jp(){let{outcome:e,items:t}=Fp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=Q().some(i=>i.name===te);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(FS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(jS,{outcome:e})})]})}var HS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Kp=10;function Vp(){let[e,t]=useState(ki());useEffect(()=>Nl(()=>{t([...ki()]);}),[]);let r=e.slice(-Kp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Kp,") \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:HS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var XS=x("app"),qS={auth:Cc,starterKitSetup:cp,moduleSetup:Mp,claudeMdSuggestion:Dp,verify:jp,main:Yd};function Gp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Qn(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Wp(){E(v.CLI_SESSION_STARTED,{cli_version:se,os:process.platform,node_version:process.version,duration_ms:ir(),interface:"tui"}).catch(()=>{});}async function Xp(){let e=await X();if(e&&mc()&&await nr()){e.customUrl&&St(e.customUrl);let{clientSecret:n,...o}=e;We.getState().setCredentials(o),Wp(),Qn(e);return}if(!e){Gp();return}try{e.customUrl&&St(e.customUrl),await xt();}catch(n){XS.debug(`Token validation failed: ${String(n)}`),Gp();return}Wp();let{clientSecret:t,...r}=e;We.getState().setCredentials(r),Qn(e);}function qp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=qS[r],{pendingExit:o}=ac(),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(Vp,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function cl(e,t={}){let r=os({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return ss(r),await Ut(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var Ie=x("auth");function ul(){Ue.clearFallbackFile(),qo();}var YS=3,Yp=3,dl=` \u2139 The data collected during setup is used solely to improve
117
117
  Flow's internal tools and will not be shared externally.
118
- `;function sr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=u=>{if(u===""){l(),n(new Error("SIGINT"));return}if(u==="\r"||u===`
118
+ `;function Wr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
119
119
  `){l(),process.stdout.write(`
120
- `),r(i);return}if(u==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(i+=u,process.stdout.write(o?"*".repeat(u.length):u));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function NS(){let e=Ur();return process.stdout.write(`
121
- `+k.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
122
- `),(await sr(k.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Op(e,t){try{await nl(e);return}catch(r){if(!(r instanceof Nr))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${Ur()} and retry.`);if(!await NS())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await nl(e,{allowOverwriteMalformed:true});}}async function BS(){if((await sr(k.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await sr(k.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(tn.test(t))return t;process.stderr.write(k.yellow(` \u26A0 ${rn}. Try again.
123
- `));}}async function Up(e){process.stdout.write(k.dim(" Installing flow-ai-obs..."));let{npmFailed:t,initFailed:r,unexpectedError:n}=await qn(e);return t?process.stdout.write(k.yellow(` \u26A0 npm install failed. Please contact Flow support.
124
- `)):n?process.stdout.write(k.yellow(` \u26A0 Unexpected error. Please contact Flow support.
125
- `)):r?process.stdout.write(k.yellow(`
120
+ `),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function ZS(){let e=ar();return process.stdout.write(`
121
+ `+C.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
122
+ `),(await Wr(C.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function pl(e,t,r){try{await cl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof _r))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${ar()} and retry.`);if(!await ZS())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await cl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function QS(){if((await Wr(C.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await Wr(C.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(Zr.test(t))return t;process.stderr.write(C.yellow(` \u26A0 ${Qr}. Try again.
123
+ `));}}async function Zp(e){process.stdout.write(C.dim(" Installing flow-ai-obs..."));let{npmFailed:t,initFailed:r,unexpectedError:n}=await Zn(e);return t?process.stdout.write(C.yellow(` \u26A0 npm install failed. Please contact Flow support.
124
+ `)):n?process.stdout.write(C.yellow(` \u26A0 Unexpected error. Please contact Flow support.
125
+ `)):r?process.stdout.write(C.yellow(`
126
126
  \u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
127
- `)):process.stdout.write(k.green(` done
128
- `)),{initFailed:r}}async function Np(){for(let e=1;e<=Rp;e++)try{return await Ps()}catch{if(e===Rp)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Bp(){let e=await Np();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
129
- `+k.cyan(" ? ")+`Starter Kit:
130
- `),e.forEach((t,r)=>{process.stdout.write(` ${k.cyan(`${r+1})`)} ${y(t.name)}
127
+ `)):process.stdout.write(C.green(` done
128
+ `)),{initFailed:r}}async function ml(){for(let e=1;e<=Yp;e++)try{return await As()}catch{if(e===Yp)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function fl(){let e=await ml();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
129
+ `+C.cyan(" ? ")+`Starter Kit:
130
+ `),e.forEach((t,r)=>{process.stdout.write(` ${C.cyan(`${r+1})`)} ${y(t.name)}
131
131
  `);}),process.stdout.write(`
132
- `);;){let t=(await sr(k.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(k.yellow(` \u26A0 Invalid selection. Please try again.
133
- `));}}async function Fp(e){if(e.plugins.length===0)return process.stdout.write(k.dim(`
132
+ `);;){let t=(await Wr(C.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(C.yellow(` \u26A0 Invalid selection. Please try again.
133
+ `));}}async function gl(e){if(e.plugins.length===0)return process.stdout.write(C.dim(`
134
134
  Starter kit '${y(e.name)}' has no plugins to install.
135
135
  `)),true;process.stdout.write(`
136
136
  Installing ${e.plugins.length} plugins from '${y(e.name)}'...
137
- `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(k.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=US;a++)try{await $e(o),t++,i=!0;break}catch(l){if(l instanceof je){t++,i=true;break}}i?process.stdout.write(k.green(` done
138
- `)):(r++,process.stdout.write(k.red(` failed
139
- `)));}return r===0?process.stdout.write(k.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
140
- `)):process.stdout.write(k.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
141
- `)),r===0}async function jp(){process.stdout.write(`
142
- `),process.stdout.write(k.bold(` Personalize your Claude Code
143
- `)),process.stdout.write(k.dim(` This plugin helps Claude understand your preferences and work style.
137
+ `);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(C.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=YS;a++)try{await ke(o),t++,i=!0;break}catch(l){if(l instanceof Be){t++,i=true;break}}i?process.stdout.write(C.green(` done
138
+ `)):(r++,process.stdout.write(C.red(` failed
139
+ `)));}return r===0?process.stdout.write(C.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
140
+ `)):process.stdout.write(C.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
141
+ `)),r===0}async function hl(){process.stdout.write(`
142
+ `),process.stdout.write(C.bold(` Personalize your Claude Code
143
+ `)),process.stdout.write(C.dim(` This plugin helps Claude understand your preferences and work style.
144
144
 
145
- `));let e=(await sr(k.cyan(" ? ")+`Install ${ie}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){b(I.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(k.dim(`
145
+ `));let e=(await Wr(C.cyan(" ? ")+`Install ${te}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){E(v.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(`
146
146
  You can always install it later from the catalog.
147
- `));return}b(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(k.dim(` Installing ${ie}...`));try{await $e(ie),process.stdout.write(k.green(` done
148
- `));}catch(t){if(t instanceof je)process.stdout.write(k.green(` already installed
149
- `));else {It.warn(`Failed to install ${ie}: ${t instanceof Error?t.message:t}`),process.stdout.write(k.red(` failed
150
- `)),process.stdout.write(k.dim(` You can install it later from the catalog.
147
+ `));return}E(v.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(C.dim(` Installing ${te}...`));try{await ke(te),process.stdout.write(C.green(` done
148
+ `));}catch(t){if(t instanceof Be)process.stdout.write(C.green(` already installed
149
+ `));else {Ie.warn(`Failed to install ${te}: ${t instanceof Error?t.message:t}`),process.stdout.write(C.red(` failed
150
+ `)),process.stdout.write(C.dim(` You can install it later from the catalog.
151
151
  `));return}}process.stdout.write(`
152
152
  `),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
153
- `),process.stdout.write(k.cyan.bold(` /${ie}
153
+ `),process.stdout.write(C.cyan.bold(` /${te}
154
154
  `)),process.stdout.write(` Claude will guide you through the rest.
155
- `);}async function FS(e){if(_p(),e.customUrl!==void 0&&!tn.test(e.customUrl))return process.stderr.write(k.red(` \u2717 ${rn}.
155
+ `);}async function ex(e){if(ul(),e.customUrl!==void 0&&!Zr.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${Qr}.
156
156
  `)),1;process.stdout.write(`
157
- `+Dp+`
158
- `),e.customUrl&&Pt(e.customUrl),It.debug(`[${e.tenant}] Authenticating tenant`);try{await _r(e);}catch(r){let n=y(r instanceof Error?r.message:"unknown error");return It.debug(`[${e.tenant}] Authentication failed: ${n}`),process.stderr.write(k.red(` \u2717 Authentication failed: ${n}
159
- `)),1}let{initFailed:t}=await Up(e.customUrl??null);try{let r;if(e.starterKit){let n=await Np(),o=n.find(s=>s.slug===e.starterKit);if(!o){process.stderr.write(k.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
157
+ `+dl+`
158
+ `),e.customUrl&&St(e.customUrl),Ie.debug(`[${e.tenant}] Authenticating tenant`);try{await sr(e);}catch(r){let n=y(r instanceof Error?r.message:"unknown error");return Ie.debug(`[${e.tenant}] Authentication failed: ${n}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${n}
159
+ `)),1}let{initFailed:t}=await Zp(e.customUrl??null);try{let r;if(e.starterKit){let n=await ml(),o=n.find(s=>s.slug===e.starterKit);if(!o){process.stderr.write(C.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
160
160
  `)),process.stderr.write(` Available starter kits:
161
161
  `);for(let s of n)process.stderr.write(` - ${y(s.slug)} (${y(s.name)})
162
- `);return 1}r=o;}else r=await Bp();return await Op({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:r.slug,customUrl:e.customUrl},!1),await Fp(r),await jp(),It.info(`[${e.tenant}] Authentication successful`),process.stdout.write(k.green(`
163
- \u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${Ur()}.
164
- `)),t&&e.customUrl&&process.stdout.write(k.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(e.customUrl)}.
162
+ `);return 1}r=o;}else r=await fl();return await pl({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:r.slug,customUrl:e.customUrl},!1),await gl(r),await hl(),Ie.info(`[${e.tenant}] Authentication successful`),process.stdout.write(C.green(`
163
+ \u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${ar()}.
164
+ `)),t&&e.customUrl&&process.stdout.write(C.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(e.customUrl)}.
165
165
  `)),process.stdout.write(`
166
- `),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return It.error(`[${e.tenant}] Starter kit setup failed: ${n}`),process.stderr.write(k.red(` \u2717 Starter kit setup failed: ${n}
167
- `)),1}}async function jS(e){_p(),It.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
168
- `),process.stdout.write(Dp+`
169
- `);let t=(await sr(k.cyan(" ? ")+"Client ID: ")).trim(),r=(await sr(k.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await sr(k.cyan(" ? ")+"Tenant: ")).trim();if(!t||!r||!n)return It.error("[auth] Validation failed: all fields are required"),process.stderr.write(k.red(` \u2717 All fields are required
170
- `)),1;let o=e??await BS();o&&Pt(o),It.debug(`[${n}] Authenticating tenant`);try{await _r({clientId:t,clientSecret:r,tenant:n});}catch(a){let l=y(a instanceof Error?a.message:"unknown error");return It.error(`[${n}] Authentication failed: ${l}`),process.stderr.write(k.red(` \u2717 Authentication failed: ${l}
171
- `)),1}let{initFailed:s}=await Up(o),i=await Bp();return await Op({clientId:t,clientSecret:r,tenant:n,starterKit:i.slug,customUrl:o??void 0},!0),await Fp(i),await jp(),It.info(`[${n}] Authentication successful`),process.stdout.write(k.green(`
172
- \u2713 Setup complete. Tenant: ${n}. JWT written to ${Ur()}.
173
- `)),s&&o&&process.stdout.write(k.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(o)}.
166
+ `),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return Ie.error(`[${e.tenant}] Starter kit setup failed: ${n}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${n}
167
+ `)),1}}async function tx(e){ul(),process.stdout.write(`
168
+ `+dl+`
169
+ `);let t=e.jwt.trim(),r;try{r=qn(t);}catch(n){let o=y(n instanceof Error?n.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${o}
170
+ `)),1}Ie.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await sr(r);}catch(n){let o=y(n instanceof Error?n.message:"unknown error");return Ie.error(`[${r.tenant}] Authentication failed: ${o}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${o}
171
+ `)),1}try{let n;if(e.starterKit){let o=await ml(),s=o.find(i=>i.slug===e.starterKit);if(!s){process.stderr.write(C.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
172
+ `)),process.stderr.write(` Available starter kits:
173
+ `);for(let i of o)process.stderr.write(` - ${y(i.slug)} (${y(i.name)})
174
+ `);return 1}n=s;}else n=await fl();return await pl({...r,starterKit:n.slug},!1,t),await gl(n),await hl(),Ie.info(`[${r.tenant}] Authentication successful`),process.stdout.write(C.green(`
175
+ \u2713 Setup complete. Tenant: ${r.tenant}. JWT written to ${ar()}.
176
+
177
+ `)),0}catch(n){if(n instanceof Error&&n.message==="SIGINT")throw n;let o=y(n instanceof Error?n.message:"unknown error");return Ie.error(`[${r.tenant}] Starter kit setup failed: ${o}`),process.stderr.write(C.red(` \u2717 Starter kit setup failed: ${o}
178
+ `)),1}}async function rx(e){ul(),Ie.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
179
+ `),process.stdout.write(dl+`
180
+ `);let t=(await Wr(C.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!t)return Ie.error("[auth] Validation failed: JWT is required"),process.stderr.write(C.red(` \u2717 JWT is required
181
+ `)),1;let r;try{r=qn(t);}catch(i){let a=y(i instanceof Error?i.message:"Invalid JWT");return process.stderr.write(C.red(` \u2717 ${a}
182
+ `)),1}let n=e??await QS();n&&St(n),Ie.debug(`[${r.tenant}] Authenticating tenant`);try{await sr(r);}catch(i){let a=y(i instanceof Error?i.message:"unknown error");return Ie.error(`[${r.tenant}] Authentication failed: ${a}`),process.stderr.write(C.red(` \u2717 Authentication failed: ${a}
183
+ `)),1}let{initFailed:o}=await Zp(n),s=await fl();return await pl({...r,starterKit:s.slug,customUrl:n??void 0},!0,t),await gl(s),await hl(),Ie.info(`[${r.tenant}] Authentication successful`),process.stdout.write(C.green(`
184
+ \u2713 Setup complete. Tenant: ${r.tenant}. JWT written to ${ar()}.
185
+ `)),o&&n&&process.stdout.write(C.yellow(` \u26A0 Custom URL was not written to settings.json \u2014 flow-ai-obs authentication failed for ${y(n)}.
174
186
  `)),process.stdout.write(`
175
- `),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=y(t instanceof Error?t.message:"unknown error");return It.error(`[auth] Unexpected error: ${r}`),process.stderr.write(k.red(` \u2717 Unexpected error: ${r}
176
- `)),1}}async function ol(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return FS({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit,customUrl:e.customUrl});if(e.customUrl!==void 0&&!tn.test(e.customUrl))return process.stderr.write(k.red(` \u2717 ${rn}.
177
- `)),1;try{return await jS(e.customUrl)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
178
- `),130;throw t}}async function KS(){try{return process.stdout.write(`
179
- `),(await sr(k.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(k.yellow(` \u26A0 Logout cancelled
187
+ `),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=y(t instanceof Error?t.message:"unknown error");return Ie.error(`[auth] Unexpected error: ${r}`),process.stderr.write(C.red(` \u2717 Unexpected error: ${r}
188
+ `)),1}}async function yl(e={}){if(e.jwt)return tx({jwt:e.jwt,starterKit:e.starterKit});if(e.clientId&&e.clientSecret&&e.tenant)return ex({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit,customUrl:e.customUrl});if(e.customUrl!==void 0&&!Zr.test(e.customUrl))return process.stderr.write(C.red(` \u2717 ${Qr}.
189
+ `)),1;try{return await rx(e.customUrl)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
190
+ `),130;throw t}}async function nx(){try{return process.stdout.write(`
191
+ `),(await Wr(C.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(C.yellow(` \u26A0 Logout cancelled
180
192
  `)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
181
- `),130;throw e}}async function Kp(e){if(!await ee())return process.stdout.write(k.yellow(` \u26A0 You are not authenticated
182
- `)),0;if(!e){let t=await KS();if(t!==null)return t}try{return await Rl(),process.stdout.write(k.green(` \u2713 Credentials removed successfully
183
- `)),0}catch{return process.stderr.write(k.red(` \u2717 Error removing credentials
184
- `)),1}}async function Vp(){let e=await ee();return e?await dr()?(process.stdout.write(`
185
- `+k.bold(` Authenticated
186
- `)),process.stdout.write(k.dim(" Tenant: ")+y(e.tenant)+`
187
- `),process.stdout.write(k.dim(" Client ID: ")+y(e.clientId)+`
188
- `),process.stdout.write(k.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
189
- `),process.stdout.write(k.dim(" Config: ")+y(await _l())+`
193
+ `),130;throw e}}async function Qp(e){if(!await X())return process.stdout.write(C.yellow(` \u26A0 You are not authenticated
194
+ `)),0;if(!e){let t=await nx();if(t!==null)return t}try{return await Wl(),process.stdout.write(C.green(` \u2713 Credentials removed successfully
195
+ `)),0}catch{return process.stderr.write(C.red(` \u2717 Error removing credentials
196
+ `)),1}}async function em(){let e=await X();return e?await nr()?(process.stdout.write(`
197
+ `+C.bold(` Authenticated
198
+ `)),process.stdout.write(C.dim(" Tenant: ")+y(e.tenant)+`
199
+ `),process.stdout.write(C.dim(" Client ID: ")+y(e.clientId)+`
200
+ `),process.stdout.write(C.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
201
+ `),process.stdout.write(C.dim(" Config: ")+y(await zl())+`
190
202
  `),process.stdout.write(`
191
- `),0):(process.stdout.write(k.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(k.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function VS(e){let t=oe(),r;try{r=await Sr();}catch{r=[];}let n=new Set(t.map(o=>o.name));return b(I.CLI_CATALOG_VIEWED,{interface:q().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(lr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(an(["","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 HS(e){let t=oe(),r=await Sr(),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&&Re(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return b(I.CLI_CATALOG_VIEWED,{interface:q().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(T("All plugins are up to date."),0):e.json?(lr(o),0):(an(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
203
+ `),0):(process.stdout.write(C.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(C.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function ox(e){let t=Q(),r;try{r=await fr();}catch{r=[];}let n=new Set(t.map(o=>o.name));return E(v.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(er(r.map(o=>({...o,installed:n.has(o.name)}))),0):(nn(["","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 sx(e){let t=Q(),r=await fr(),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&&Le(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return E(v.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(k("All plugins are up to date."),0):e.json?(er(o),0):(nn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
192
204
  ${o.length} plugin(s) outdated.
193
- `),0)}async function JS(e){let t=oe();if(b(I.CLI_CATALOG_VIEWED,{interface:q().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return T("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return lr(t),0;let r=[];try{r=await Sr();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=Io.indexOf(s.scope??"user"),l=Io.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return an(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??Ra(s.marketplace);return [s.name??"",s.version??"n/a",en[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",vt(s.installedAt??"")]})),process.stdout.write(`
205
+ `),0)}async function ix(e){let t=Q();if(E(v.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return k("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return er(t),0;let r=[];try{r=await fr();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=vo.indexOf(s.scope??"user"),l=vo.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return nn(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??Ba(s.marketplace);return [s.name??"",s.version??"n/a",Yr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",wt(s.installedAt??"")]})),process.stdout.write(`
194
206
  ${t.length} plugin(s) installed.
195
- `),0}async function Hp(e){if(!await ce())return 1;try{return e.available?await VS(e):e.outdated?await HS(e):await JS(e)}catch(t){return P(t instanceof Error?t.message:"Failed to list plugins."),1}}var ue=x("manage");function ii(e,t){return t?oe().find(r=>r.name===e&&r.scope===t):oe().find(r=>r.name===e)}function GS(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,T(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=sl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function WS(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(wn(e,r.scope));if(!await Mt(`${t}Install external plugin "${i}"?
207
+ `),0}async function tm(e){if(!await ne())return 1;try{return e.available?await ox(e):e.outdated?await sx(e):await ix(e)}catch(t){return T(t instanceof Error?t.message:"Failed to list plugins."),1}}var oe=x("manage");function di(e,t){return t?Q().find(r=>r.name===e&&r.scope===t):Q().find(r=>r.name===e)}function ax(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,k(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=wl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function lx(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(yn(e,r.scope));if(!await Tt(`${t}Install external plugin "${i}"?
196
208
  This will run: ${a}
197
- [y/N] `))return ue.debug(`[${e}] Installation cancelled by user`),r.silent||T(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=sl({text:`${t}Installing ${e}...`}).start());}let s=o?GS(t,o):void 0;try{let i=await fd(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?ze({status:"error",plugin:e,message:a}):P(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Ne({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):ae(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=X(i);return r.silent?ze({status:"error",plugin:e,message:a}):P(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function zS(e,t,r){let n=r.silent?void 0:sl({text:`${t}Installing ${e}...`}).start();if(hn(e))return WS(e,t,r,n);try{let o=await $e(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:c}=fs(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${c})`;}});return n?.stop(),r.silent?Ne({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):ae(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof je)return r.silent?Ne({status:"already_installed",plugin:e,message:o.message}):T(`${t}${o.message}`),{name:e,success:true};let s=X(o);return r.silent?ze({status:"error",plugin:e,message:s}):P(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function XS(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;T(`
198
- Installation summary: ${t} succeeded, ${r} failed`);}async function ai(e,t={}){if(!await ce())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await zS(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?Ne({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):XS(r)),r.some(n=>!n.success)?1:0}async function Jp(e,t){if(!await ce())return 1;if(ue.debug(`[${e}] Looking up installed plugin`),!t.force){let r=ii(e,t.scope);if(!r)return ue.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await Mt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return ue.debug(`[${e}] Uninstall cancelled by user`),T("Operation cancelled."),0}try{return ue.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await oo(e,t.scope),ue.info(`[${e}] Uninstalled successfully`),ae("Plugin removed successfully"),0}catch(r){return ue.error(`[${e}] Failed to uninstall: ${X(r)}`),P(X(r)),1}}async function Gp(e,t={}){if(!await ce())return 1;ue.debug(`[${e}] Looking up installed plugin`);let r=ii(e,t.scope);if(!r)return ue.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return ue.debug(`[${e}] Already enabled, skipping`),T(`${r.name} is already enabled`),0;try{return ue.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await so(e,"enabled",t.scope),ue.info(`[${e}] Enabled successfully`),ae(`${r.name} enabled successfully`),0}catch(n){return ue.error(`[${e}] Failed to enable: ${X(n)}`),P(X(n)),1}}async function Wp(e,t={}){if(!await ce())return 1;ue.debug(`[${e}] Looking up installed plugin`);let r=ii(e,t.scope);if(!r)return ue.error(`[${e}] Plugin is not installed`),P(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return ue.debug(`[${e}] Already disabled, skipping`),T(`${r.name} is already disabled`),0;try{return ue.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await so(e,"disabled",t.scope),ue.info(`[${e}] Disabled successfully`),ae(`${r.name} disabled successfully`),0}catch(n){return ue.error(`[${e}] Failed to disable: ${X(n)}`),P(X(n)),1}}async function zp(e,t,r){r.silent||T(`${t}Updating ${e}...`);try{let n=await Fs(e,r);return r.silent?Ne({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):ae(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof wr)return r.silent?Ne({status:"up_to_date",plugin:e,message:n.message}):T(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=X(n);return r.silent?ze({status:"error",plugin:e,message:o}):P(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function qS(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;T(`
199
- Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function YS(e,t,r){try{let n=await xn(e);Re(t,n.version,r.force)?T(`Would update ${e}: v${t} \u2192 v${n.version}`):T(`${e} is already up to date (v${t})`);}catch(n){return P(X(n)),1}return 0}function ZS(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function QS(e,t,r){let n=t.get(e.name);return n?e.version&&Re(e.version,n,r)?(T(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(T(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(T(`Skipping ${e.name}: not found in catalog`),false)}async function ex(e,t){try{let r=await Sr(),n=ZS(r),o=0;for(let s of e)QS(s,n,t.force)&&o++;o===0&&T("All plugins are up to date");}catch(r){return P(X(r)),1}return 0}async function tx(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await zp(e[n].name,o,t);r.push(s);}return t.silent?Ne({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):qS(r),r.some(n=>!n.success)?1:0}async function Xp(e,t={}){if(!await ce())return 1;if(e){let o=ii(e,t.scope);return o?t.dryRun?YS(e,o.version??"",t):(await zp(e,"",t)).success?0:1:(t.silent?ze({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):P(`Plugin "${e}" is not installed`),1)}let n=oe().filter(o=>o.marketplace===Z);return n.length===0?(t.silent?Ne({status:"empty",message:"No plugins installed"}):T("No plugins installed"),0):t.dryRun?ex(n,t):tx(n,t)}var To=x("cli:bundle");function rx(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function nx(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
209
+ [y/N] `))return oe.debug(`[${e}] Installation cancelled by user`),r.silent||k(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=wl({text:`${t}Installing ${e}...`}).start());}let s=o?ax(t,o):void 0;try{let i=await Md(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ge({status:"error",plugin:e,message:a}):T(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Oe({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):re(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=V(i);return r.silent?Ge({status:"error",plugin:e,message:a}):T(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function cx(e,t,r){let n=r.silent?void 0:wl({text:`${t}Installing ${e}...`}).start();if(gn(e))return lx(e,t,r,n);try{let o=await ke(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=Ss(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${u})`;}});return n?.stop(),r.silent?Oe({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):re(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof Be)return r.silent?Oe({status:"already_installed",plugin:e,message:o.message}):k(`${t}${o.message}`),{name:e,success:true};let s=V(o);return r.silent?Ge({status:"error",plugin:e,message:s}):T(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function ux(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;k(`
210
+ Installation summary: ${t} succeeded, ${r} failed`);}async function pi(e,t={}){if(!await ne())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await cx(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?Oe({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):ux(r)),r.some(n=>!n.success)?1:0}async function rm(e,t){if(!await ne())return 1;if(oe.debug(`[${e}] Looking up installed plugin`),!t.force){let r=di(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await Tt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return oe.debug(`[${e}] Uninstall cancelled by user`),k("Operation cancelled."),0}try{return oe.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await io(e,t.scope),oe.info(`[${e}] Uninstalled successfully`),re("Plugin removed successfully"),0}catch(r){return oe.error(`[${e}] Failed to uninstall: ${V(r)}`),T(V(r)),1}}async function nm(e,t={}){if(!await ne())return 1;oe.debug(`[${e}] Looking up installed plugin`);let r=di(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return oe.debug(`[${e}] Already enabled, skipping`),k(`${r.name} is already enabled`),0;try{return oe.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await ao(e,"enabled",t.scope),oe.info(`[${e}] Enabled successfully`),re(`${r.name} enabled successfully`),0}catch(n){return oe.error(`[${e}] Failed to enable: ${V(n)}`),T(V(n)),1}}async function om(e,t={}){if(!await ne())return 1;oe.debug(`[${e}] Looking up installed plugin`);let r=di(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),T(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return oe.debug(`[${e}] Already disabled, skipping`),k(`${r.name} is already disabled`),0;try{return oe.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await ao(e,"disabled",t.scope),oe.info(`[${e}] Disabled successfully`),re(`${r.name} disabled successfully`),0}catch(n){return oe.error(`[${e}] Failed to disable: ${V(n)}`),T(V(n)),1}}async function sm(e,t,r){r.silent||k(`${t}Updating ${e}...`);try{let n=await Hs(e,r);return r.silent?Oe({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):re(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof mr)return r.silent?Oe({status:"up_to_date",plugin:e,message:n.message}):k(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=V(n);return r.silent?Ge({status:"error",plugin:e,message:o}):T(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function dx(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;k(`
211
+ Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function px(e,t,r){try{let n=await Sn(e);Le(t,n.version,r.force)?k(`Would update ${e}: v${t} \u2192 v${n.version}`):k(`${e} is already up to date (v${t})`);}catch(n){return T(V(n)),1}return 0}function mx(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function fx(e,t,r){let n=t.get(e.name);return n?e.version&&Le(e.version,n,r)?(k(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(k(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(k(`Skipping ${e.name}: not found in catalog`),false)}async function gx(e,t){try{let r=await fr(),n=mx(r),o=0;for(let s of e)fx(s,n,t.force)&&o++;o===0&&k("All plugins are up to date");}catch(r){return T(V(r)),1}return 0}async function hx(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await sm(e[n].name,o,t);r.push(s);}return t.silent?Oe({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):dx(r),r.some(n=>!n.success)?1:0}async function im(e,t={}){if(!await ne())return 1;if(e){let o=di(e,t.scope);return o?t.dryRun?px(e,o.version??"",t):(await sm(e,"",t)).success?0:1:(t.silent?Ge({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):T(`Plugin "${e}" is not installed`),1)}let n=Q().filter(o=>o.marketplace===W);return n.length===0?(t.silent?Oe({status:"empty",message:"No plugins installed"}):k("No plugins installed"),0):t.dryRun?gx(n,t):hx(n,t)}var ko=x("cli:bundle");function yx(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function wx(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
200
212
  Bundle: ${y(e)} (${t.length} artifacts)
201
- `);for(let o of t)process.stdout.write(`${rx(o)}
213
+ `);for(let o of t)process.stdout.write(`${yx(o)}
202
214
  `);process.stdout.write(`
203
215
  ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
204
216
 
205
- `);}async function qp(e){if(!e.trim())return P("Bundle name cannot be empty."),1;if(!await ce())return 1;To.debug(`Fetching bundle "${e}"`);let r;try{r=await Hs(e);}catch(a){return a instanceof $n||a instanceof xo?(P(a.message),1):(P(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(To.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),nx(r.title,n),o.length===0)return P("No artifacts available for installation in this bundle."),1;if(!await Mt(`Install ${o.length} artifact(s)? [Y/n] `))return To.debug("Installation cancelled by user"),0;To.debug(`Starting installation of ${o.length} artifact(s)`);let i=await Os(r,{onProgress:({index:a,total:l,artifact:c,success:u,error:d})=>{let m=y(c.name??c.flowId),p=y(c.type??"unknown"),f=u?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
217
+ `);}async function am(e){if(!e.trim())return T("Bundle name cannot be empty."),1;if(!await ne())return 1;ko.debug(`Fetching bundle "${e}"`);let r;try{r=await Xs(e);}catch(a){return a instanceof An||a instanceof bo?(T(a.message),1):(T(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(ko.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),wx(r.title,n),o.length===0)return T("No artifacts available for installation in this bundle."),1;if(!await Tt(`Install ${o.length} artifact(s)? [Y/n] `))return ko.debug("Installation cancelled by user"),0;ko.debug(`Starting installation of ${o.length} artifact(s)`);let i=await js(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
206
218
  `),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
207
219
  `),a===l&&process.stdout.write(`
208
- `);}});if(To.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&ae(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");P(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");T(`${i.skipped} unavailable: ${a}`);}return 0}var Yp=x("marketplace");function sx(e){return `claude plugin marketplace add ${e}`}async function Zp(e,t){if(!await ce())return 1;let r;try{r=bs(e);}catch(s){let i=X(s);return t.silent?ze({status:"error",source:e,message:i}):P(i),1}Yp.debug(`[marketplace] Adding marketplace source: ${r}`);let n=sx(r);if(!t.force){let s=y(r),i=y(n);if(!await Mt(`Add marketplace "${s}"?
220
+ `);}});if(ko.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&re(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");T(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");k(`${i.skipped} unavailable: ${a}`);}return 0}var lm=x("marketplace");function xx(e){return `claude plugin marketplace add ${e}`}async function cm(e,t){if(!await ne())return 1;let r;try{r=Cs(e);}catch(s){let i=V(s);return t.silent?Ge({status:"error",source:e,message:i}):T(i),1}lm.debug(`[marketplace] Adding marketplace source: ${r}`);let n=xx(r);if(!t.force){let s=y(r),i=y(n);if(!await Tt(`Add marketplace "${s}"?
209
221
  This will run: ${i}
210
- [y/N] `))return Yp.debug("[marketplace] Operation cancelled by user"),T("Operation cancelled."),0}let o=t.silent?void 0:sl({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await Pe(n);return o?.stop(),s.exitCode!==0?(t.silent?ze({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(P(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&T(`stdout: ${s.stdout}`)),1):(t.silent?Ne({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(ae(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&T(s.stdout)),0)}catch(s){o?.stop();let i=X(s);return t.silent?ze({status:"error",source:r,message:i}):P(`Failed to add marketplace "${r}": ${i}`),1}}async function cx(){return await ee()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function ux(){let e=Date.now();try{await Sr();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function dx(){return await dr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function px(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Qp(){process.stdout.write(`
211
- `+k.bold(` FlowSetup CLI Diagnostics
222
+ [y/N] `))return lm.debug("[marketplace] Operation cancelled by user"),k("Operation cancelled."),0}let o=t.silent?void 0:wl({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await Se(n);return o?.stop(),s.exitCode!==0?(t.silent?Ge({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(T(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&k(`stdout: ${s.stdout}`)),1):(t.silent?Oe({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(re(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&k(s.stdout)),0)}catch(s){o?.stop();let i=V(s);return t.silent?Ge({status:"error",source:r,message:i}):T(`Failed to add marketplace "${r}": ${i}`),1}}async function Px(){return await X()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Ex(){let e=Date.now();try{await fr();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 Tx(){return await nr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function Cx(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function um(){process.stdout.write(`
223
+ `+C.bold(` FlowSetup CLI Diagnostics
212
224
 
213
- `));let e=[{name:"Credentials",fn:cx},{name:"Prompt Manager",fn:ux},{name:"Valid Token",fn:dx},{name:"Claude Code",fn:px}],t=true;for(let r of e){let n=await r.fn(),o="",s=k.green;n.passed?o=k.green("[OK] "):(o=k.red("[FAIL]"),s=k.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
225
+ `));let e=[{name:"Credentials",fn:Px},{name:"Prompt Manager",fn:Ex},{name:"Valid Token",fn:Tx},{name:"Claude Code",fn:Cx}],t=true;for(let r of e){let n=await r.fn(),o="",s=C.green;n.passed?o=C.green("[OK] "):(o=C.red("[FAIL]"),s=C.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
214
226
  `);}return process.stdout.write(`
215
- `),t?(process.stdout.write(k.green(` \u2713 All checks passed!
227
+ `),t?(process.stdout.write(C.green(` \u2713 All checks passed!
216
228
 
217
- `)),0):(process.stdout.write(k.red(` \u2717 Some checks failed \u2014 verify your configuration
229
+ `)),0):(process.stdout.write(C.red(` \u2717 Some checks failed \u2014 verify your configuration
218
230
 
219
- `)),1)}un();async function em(e){let t=await ee(),r=pr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Kt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await qc.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}var fx=x("commands:usage"),li=20,tm="EMAIL",rm="MONTHLY CONSUMPTION (USD)",nm="STATUS";function gx(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*li),n=li-r,o=k.green;return t>=90?o=k.red:t>=70&&(o=k.yellow),o("\u2588".repeat(r))+k.dim("\u2591".repeat(n))}function om(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function hx(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?k.green(`\u2299 ${n}`):t==="warning"?k.yellow(`\u26A0 ${n}`):t==="blocked"?k.red("\u2717 Budget limit reached"):k.red(`\u2717 ${n}`)}function yx(e){let t=vt(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 wx(e){try{let t=await qo();if(t?.email)return y(t.email);let r=cn(e);return y(r.email??"")}catch(t){return fx.debug(`JWT email decode failed: ${String(t)}`),""}}async function sm(e){if(!await ce())return 1;let r;try{r=await Et();}catch(g){return P(`Authentication error: ${X(g)}`),1}let n;try{n=await em(r);}catch(g){return P(`Failed to fetch usage data: ${X(g)}`),1}if(e.json)return lr(n),0;let o=await wx(r)||y(n.user_id),s=om(n.consumed_usd),i=om(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,c=Math.max(tm.length,o.length+2),u=Math.max(rm.length,li+2+l.length),d=` ${tm.padEnd(c)} ${rm.padEnd(u)} ${nm}`,m=` ${"\u2500".repeat(c)} ${"\u2500".repeat(u)} ${"\u2500".repeat(nm.length)}`,p=`${k.cyan("\u2022")} ${o.padEnd(c-2)}`,f=`${gx(n.percentage)} ${l.padEnd(u-li-2)}`,h=` ${k.dim("Resets")} ${yx(n.renewal_date)}`;return process.stdout.write(`
220
- `),process.stdout.write(k.dim(d)+`
221
- `),process.stdout.write(k.dim(m)+`
222
- `),process.stdout.write(` ${p} ${f} ${hx(n.status)}
223
- `),process.stdout.write(h+`
231
+ `)),1)}an();async function dm(e){let t=await X(),r=or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Dt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await fu.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}var Ax=x("commands:usage"),mi=20,pm="EMAIL",mm="MONTHLY CONSUMPTION (USD)",fm="STATUS";function $x(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*mi),n=mi-r,o=C.green;return t>=90?o=C.red:t>=70&&(o=C.yellow),o("\u2588".repeat(r))+C.dim("\u2591".repeat(n))}function gm(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function Lx(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?C.green(`\u2299 ${n}`):t==="warning"?C.yellow(`\u26A0 ${n}`):t==="blocked"?C.red("\u2717 Budget limit reached"):C.red(`\u2717 ${n}`)}function Mx(e){let t=wt(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 Rx(e){try{let t=await Qo();if(t?.email)return y(t.email);let r=sn(e);return y(r.email??"")}catch(t){return Ax.debug(`JWT email decode failed: ${String(t)}`),""}}async function hm(e){if(!await ne())return 1;let r;try{r=await xt();}catch(h){return T(`Authentication error: ${V(h)}`),1}let n;try{n=await dm(r);}catch(h){return T(`Failed to fetch usage data: ${V(h)}`),1}if(e.json)return er(n),0;let o=await Rx(r)||y(n.user_id),s=gm(n.consumed_usd),i=gm(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(pm.length,o.length+2),c=Math.max(mm.length,mi+2+l.length),d=` ${pm.padEnd(u)} ${mm.padEnd(c)} ${fm}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(fm.length)}`,p=`${C.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${$x(n.percentage)} ${l.padEnd(c-mi-2)}`,g=` ${C.dim("Resets")} ${Mx(n.renewal_date)}`;return process.stdout.write(`
232
+ `),process.stdout.write(C.dim(d)+`
233
+ `),process.stdout.write(C.dim(m)+`
234
+ `),process.stdout.write(` ${p} ${f} ${Lx(n.status)}
235
+ `),process.stdout.write(g+`
224
236
  `),process.stdout.write(`
225
- `),0}var Ix=["github.com","www.github.com"],bx=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,vx=/^([^@]+)@(.+)$/;function Px(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function il(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 Ex(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=il(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=il(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ci(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Px(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:")&&Ix.includes(r.hostname))return Ex(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(bx);if(s){let i=s[1],a=s[2],l=s[3],c,u=a.match(vx);u&&(a=u[1],c=u[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),c&&(d.skillFilter=c),l){let m=l.replace(/^\//,"");m&&(d.subpath=il(m));}return d}}return {type:"git",url:t}}function ui(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 im(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 ll=new Set(["node_modules",".git","dist","build","__pycache__"]);function cm(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function $x(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function al(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Co(e){try{let t=await readFile(e,"utf-8"),{data:r}=im(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 um(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([al(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!ll.has(a.name)).map(a=>um(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function mi(e,t){let r=[],n=new Set;if(t&&!$x(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await al(o)){let i=await Co(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=join(i,l.name);if(await al(c)){let u=await Co(join(c,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let i=await um(o);for(let a of i){let l=await Co(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function dm(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}var fm=1,Ox={retries:5,minTimeout:50};async function gm(e,t){mkdirSync(dirname(e),{recursive:true});let r=await ug.lock(e+".lock",{realpath:false,retries:Ox});try{return await t()}finally{await r();}}function pm(){return {version:fm,skills:{}}}async function fi(e){let t=Fn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<fm?pm():n}catch{return pm()}}function Ux(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function hm(e,t){let r=Fn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Ux(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
226
- `,"utf-8");}async function ym(e,t,r){let n=Fn(r);await gm(n,async()=>{let o=await fi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await hm(o,r);});}async function wm(e,t){let r=Fn(t);await gm(r,async()=>{let n=await fi(t);e in n.skills&&(delete n.skills[e],await hm(n,t));});}var Sm=x("skillInstaller");async function Hx(e,t,r,n){try{await b(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:q().interfaceType});}catch(o){Sm.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function Jx(e,t){try{await b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:q().interfaceType});}catch(r){Sm.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function Gx(e,t){await cp(e,t,{recursive:true,dereference:true,filter:r=>!ll.has(basename(r))});}async function Wx(e,t,r){let n=tt(e.name),o=Lr(t),s=join(o,n);if(!cm(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 Gx(e.path,s);let a=ui(r)??r.url;return await ym(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 xm(e,t){let r=ci(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 Rt(r.url,r.ref),o=n;let s=await mi(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?dm(s,i):s,l=[],c=r.ref??"latest";for(let u of a){let d=Date.now(),m=await Wx(u,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await Hx(u.name,t.scope,c,p):await Jx(u.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(u=>u.success).length,failed:l.filter(u=>!u.success).length}}finally{n&&await _t(n).catch(()=>{});}}var Zx=x("skills");async function Qx(e){try{await b(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:q().interfaceType});}catch(t){Zx.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function eI(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function tI(e){let t=ci(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return P("Invalid local path."),1;n=t.localPath;}else T(`Fetching skills from ${y(e)}...`),r=await Rt(t.url,t.ref),n=r;let o=await mi(n,t.subpath);if(o.length===0)return T("No skills found in this source."),0;let i=ui(t)??y(e);T(`Found ${o.length} skill(s) in ${i}:
227
- `);for(let a of o){let l=y(a.name),c=y(a.description);process.stdout.write(` ${k.bold(l)} ${k.dim(c)}
237
+ `),0}var Ox=["github.com","www.github.com"],Ux=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Nx=/^([^@]+)@(.+)$/;function Bx(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Sl(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 Fx(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=Sl(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Sl(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function fi(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Bx(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:")&&Ox.includes(r.hostname))return Fx(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(Ux);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(Nx);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=Sl(m));}return d}}return {type:"git",url:t}}function gi(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 ym(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 Il=new Set(["node_modules",".git","dist","build","__pycache__"]);function xm(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Hx(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function xl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Ao(e){try{let t=await readFile(e,"utf-8"),{data:r}=ym(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 Im(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([xl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Il.has(a.name)).map(a=>Im(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function wi(e,t){let r=[],n=new Set;if(t&&!Hx(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await xl(o)){let i=await Ao(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 xl(u)){let c=await Ao(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await Im(o);for(let a of i){let l=await Ao(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function bm(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}var Em=1,Yx={retries:5,minTimeout:50};async function Tm(e,t){mkdirSync(dirname(e),{recursive:true});let r=await bg.lock(e+".lock",{realpath:false,retries:Yx});try{return await t()}finally{await r();}}function vm(){return {version:Em,skills:{}}}async function Si(e){let t=Nn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<Em?vm():n}catch{return vm()}}function Zx(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Cm(e,t){let r=Nn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Zx(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
238
+ `,"utf-8");}async function km(e,t,r){let n=Nn(r);await Tm(n,async()=>{let o=await Si(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Cm(o,r);});}async function Am(e,t){let r=Nn(t);await Tm(r,async()=>{let n=await Si(t);e in n.skills&&(delete n.skills[e],await Cm(n,t));});}var $m=x("skillInstaller");async function sI(e,t,r,n){try{await E(v.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:J().interfaceType});}catch(o){$m.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function iI(e,t){try{await E(v.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(r){$m.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function aI(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Il.has(basename(r))});}async function lI(e,t,r){let n=Qe(e.name),o=Cr(t),s=join(o,n);if(!xm(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 aI(e.path,s);let a=gi(r)??r.url;return await km(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 Lm(e,t){let r=fi(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 Ct(r.url,r.ref),o=n;let s=await wi(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?bm(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await lI(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await sI(c.name,t.scope,u,p):await iI(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 kt(n).catch(()=>{});}}var mI=x("skills");async function fI(e){try{await E(v.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:J().interfaceType});}catch(t){mI.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function gI(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function hI(e){let t=fi(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return T("Invalid local path."),1;n=t.localPath;}else k(`Fetching skills from ${y(e)}...`),r=await Ct(t.url,t.ref),n=r;let o=await wi(n,t.subpath);if(o.length===0)return k("No skills found in this source."),0;let i=gi(t)??y(e);k(`Found ${o.length} skill(s) in ${i}:
239
+ `);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${C.bold(l)} ${C.dim(u)}
228
240
  `);}return process.stdout.write(`
229
- `),0}catch(n){return n instanceof br?P(n.message):P(n instanceof Error?n.message:String(n)),1}finally{r&&await _t(r).catch(()=>{});}}function rI(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);ae(`${n} installed ${k.dim(`\u2192 ${o}/`)}`);}else P(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
230
- `);let t=e.source;e.installed>0&&T(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&P(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?T("No skills found in this source."):e.results.length===0&&e.discovered>0&&T(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function bm(e,t){if(t.list)return tI(e);let r=t.global?"global":"project";try{let n=await xm(e,{scope:r,skillFilter:t.skill,yes:t.yes});return rI(n),n.failed>0?1:0}catch(n){return n instanceof br?P(n.message):P(n instanceof Error?n.message:String(n)),1}}async function vm(e){let t=Lr(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 Co(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 Pm(e){let t=e.global?"global":"project",r=await vm(t),n=await fi(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[tt(i.name)]?.source}));return lr(s),0}if(r.length===0)return T(`No skills installed (${t==="global"?"global":"project"} scope).`),0;T(`${t==="global"?"Global":"Project"} skills (${r.length}):
231
- `);for(let s of r){let i=n.skills[tt(s.name)]?.source,a=y(s.name),l=y(s.description),c=l.length>80?l.slice(0,77)+"...":l,u=i?k.dim(` (${i})`):"";process.stdout.write(` ${k.bold(a)}${u}
232
- `),process.stdout.write(` ${k.dim(c)}
241
+ `),0}catch(n){return n instanceof yr?T(n.message):T(n instanceof Error?n.message:String(n)),1}finally{r&&await kt(r).catch(()=>{});}}function yI(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);re(`${n} installed ${C.dim(`\u2192 ${o}/`)}`);}else T(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
242
+ `);let t=e.source;e.installed>0&&k(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&T(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?k("No skills found in this source."):e.results.length===0&&e.discovered>0&&k(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function Rm(e,t){if(t.list)return hI(e);let r=t.global?"global":"project";try{let n=await Lm(e,{scope:r,skillFilter:t.skill,yes:t.yes});return yI(n),n.failed>0?1:0}catch(n){return n instanceof yr?T(n.message):T(n instanceof Error?n.message:String(n)),1}}async function _m(e){let t=Cr(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 Ao(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 Dm(e){let t=e.global?"global":"project",r=await _m(t),n=await Si(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[Qe(i.name)]?.source}));return er(s),0}if(r.length===0)return k(`No skills installed (${t==="global"?"global":"project"} scope).`),0;k(`${t==="global"?"Global":"Project"} skills (${r.length}):
243
+ `);for(let s of r){let i=n.skills[Qe(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?C.dim(` (${i})`):"";process.stdout.write(` ${C.bold(a)}${c}
244
+ `),process.stdout.write(` ${C.dim(u)}
233
245
 
234
- `);}return 0}async function Em(e,t){let r=t.global?"global":"project";if(!e){let i=await vm(r);if(i.length===0)return T("No skills installed."),0;T("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
246
+ `);}return 0}async function Om(e,t){let r=t.global?"global":"project";if(!e){let i=await _m(r);if(i.length===0)return k("No skills installed."),0;k("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
235
247
  `);return process.stdout.write(`
236
- `),T("Specify a skill name to remove: flow skills remove <name>"),1}let n=tt(e),o=Lr(r),s=join(o,n);try{await stat(s);}catch{return P(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await eI(`Remove skill "${y(n)}"?`))return T("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await wm(n,r),await Qx(n),ae(`Skill "${y(n)}" removed.`),0}catch(i){return P(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var gi=x("transfer"),ul=1;function nI(e){return e.marketplace&&e.marketplace!==Z?`${e.name}@${e.marketplace}`:e.name}function oI(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&T(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),T(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function km(e){let t=we__default.resolve(e.output);try{let r=oe(),n={version:ul,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 Se__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),ae(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=X(r);return gi.error(`Export failed: ${n}`),P(`Failed to export plugins: ${n}`),1}}async function Am(e,t={}){if(!await ce())return 1;let r;try{let a=Se__default.readFileSync(we__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return P(`Failed to read import file "${e}": ${X(a)}`),1}if(r.version!==ul)return P(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${ul}`),1;if(!Array.isArray(r.plugins))return P('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return T("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let c=`entry[${a}]`;gi.warn(`Skipping ${c}: missing or invalid name`),o.push({name:c,error:"missing or invalid name"});}else l.type==="mcp"?(gi.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&T(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(oe().map(l=>l.name));oI(n,a);}if(t.dryRun)return T("Dry-run mode: no plugins were installed"),0;if(n.length===0){T(`
237
- Import summary: 0 installed, ${o.length} failed`);for(let a of o)P(` ${a.name}: ${a.error}`);return o.length>0?1:0}T(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=nI(a);gi.debug(`[${a.name}] Installing as "${c}" in scope "${l}"`),await ai([c],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}T(`
238
- Import summary: ${i} installed, ${o.length} failed`);for(let a of o)P(` ${a.name}: ${a.error}`);return o.length>0?1:0}function j(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var iI=x("moduleProxy");function aI(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=wa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function $m(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await b(I.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{iI.warn(`Failed to emit proxy executed event: ${String(s)}`);}),j(o);}async function Mm(e,t){let r=ne.find(o=>o.alias===e);if(!r){P(`Unknown module alias: '${e}'`),j(1);return}if(!await Ct(r.binaryName)){P(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await b(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),j(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await At(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){P(`No supported installation method available for '${e}' on this platform.`),j(1);return}if(await aI("Would you like to install it now? [Y/n] ")){await b(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await hr(r,"inline",s);if(!a.success){P(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),j(1);return}await $m(r,t);}else T(`To install manually, run: flow modules install ${e}`),await b(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),j(1);return}await $m(r,t);}var dI=promisify(execFile);async function pI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await dI(Gt(),["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/${le}`,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 mI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Re(t,r)?"outdated":"installed"}async function dl(){let e=await Promise.all(ne.map(async t=>{let[r,n]=await Promise.all([Ct(t.binaryName),pI(t)]),s=qe(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=mI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return an(["Name","Alias","Version","Status","Platform"],e),0}async function Dm(e){let t=ne.find(i=>i.alias===e);if(!t)return P(`Unknown module alias: '${e}'`),1;let[r]=await Mn([t]);if(r.alreadyInstalled){let i=qe(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return T(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?P(`Module ${t.name} is not supported on ${process.platform}.${a}`):P(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=sl({text:`Installing ${t.name}...`}).start(),s;try{s=await hr(t,"on_demand",n);}finally{o.stop();}return s.success?(ae(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(P(s.error?.message??"Installation failed"),1)}async function Rm(e,t){let r=sl({text:`Updating ${e.name}...`}).start(),n;try{n=await ls(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 Om(e){if(e!==null){let n=ne.find(i=>i.alias===e);if(!n)return P(`Unknown module alias: '${e}'`),1;let o=qe(n.alias);return o?.installMethod?await Rm(n,o.installedVersion??"unknown")==="error"?1:0:(P(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Br().filter(n=>n.installMethod!==null);if(t.length===0)return T("No installed modules to update."),0;let r=0;for(let n of t){let o=ne.find(i=>i.alias===n.alias);if(!o)continue;await Rm(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function Um(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${le}`,"-V, --version","Display the CLI version").addHelpText("after",`
248
+ `),k("Specify a skill name to remove: flow skills remove <name>"),1}let n=Qe(e),o=Cr(r),s=join(o,n);try{await stat(s);}catch{return T(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await gI(`Remove skill "${y(n)}"?`))return k("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Am(n,r),await fI(n),re(`Skill "${y(n)}" removed.`),0}catch(i){return T(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var xi=x("transfer"),vl=1;function wI(e){return e.marketplace&&e.marketplace!==W?`${e.name}@${e.marketplace}`:e.name}function SI(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&k(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),k(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function Bm(e){let t=pe__default.resolve(e.output);try{let r=Q(),n={version:vl,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 me__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),re(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=V(r);return xi.error(`Export failed: ${n}`),T(`Failed to export plugins: ${n}`),1}}async function Fm(e,t={}){if(!await ne())return 1;let r;try{let a=me__default.readFileSync(pe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return T(`Failed to read import file "${e}": ${V(a)}`),1}if(r.version!==vl)return T(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${vl}`),1;if(!Array.isArray(r.plugins))return T('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return k("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}]`;xi.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(xi.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&k(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(Q().map(l=>l.name));SI(n,a);}if(t.dryRun)return k("Dry-run mode: no plugins were installed"),0;if(n.length===0){k(`
249
+ Import summary: 0 installed, ${o.length} failed`);for(let a of o)T(` ${a.name}: ${a.error}`);return o.length>0?1:0}k(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",u=wI(a);xi.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await pi([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}k(`
250
+ Import summary: ${i} installed, ${o.length} failed`);for(let a of o)T(` ${a.name}: ${a.error}`);return o.length>0?1:0}function U(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var II=x("moduleProxy");function bI(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=Pa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function jm(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await E(v.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{II.warn(`Failed to emit proxy executed event: ${String(s)}`);}),U(o);}async function Vm(e,t){let r=Z.find(o=>o.alias===e);if(!r){T(`Unknown module alias: '${e}'`),U(1);return}if(!await bt(r.binaryName)){T(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await E(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),U(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Pt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){T(`No supported installation method available for '${e}' on this platform.`),U(1);return}if(await bI("Would you like to install it now? [Y/n] ")){await E(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await dr(r,"inline",s);if(!a.success){T(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),U(1);return}await jm(r,t);}else k(`To install manually, run: flow modules install ${e}`),await E(v.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),U(1);return}await jm(r,t);}var TI=promisify(execFile);async function CI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await TI(Nt(),["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/${se}`,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 kI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Le(t,r)?"outdated":"installed"}async function Pl(){let e=await Promise.all(Z.map(async t=>{let[r,n]=await Promise.all([bt(t.binaryName),CI(t)]),s=ze(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=kI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return nn(["Name","Alias","Version","Status","Platform"],e),0}async function Gm(e){let t=Z.find(i=>i.alias===e);if(!t)return T(`Unknown module alias: '${e}'`),1;let[r]=await Ln([t]);if(r.alreadyInstalled){let i=ze(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return k(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?T(`Module ${t.name} is not supported on ${process.platform}.${a}`):T(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=wl({text:`Installing ${t.name}...`}).start(),s;try{s=await dr(t,"on_demand",n);}finally{o.stop();}return s.success?(re(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(T(s.error?.message??"Installation failed"),1)}async function Jm(e,t){let r=wl({text:`Updating ${e.name}...`}).start(),n;try{n=await ps(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function Wm(e){if(e!==null){let n=Z.find(i=>i.alias===e);if(!n)return T(`Unknown module alias: '${e}'`),1;let o=ze(n.alias);return o?.installMethod?await Jm(n,o.installedVersion??"unknown")==="error"?1:0:(T(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Dr().filter(n=>n.installMethod!==null);if(t.length===0)return k("No installed modules to update."),0;let r=0;for(let n of t){let o=Z.find(i=>i.alias===n.alias);if(!o)continue;await Jm(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function zm(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${se}`,"-V, --version","Display the CLI version").addHelpText("after",`
239
251
  Without arguments, opens the interactive interface (TUI).
240
252
  Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
241
253
  Examples:
242
- $ flow setup init`).action(async()=>{let u=await ol();j(u);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
254
+ $ flow setup init`).action(async()=>{let c=await yl();U(c);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
243
255
  Examples:
244
256
  $ flow plugin list
245
257
  $ flow plugin list --available
246
258
  $ flow plugin list --outdated
247
- $ flow plugin list --json`).action(async u=>{let d=await Hp(u);j(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
259
+ $ flow plugin list --json`).action(async c=>{let d=await tm(c);U(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
248
260
  Examples:
249
261
  $ flow plugin install flow-adr-writer
250
262
  $ flow plugin install flow-adr-writer --scope project
@@ -252,11 +264,11 @@ Examples:
252
264
  $ flow plugin install flow-adr-writer --force
253
265
  $ flow plugin install flow-adr-writer --silent
254
266
  $ flow plugin install superpowers@claude-plugins-official
255
- $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(u,d)=>{let m=u.filter(f=>f.trim());if(m.length===0){P("No valid plugin names provided"),j(1);return}Ue("cli",{verbose:d.verbose,silent:d.silent});let p=await ai(m,d);j(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",`
267
+ $ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){T("No valid plugin names provided"),U(1);return}De("cli",{verbose:d.verbose,silent:d.silent});let p=await pi(m,d);U(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",`
256
268
  Examples:
257
269
  $ flow plugin uninstall flow-adr-writer
258
270
  $ flow plugin uninstall flow-adr-writer --scope project
259
- $ flow plugin uninstall startup-pack-ai --force`).action(async(u,d)=>{let m=await Jp(u,d);j(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",`
271
+ $ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await rm(c,d);U(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",`
260
272
  Examples:
261
273
  $ flow plugin update flow-adr-writer
262
274
  $ flow plugin update flow-adr-writer --scope project
@@ -265,78 +277,80 @@ Examples:
265
277
  $ flow plugin update flow-adr-writer --verbose
266
278
  $ flow plugin update flow-adr-writer --silent
267
279
  $ flow plugin update
268
- $ flow plugin update --dry-run`).action(async(u,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await Xp(u??null,d);j(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",`
280
+ $ flow plugin update --dry-run`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await im(c??null,d);U(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",`
269
281
  Examples:
270
282
  $ flow plugin enable flow-adr-writer
271
- $ flow plugin enable flow-adr-writer --scope project`).action(async(u,d)=>{Ue("cli");let m=await Gp(u,d);j(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",`
283
+ $ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{De("cli");let m=await nm(c,d);U(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",`
272
284
  Examples:
273
285
  $ flow plugin disable flow-adr-writer
274
- $ flow plugin disable flow-adr-writer --scope project`).action(async(u,d)=>{Ue("cli");let m=await Wp(u,d);j(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
286
+ $ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{De("cli");let m=await om(c,d);U(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
275
287
  Examples:
276
288
  $ flow plugin export
277
- $ flow plugin export --output my-plugins.json`).action(async u=>{let d=await km(u);j(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",`
289
+ $ flow plugin export --output my-plugins.json`).action(async c=>{let d=await Bm(c);U(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",`
278
290
  Examples:
279
291
  $ flow plugin import flow-plugins.json
280
292
  $ flow plugin import flow-plugins.json --scope user
281
293
  $ flow plugin import flow-plugins.json --force
282
294
  $ flow plugin import flow-plugins.json --dry-run
283
- $ flow plugin import flow-plugins.json --diff`).action(async(u,d)=>{let m=await Am(u,d);j(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",`
295
+ $ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Fm(c,d);U(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",`
284
296
  Examples:
285
297
  $ flow plugin marketplace add anthropics/claude-code
286
298
  $ flow plugin marketplace add https://github.com/owner/repo
287
299
  $ flow plugin marketplace add anthropics/claude-code --force
288
- $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(u,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await Zp(u,d);j(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",`
300
+ $ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await cm(c,d);U(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",`
289
301
  Examples:
290
302
  $ flow mcp add notion --transport http https://mcp.notion.com/mcp
291
303
  $ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
292
304
  $ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
293
- $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(u,d,m)=>{Ue("cli",{verbose:m.verbose,silent:m.silent});let p=await Sd(u,d,m);j(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",`
305
+ $ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{De("cli",{verbose:m.verbose,silent:m.silent});let p=await Ud(c,d,m);U(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",`
294
306
  Examples:
295
307
  $ flow mcp remove notion
296
308
  $ flow mcp remove notion --scope project
297
- $ flow mcp remove playwright-mcp --force`).action(async(u,d)=>{Ue("cli",{verbose:d.verbose,silent:d.silent});let m=await xd(u,d);j(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
309
+ $ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{De("cli",{verbose:d.verbose,silent:d.silent});let m=await Nd(c,d);U(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("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
298
310
  Examples:
299
311
  $ flow auth login
312
+ $ flow auth login --jwt <token>
313
+ $ flow auth login --jwt <token> --starter-kit dev
300
314
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
301
315
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
302
316
  $ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --custom-url https://tenant.ciandt.com
303
- $ flow auth login --verbose`).action(async u=>{Ue("cli",{verbose:u.verbose});let d=await ol(u);j(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
317
+ $ flow auth login --verbose`).action(async c=>{De("cli",{verbose:c.verbose});let d=await yl(c);U(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
304
318
  Examples:
305
319
  $ flow auth logout
306
- $ flow auth logout --force`).action(async u=>{let d=await Kp(u.force);j(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
320
+ $ flow auth logout --force`).action(async c=>{let d=await Qp(c.force);U(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
307
321
  Examples:
308
- $ flow auth status`).action(async()=>{let u=await Vp();j(u);}),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",`
322
+ $ flow auth status`).action(async()=>{let c=await em();U(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
309
323
  Examples:
310
324
  $ flow skills add vercel-labs/agent-skills
311
325
  $ flow skills add owner/repo -g
312
326
  $ flow skills add owner/repo --skill pr-review commit
313
327
  $ flow skills add ./local/skills -y
314
- $ flow skills add owner/repo --list`).action(async(u,d)=>{let m=await bm(u,d);j(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
328
+ $ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await Rm(c,d);U(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
315
329
  Examples:
316
330
  $ flow skills list
317
331
  $ flow skills list -g
318
- $ flow skills list --json`).action(async u=>{let d=await Pm(u);j(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",`
332
+ $ flow skills list --json`).action(async c=>{let d=await Dm(c);U(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",`
319
333
  Examples:
320
334
  $ flow skills remove pr-review
321
- $ flow skills remove pr-review -g --force`).action(async(u,d)=>{let m=await Em(u,d);j(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",`
335
+ $ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Om(c,d);U(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",`
322
336
  Examples:
323
337
  $ flow bundle install "My React Kit"
324
338
  $ flow bundle install "Squad Setup Bundle"
325
- $ flow bundle install "My React Kit" --verbose`).action(async(u,d)=>{Ue("cli",{verbose:d.verbose});let m=await qp(u);j(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
339
+ $ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{De("cli",{verbose:d.verbose});let m=await am(c);U(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
326
340
  Examples:
327
- $ flow health`).action(async()=>{let u=await Qp();j(u);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
341
+ $ flow health`).action(async()=>{let c=await um();U(c);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
328
342
  Examples:
329
343
  $ flow usage
330
- $ flow usage --json`).action(async u=>{let d=await sm(u);j(d);});let c=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");c.action(async()=>{let u=await dl();j(u);}),c.command("list").description("List available and installed modules").addHelpText("after",`
344
+ $ flow usage --json`).action(async c=>{let d=await hm(c);U(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await Pl();U(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
331
345
  Examples:
332
- $ flow modules list`).action(async()=>{let u=await dl();j(u);}),c.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
346
+ $ flow modules list`).action(async()=>{let c=await Pl();U(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
333
347
  Examples:
334
348
  $ flow modules install metrics
335
- $ flow modules install dashboard`).action(async u=>{let d=await Dm(u);j(d);}),c.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
349
+ $ flow modules install dashboard`).action(async c=>{let d=await Gm(c);U(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",`
336
350
  Examples:
337
351
  $ flow modules update
338
- $ flow modules update metrics`).action(async u=>{let d=await Om(u??null);j(d);}),t.addCommand(c);for(let u of ne)t.command(u.alias).description(u.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Mm(u.alias,d);});return t.hook("preAction",()=>{Zs();}),t}function hI(){return we__default.join(Te__default.homedir(),".claude","settings.json")}function Bm(){let e=hI();try{if(!Se__default.existsSync(e))return !0;let r=JSON.parse(Se__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var bI=x("updateChecker"),vI=promisify(execFile),PI=1440*60*1e3,Fm=3e4;function EI(){let e=process.env.FLOW_HOME??we__default.join(Te__default.homedir(),".flow");return we__default.join(e,"update.lock")}async function jm(e){try{let{stdout:t}=await vI(Gt(),["view",e,"version"],{timeout:Fm,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function TI(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Fm);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 CI(e){return e.versionCheck.type==="npm-registry"?jm(e.versionCheck.package):TI(e.versionCheck.repo)}async function kI(){let e=await jm("@ciandt-flow/cli");return e&&Re(le,e)?(oi({currentVersion:le,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function AI(){let e=Br().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=ne.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<PI)return;let s=await CI(r);try{await pt({...t,lastChecked:new Date().toISOString()});}catch(i){bI.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Re(t.installedVersion,s)&&ls(r,"background").catch(()=>{});}));}async function ml(){let e=Bm();if(e===false)return;let t=EI();Se__default.mkdirSync(we__default.dirname(t),{recursive:true});let r=null;try{r=await ug.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await kI().catch(()=>null);n&&process.stdout.write(`
352
+ $ flow modules update metrics`).action(async c=>{let d=await Wm(c??null);U(d);}),t.addCommand(u);for(let c of Z)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Vm(c.alias,d);});return t.hook("preAction",()=>{ni();}),t}function LI(){return pe__default.join(ve__default.homedir(),".claude","settings.json")}function qm(){let e=LI();try{if(!me__default.existsSync(e))return !0;let r=JSON.parse(me__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var UI=x("updateChecker"),NI=promisify(execFile),BI=1440*60*1e3,Ym=3e4;function FI(){let e=process.env.FLOW_HOME??pe__default.join(ve__default.homedir(),".flow");return pe__default.join(e,"update.lock")}async function Zm(e){try{let{stdout:t}=await NI(Nt(),["view",e,"version"],{timeout:Ym,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function jI(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Ym);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 KI(e){return e.versionCheck.type==="npm-registry"?Zm(e.versionCheck.package):jI(e.versionCheck.repo)}async function VI(){let e=await Zm("@ciandt-flow/cli");return e&&Le(se,e)?(ci({currentVersion:se,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function JI(){let e=Dr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=Z.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<BI)return;let s=await KI(r);try{await ct({...t,lastChecked:new Date().toISOString()});}catch(i){UI.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Le(t.installedVersion,s)&&ps(r,"background").catch(()=>{});}));}async function Tl(){let e=qm();if(e===false)return;let t=FI();me__default.mkdirSync(pe__default.dirname(t),{recursive:true});let r=null;try{r=await bg.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await VI().catch(()=>null);n&&process.stdout.write(`
339
353
  \u26A0 @ciandt-flow/cli v${n} installing in background.
340
354
  Restart flow to apply the update.
341
355
 
342
- `);}await AI().catch(()=>{});}finally{await r().catch(()=>{});}}var LI=x("cli"),fl=Um(async()=>{Ue("tui"),Kl("tui"),Vl(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Hn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Hn("sigterm",t,r).finally(()=>process.exit(143));}),await ml().catch(()=>{}),await eu().catch(t=>{LI.error(`Failed to init catalog registry: ${String(t)}`);}),await Lp();let{waitUntilExit:e}=render(jsx(Mp,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});fl.hook("preAction",async(e,t)=>{t!==fl&&await ml().catch(()=>{});});fl.parse();
356
+ `);}await JI().catch(()=>{});}finally{await r().catch(()=>{});}}var GI=x("cli"),Cl=zm(async()=>{De("tui"),rc("tui"),nc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Kn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Kn("sigterm",t,r).finally(()=>process.exit(143));}),await Tl().catch(()=>{}),await wu().catch(t=>{GI.error(`Failed to init catalog registry: ${String(t)}`);}),await Xp();let{waitUntilExit:e}=render(jsx(qp,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Cl.hook("preAction",async(e,t)=>{t!==Cl&&await Tl().catch(()=>{});});Cl.parse();