@ciandt-flow/cli 2.2.1-beta.241 → 2.2.1-beta.242
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.
- package/dist/index.js +26 -26
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {execa}from'execa';import
|
|
2
|
+
import {execa}from'execa';import Pc,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Jf,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as Hr from'crypto';import {randomUUID,createHash}from'crypto';import*as me from'fs';import me__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as de from'path';import de__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as we from'os';import we__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as ea from'readline';import {createInterface}from'readline';import R from'chalk';import Si from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Ef from'jsonwebtoken';import _f from'ink-big-text';import wu from'ink-spinner';import*as ht from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Tg from'proper-lockfile';import Ug from'extract-zip';import {simpleGit}from'simple-git';import ma from'semver';import Ka from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var wm=Object.defineProperty;var ti=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var xm=(e,t)=>{for(var r in t)wm(e,r,{get:t[r],enumerable:true});};function ef(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 Pi(e){if(wl.some(r=>r.test(e)))return true;let t=ef(e);return !!(t&&wl.some(r=>r.test(t)))}function tf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function qr(e,t){let r=tf(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&&Pi(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var wl,Mn=ti(()=>{"use strict";wl=[/^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 Og(){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 bc(){return Ic??=Og(),Ic}var Ic,vc=ti(()=>{"use strict";});var Cc={};xm(Cc,{GitRepoAdapter:()=>nn});function Ec(e,t){if(!Ng.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Ng,nn,Ki=ti(()=>{"use strict";vc();Mn();Ng=/^[a-zA-Z0-9_.-]+$/;nn=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(Pi(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Ec(a,"owner"),Ec(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 Pc.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 Pc.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 bc();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 fo="FLOW",Q="flow-skills",ri="flow-cli",En="internal",Kr="external",Vr={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"}},Za={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},ni=new Set(["internal","external"]),Cn={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"}},ee="flow-claude-md-setup",Ke=5,yr=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var Qa=new Set(["skill","mcp","bundle"]),w=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Qa),origins:new Set(ni)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:""}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(Qa)},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(ni)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var go="aes-256-gcm",bm=16,el=16,Tn=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=Hr.randomBytes(bm),n=Hr.createCipheriv(go,this.key,r,{authTagLength:el}),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:go}}decrypt(t){if(t.algorithm!==go)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=Hr.createDecipheriv(go,this.key,Buffer.from(t.iv,"hex"),{authTagLength:el});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var vm=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Pm=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Em=/[A-Za-z0-9+/]{40,}={0,2}/g;function oi(e){return e.replace(vm,"Bearer ***").replace(Pm,"***").replace(Em,"***")}var Sr=".claude",ho=".flow";function tl(e,t){return ii(Q,e,t)}function si(e){return de.join(we.homedir(),Sr,"plugins","marketplaces",Q,"plugins","native",e)}function yo(){return de.join(we.homedir(),Sr,"plugins","marketplaces",Q,".claude-plugin","marketplace.json")}function So(){return de.join(we.homedir(),Sr,"plugins","known_marketplaces.json")}function rl(){return de.join(we.homedir(),Sr,"plugins","marketplaces",Q)}function nl(){return de.join(we.homedir(),ho,"cache","install.lock")}function ol(){return de.join(we.homedir(),ho,"logs","flowsetup.log")}function ii(e,t,r){return de.join(we.homedir(),Sr,"plugins","cache",e,t,r)}function wr(e){let t=e==="global"?we.homedir():process.cwd();return de.join(t,".claude","skills")}function kn(e){let t=e==="global"?we.homedir():process.cwd();return de.join(t,".claude","skills-lock.json")}function wo(e="user"){return e==="project"?de.join(process.cwd(),".opencode","plugins"):de.join(we.homedir(),".config","opencode","plugins")}function sl(){return de.join(we.homedir(),ho,"flow-catalogs.json")}function il(){let e=process.env.FLOW_HOME??de.join(we.homedir(),ho);return de.join(e,"config.json")}function xo(e="user"){return e==="project"||e==="local"?de.join(process.cwd(),Sr,"agents"):de.join(we.homedir(),Sr,"agents")}var Cm=5*1024*1024,Tm=3,Io=class{filePath;constructor(){this.filePath=ol(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
3
|
`;try{me.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=de.dirname(this.filePath);me.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(me.statSync(this.filePath).size>Cm){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=de.dirname(this.filePath),r=de.basename(this.filePath,".log"),n=me.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Tm))me.unlinkSync(de.join(t,o));}catch{}}};var bo=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
|
|
4
4
|
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var vo=class{write(t){process.stdout.write(t.message+`
|
|
5
|
-
`);}};var Po=[],ai=new Set;function li(){return Po}function
|
|
5
|
+
`);}};var Po=[],ai=new Set;function li(){return Po}function al(e){return ai.add(e),()=>{ai.delete(e);}}var Eo=class{write(t){Po.push(t),Po.length>100&&Po.shift();for(let r of ai)r();}};var Jr={debug:0,info:1,warn:2,error:3},Ir={context:"cli",transports:[],minLevel:"warn",debugModules:null};function km(){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 Le(e,t){if(e==="tui"){let r=km();Ir={context:e,transports:[new Eo,new Io],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Ir={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Ir={context:e,transports:[new bo("cli")],minLevel:"debug",debugModules:null}:Ir={context:e,transports:[new vo],minLevel:"info",debugModules:null};}function ll(){return Ir.transports}function cl(e,t){let{debugModules:r,minLevel:n}=Ir;return Ir.context==="tui"&&r&&r!=="all"?r.has(t)?Jr[e]>=Jr.debug:Jr[e]>=Jr.warn:Jr[e]>=Jr[n]}var ul=new Map;function Co(e,t,r){if(!cl(e,t))return;let n={level:e,module:t,message:oi(r),timestamp:new Date};for(let o of ll())o.write(n);}function I(e){let t=ul.get(e);if(t)return t;let r={debug:n=>Co("debug",e,n),info:n=>Co("info",e,n),warn:n=>Co("warn",e,n),error:n=>Co("error",e,n)};return ul.set(e,r),r}var ci=I("encryption"),ui="__encrypted__";function Am(e){return typeof e=="object"&&e!==null&&ui in e&&e[ui]===true}function di(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ui]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return ci.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Am(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return ci.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return ci.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var pi=promisify(execFile),Lm=promisify(exec),nt=I("encryption:macos-keyvault"),Gr=class{static async isAvailable(){try{let{stdout:t}=await Lm("command -v security");return nt.debug(`security binary found at: ${t.trim()}`),!0}catch{return nt.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{nt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await pi("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return nt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return nt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{nt.debug(`Storing secret: service=${t}, account=${r}`),await pi("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),nt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw nt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return nt.debug(`Deleting secret: service=${t}, account=${r}`),await pi("security",["delete-generic-password","-a",r,"-s",t]),nt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return nt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function 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 te(e){process.stdout.write(R.green(` \u2713 ${y(e)}
|
|
6
6
|
`));}function E(e){process.stderr.write(R.red(` \u2717 ${y(e)}
|
|
7
7
|
`));}function C(e){process.stdout.write(R.cyan(` \u2139 ${y(e)}
|
|
8
8
|
`));}function Wr(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(`
|
|
@@ -107,19 +107,19 @@ ${yi}
|
|
|
107
107
|
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw ot.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=hi(t,r);ot.debug(`Deleting secret: target=${n}`);let o=Wm(n),{stdout:s}=await ko(To(o)),i=s.trim()==="True";return ot.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
108
|
`)[0]:"unknown error";return ot.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var zm=32,Xm="flow-plugins-cli-fallback",wi="flow-plugins-cli-fallback",qm={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 Ym(){let e=`${we.hostname()}${we.userInfo().username}`;return Hr.scryptSync(e,Xm,zm)}function Zm(){let e=Ym(),t=new Tn(e),r=di(t);return new Si({projectName:wi,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var $o=null;function Ao(){return $o||($o=Zm()),$o}var _e=class{warned=false;async getSecret(t,r){return Ao().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=qm[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;}Ao().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ao(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Ao().path}static hasExistingData(){try{let t=new Si({projectName:wi});return me.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Si({projectName:wi});me.rmSync(t.path,{force:!0});}catch{}$o=null;}};async function xi(){if(_e.hasExistingData())return new _e;switch(process.platform){case "darwin":return await Gr.isAvailable()?new Gr:new _e;case "linux":return await Yt.isAvailable()?new Yt:await Yt.ensureInstalled()?new Yt:new _e;case "win32":return await Xr.isAvailable()?new Xr:new _e;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Qm=I("config:credentials"),Mt="flow-plugins-cli",Ii="credentials",bi="token-cache",vi="user-info",Ro=null;async function Zt(){return Ro||(Ro=xi()),Ro}function _o(){Ro=null;}async function re(){let t=await(await Zt()).getSecret(Mt,Ii);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Lt(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 Qm.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Zt()).setSecret(Mt,Ii,JSON.stringify(e));}async function fl(){let e=await Zt();await e.deleteSecret(Mt,Ii),await e.deleteSecret(Mt,bi),await e.deleteSecret(Mt,vi);}async function gl(){return (await Zt()).getStoragePath()}async function hl(e){await(await Zt()).setSecret(Mt,bi,JSON.stringify(e));}async function Do(){let t=await(await Zt()).getSecret(Mt,bi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Oo(e){await(await Zt()).setSecret(Mt,vi,JSON.stringify(e));}async function yl(){let t=await(await Zt()).getSecret(Mt,vi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Qt(){let e=await Do();return e?new Date(e.expiresAt)>new Date:false}function No(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")}}Mn();var Ei=I("api:auth");function of(e){if(!yr.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var wl={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 sf(e){if(e instanceof HTTPError){let t=e.response.status;Ei.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&wl[r]?new Error(wl[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?(Ei.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Ei.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function br(e){let t=qr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");of(e.tenant);let r;try{r=await vc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await sf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Lt(e),await hl({accessToken:r.access_token,expiresAt:n});let o=No(r.access_token);await Oo({sub:o.sub,name:o.name,email:o.email});}var xl=I("lib:tokenProvider");async function er(){if(await Qt()){let n=await Do();if(n)return n.accessToken}xl.debug("Token expired or missing, re-authenticating...");let t=await re();if(!t)throw new Error("Not authenticated. Run: flow auth login");_e.clearFallbackFile(),_o(),await br(t);let r=await Do();if(!r)throw new Error("Authentication succeeded but token was not persisted");return xl.debug("Token refreshed successfully"),r.accessToken}Mn();var Bo=I("api:metrics");function Il(){return qr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function bl(e,t,r){return vc.post(e,{json:t,headers:r})}async function lf(e){let t=await yl();if(t)return t;let r=No(e),n={sub:r.sub,name:r.name,email:r.email};return await Oo(n),n}async function v(e,t){let r=await er(),n=await lf(r),o=await re();if(!yr.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:ri,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await bl(Il(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Bo.debug(`Metrics event sent: ${e}`);}catch(i){throw Bo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function vl(e,t,r){try{let n=r&&yr.test(r)?r:"unknown",o={action:e,booster:ri,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await bl(Il(),o,{FlowTenant:n}),Bo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Bo.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={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 cf={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},st={...cf};function Pl(e){let t=Date.now();st={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function vr(e){st.currentStep=e,st.stepStart=Date.now();}function j(){return {...st}}function Rt(){return st.sessionStart===0?0:Date.now()-st.sessionStart}function Pr(){return st.stepStart===0?0:Date.now()-st.stepStart}function El(){st.tuiSessionStart=Date.now();}function Cl(){return st.tuiSessionStart===0?0:Date.now()-st.tuiSessionStart}var uf=3e3,df=I("abandonment");async function Uo(e){let{currentStep:t,sessionStart:r}=j();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Rt()};try{await Promise.race([v(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),uf))]);}catch(o){df.warn(`Abandonment event failed: ${String(o)}`);}}function Tl(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var pf=3e3,mf=I("session-end");async function Rn(e,t,r){let n=Cl(),s=[v(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Uo(e));try{await Tl(Promise.all(s).then(()=>{}),pf);}catch(i){mf.warn(`Session end event failed: ${String(i)}`);}}var yf=2e3;function Al(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=w(l=>l.pendingExit),o=w(l=>l.setPendingExit),s=w(l=>l.activeTab),i=w(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Rn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},yf);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var If=16;function $l({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(If)}),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 Je=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 Er(){return de__default.join(we__default.homedir(),".claude","settings.json")}function Nn(){let e=Er();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 Fo(e){let t=Er();me__default.mkdirSync(de__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 Ll(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 ki(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 Cf=3600,Cr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Tf(e){return Ef.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Cf})}function jo(e,t={}){let r=Nn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Cr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?ki(r.settings):null,s=Tf(e),i=Ll(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function Ko(e){Fo(e.merged);}function Rl(){let e=Nn();return e.status!=="ok"?false:ki(e.settings)!==null}var _l="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(_l=e.version);}catch{}var ne=_l;function Mf(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 ft=["clientId","clientSecret","tenant"],Lf={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function Ol(){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=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:S}=Je(),P=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),T=()=>{d("fields"),p(null),t(M=>({...M,clientSecret:""})),n("clientSecret");},k=async()=>{g.current=true;let M=P();try{await Lt(M);}catch(U){a(U instanceof Error?U.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:x,...A}=M;h(A),S(true),v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{}),Bn({starterKit:A.starterKit});},$=async M=>{g.current=true;let x=P();try{Ko(M),await Lt(x);}catch(H){a(H instanceof Error?H.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:A,...U}=x;h(U),S(true),v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{}),Bn({starterKit:U.starterKit});},O=M=>{try{return jo(P(),{allowOverwriteMalformed:M})}catch(x){return x instanceof Cr?(d("malformedConfirm"),null):(a(x instanceof Error?x.message:"Failed to read settings.json"),d("fields"),null)}};useInput((M,x)=>{if(!(l||g.current)){if(u==="preview"){x.return&&m?$(m):x.escape?k():M==="q"&&T();return}if(u==="malformedConfirm"){if(x.return){let A=O(true);A&&(p(A),$(A));}else x.escape&&T();return}if(x.shift&&x.tab){let A=ft.indexOf(r);A>0&&n(ft[A-1]);}else if(x.tab){let A=ft.indexOf(r);A<ft.length-1&&n(ft[A+1]);}else if(x.return)if(r==="tenant")V();else {let A=ft.indexOf(r);n(ft[A+1]);}}},{isActive:true});let V=async()=>{let M={};for(let x of ft)e[x].trim()||(M[x]="This field is required");if(Object.keys(M).length>0){s(M);let x=ft.find(A=>M[A]);x&&n(x);return}c(true),a(null),f.current+=1;try{await br(P());let x=O(!1);x&&(p(x),d("preview"));}catch(x){let A=x instanceof Error?x.message:"Authentication failed";a(A),vl(b.CLI_AUTH_FAILED,{error_code:Mf(x),attempt:f.current},e.tenant.trim()).catch(()=>{}),t(U=>({...U,clientSecret:""}));}finally{c(false);}},ge=M=>x=>{t(A=>({...A,[M]:x})),o[M]&&s(A=>({...A,[M]:void 0}));};return u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \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:[fo," \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:[fo," \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:ft.map(M=>jsx(Box,{marginBottom:1,children:jsx($l,{label:Lf[M],value:e[M],onChange:ge(M),masked:M==="clientSecret",isActive:r===M&&!l,error:o[M]})},M))}),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 Yr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(_f,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ne]})})]})}function Df(){let e=sl();if(!me__default.existsSync(e))return {};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ai=null;function Of(){return Ai===null&&(Ai=Df()),Ai}function tr(){return !!Of().ENABLE_EXPERIMENTAL_BETAS}var jl=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],G=tr()?jl:jl.slice(0,3);function Nf(e){return G.findIndex(t=>t.id===e)}function $i(e,t,r){let n=Nf(r.activeTab);if(t.rightArrow||t.tab){let o=G[(n+1)%G.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=G[(n-1+G.length)%G.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:G[n]?.focus??"list"}]:[]}var Hl={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Jl({outdatedCount:e=0}){let t=w(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:G.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Hl[r]} (${e})`:Hl[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var De=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Wl(){let e=w(i=>i.focus),t=De(i=>i.query),r=De(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 jf=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Vr[e]})),Kf=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Ya[e]}));function zl(){let e=w(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"]})]}),jf.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"]})]}),Kf.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 Xl({type:e}){let{label:t,color:r}=Vr[e];return jsx(Text,{color:r,children:t})}function Zl({origin:e}){return e===En?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Ho=Jf.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(Xl,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Zl,{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 ",qt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Zr({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function tc({items:e,emptyMessage:t}){let r=w(l=>l.selectedIndex);if(e.length===0)return jsx(Zr,{message:t});let n=Math.max(0,r-Math.floor(Ke/2)),o=Math.min(e.length,n+Ke);o===e.length&&(n=Math.max(0,o-Ke));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(Ho,{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 oc({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 ic({groups:e,emptyMessage:t}){let r=w(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(Zr,{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(Ke/2)),c=Math.min(n.length,l+Ke);c===n.length&&(l=Math.max(0,c-Ke));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(oc,{label:p.label,pathHint:p.pathHint},p.key):jsx(Ho,{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 Qf={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function eg({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(Wl,{}),jsx(zl,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Qf[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(ic,{groups:n,emptyMessage:r}):jsx(tc,{items:e,emptyMessage:r})]})}function ac({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=w(l=>l.activeTab),s=w(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(eg,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var ng={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 Jo(){let e=w(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:[ng[e],t?" | Ctrl+D: debug log":""]})})}function lc({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 Go({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Su,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Wo({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 We({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=w(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 Fi=Object.entries(Cn),gc=[...Fi.map(([,e])=>e.actionLabel),"Cancel"],hc=Object.fromEntries(Fi.map(([,e])=>[e.actionLabel,e.description]));function yc(e){let t=Fi.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var hg=I("provider.registry"),yg=3e4,Xo=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+yg}),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"&&hg.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 Sg={user:"global",project:"project",local:"local"};function qo(e){return e?Sg[e]:"global"}var Oe=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},nr=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};Mn();function gt(){return vc.create({prefix:qr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await er();e.headers.set("Authorization",`Bearer ${t}`);let r=await re();r?.tenant&&yr.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var xg=I("catalog.registry"),Yo=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);xg.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 kg={retries:5,minTimeout:50};async function ji(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Tg.lock(e+".lock",{realpath:false,retries:kg});try{return await t()}finally{await r();}}var Zo=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 ji(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 ji(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ji(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 Ag=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function jn(e){if(!e||!Ag.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var $g=/^[^@]+@[^@]+$/;function en(e){return $g.test(e)}function tn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Mg=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Lg(e){if(!Mg.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 rn(e,t){let r=tn(e);Lg(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Rg=/^[\w./:@?&=+#%-]+$/;function Qo(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Rg.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var _g=I("catalog.flow-api"),es=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 gt().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){jn(t);try{return await gt().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 gt().head("v1/plugins/catalog"),_g.debug("ping ok"),!0}catch{return false}}};var ie=new Yo,Dt=new Zo;ie.register(new es);var Cc=false;async function Tc(){if(Cc)return;Cc=true;let e=await Dt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Ki(),Ec));for(let r of e)ie.register(new t(r.id,r.name,r.source));}async function or(){return ie.fetchAll()}async function kc(){return ie.fetchAllWithErrors()}async function on(e){jn(e);try{return await gt().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 Ac(e){jn(e);try{let t=await gt().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function ts(){try{let{profiles:e}=await gt().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 $c(e,t){let r=de.resolve(t);await ht.mkdir(r,{recursive:true});let n=de.join(de.dirname(r),`${randomUUID()}.zip`);try{await ht.writeFile(n,e),await Ug(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=de.resolve(r,o.fileName);if(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=de.normalize(r+de.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(de.resolve(de.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await ht.unlink(n);}catch{}}}async function Vi(e){await ht.rm(e,{recursive:true,force:true});}async function sr(){let e=rl();await ht.mkdir(de.dirname(e),{recursive:true});try{await ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Tg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Kg(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:Q,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Rc(){let e=yo();if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return null}}function Vg(){let e=Rc();if(e)return e;let t=Kg(),r=yo();return me__default.mkdirSync(de__default.dirname(r),{recursive:true}),Hi(t),t}function Hi(e){let t=yo(),r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function Hg(){let e=So(),t={};try{me__default.existsSync(e)&&(t=JSON.parse(me__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[Q])return;t[Q]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:tl(),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 _c(e,t){ir(e.name),Hg();let r=si(e.name);me__default.mkdirSync(de__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=Vg();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}),Hi(n));}function Ji(e){ir(e);let t=si(e);try{me__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Rc();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Hi(r);}var Gg=I("mcpConfigReader"),Wg=500,zg=512;function Xg(){return de__default.join(we__default.homedir(),".claude.json")}function qg(){return de__default.join(process.cwd(),".mcp.json")}function Oc(e){if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return Gg.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gi(e){if(!Kn(e))return {};let t=e.mcpServers;return Kn(t)?t:{}}function Wi(e,t){return Object.keys(e).slice(0,Wg).map(n=>({name:y(n.slice(0,zg)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Bc(){let e=[],t=Xg(),r=Oc(t);if(Kn(r)){let a=r,l=Gi(a);e.push(...Wi(l,"user"));let c=process.cwd();if(Kn(a.projects)){let u=a.projects[c];if(Kn(u)){let d=Gi(u);e.push(...Wi(d,"local"));}}}let n=qg(),o=Oc(n),s=Gi(o);e.push(...Wi(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=I("storage");async function Zg(e,t,r){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:j().interfaceType});}catch(n){ze.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Qg(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:j().interfaceType}).catch(o=>ze.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Yi(){return de__default.join(we__default.homedir(),".claude","plugins","installed_plugins.json")}function eh(){return de__default.join(we__default.homedir(),".claude","plugins")}function Uc(e){let t=de__default.resolve(e),r=de__default.resolve(eh()),n=de__default.resolve(de__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+de__default.sep)||t===r,s=t.startsWith(n+de__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Fc(e="user"){return e==="local"?de__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?de__default.join(process.cwd(),".claude","settings.json"):de__default.join(we__default.homedir(),".claude","settings.json")}function lt(){let e=Yi();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 Zi(){let e=Yi();try{let t=await me__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function th(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function jc(e,t){try{me__default.mkdirSync(de__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 th(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Xe(e){jc(Yi(),e);}function Vn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function rh(e,t){let r=de__default.join(e,".claude-plugin"),n=de__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=de__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 Qi(e="user"){let t=Fc(e);if(!me__default.existsSync(t))return {};try{return JSON.parse(me__default.readFileSync(t,"utf-8"))}catch{return {}}}function Kc(e,t="user"){jc(Fc(t),e);}function nh(e,t){let{name:r,marketplace:n}=Vn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Vn(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 oh(e,t){let{name:r,marketplace:n}=Vn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Vn(i).name===r)[0],o?{key:o,name:r}:null}function zi(e="user"){return Qi(e).enabledPlugins??{}}function Xi(e,t="user"){let r=Qi(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Kc(r,t);}function Hn(e,t,r="user"){let n=Qi(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Kc(n,r);}function sh(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=lt(),t=zi(),r=zi("project"),n=zi("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=Vn(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return sh(p).map(g=>{let h=rh(g.installPath,d),P=(o[g.scope]??t)[c];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:P===false?"disabled":"enabled"}})}),i=Bc(),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 rs(e,t){ze.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=lt(),o=oh(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}`),Uc(l.installPath);let c=de__default.dirname(l.installPath);ze.debug(`[${i}] Removing directory: ${c}`),me__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;Xe({...n,plugins:m}),Xi(s,t),Ji(i);}else n.plugins[s]=u,Xe(n),Xi(s,t);}else {ze.debug(`[${i}] Resolved key: ${s}`);for(let u of a){Uc(u.installPath);let d=de__default.dirname(u.installPath);ze.debug(`[${i}] Removing directory: ${d}`),me__default.rmSync(d,{recursive:!0,force:!0}),Xi(s,u.scope);}Ji(i);let{[s]:l,...c}=n.plugins;Xe({...n,plugins:c});}await Zg(i,a[0].origin??"internal",a[0].type??"skill"),ze.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Jn(e,t,r){ze.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=lt(),{key:s,name:i}=nh(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}`),Hn(s,t==="enabled",l),Qg(i,t,c),ze.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var ih=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ah=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ir(e){if(!ih.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function lh(e){if(!ah.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 ar=I("installer");function ch(e,t){let r=`${e}@${Q}`,o=lt().plugins[r];if(o&&!t)throw new Oe(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function uh(e,t,r){r&&await Vi(t);try{ar.debug(`[${t}] Extracting archive...`),await $c(e,t);}catch(n){throw await Vi(t),n}}function dh(e,t,r,n,o,s="claude-code",i){let a=lt(),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],Xe(a),Hn(e,true,n);}async function ph(e,t,r,n,o,s){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:j().interfaceType});}catch(i){ar.warn(`Failed to send install metrics: ${String(i)}`);}}async function mh(e,t,r,n){try{await v(b.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){ar.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function ve(e,t={}){let r=Date.now(),n=null;try{ar.debug(`[${e}] Acquiring lock...`),n=await sr();let{pluginKey:o,alreadyInstalled:s}=ch(e,t.force);ar.debug(`[${e}] Fetching manifest...`);let i=await on(e);ir(i.name),lh(i.version),ar.debug(`[${e}] Downloading archive...`);let a=await Ac(e),l=t.scope??"user",c=t.type??"skill",u=el(i.name,i.version);await uh(a,u,!!s&&!!t.force),dh(o,u,i.version,l,"internal",t.providerId,c),_c(i,u);let d=Date.now()-r;ar.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:u,duration_ms:d};return t.skipMetrics||await ph(i.name,i.version,d,qo(l),"internal",c),m}catch(o){throw await mh(e,o,"internal",t.type??"skill"),ar.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var fh=I("commands:helpers");async function pe(){if(!await re())return E("Not authenticated. Run: flow auth login"),false;try{await er();}catch(t){return fh.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function yt(e){let t=ea.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 Vc(e){let t=ea.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var sn=I("claudeProxy"),sa="claude ",Hc="flow ",ta=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ra=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";}},gh=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,hh=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,yh=/^(flow|claude)\s+auth\s+login(\s|$)/,Jc=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Gc(e){return Jc.test(e.trim())}function Sh(e){return Jc.exec(e.trim())?.[2]??""}async function Wc(e){let t=Sh(e),r=Date.now();sn.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 ia(n)?new na:n}}function wh(e){zc(e);let t=e.slice(sa.length);if(!gh.test(t))throw new ra(e)}var ns=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},na=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function zc(e){if(!e||!/^claude /.test(e))throw new ta(e)}async function he(e){zc(e);let t=e.slice(sa.length).split(/\s+/).filter(Boolean),r=xh(t);sn.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 sn.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 ia(o)?new ns:o}}function xh(e){return e.length>=3?e[2]:e.join(" ")}function ia(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Ih(e){return e.startsWith(Hc)?sa+e.slice(Hc.length):e}function bh(e){return hh.test(e)||yh.test(e)}function vh(e){let t=0;for(;t<e.length&&bh(e[t]);)t++;return e.slice(t)}var Ph=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Eh(e,t){return !t||e.includes("--scope")||!Ph.test(e)?e:`${e} --scope ${t}`}async function Gn(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=vh(r).map(i=>Ih(i)).map(i=>Eh(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)wh(i);sn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await he(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await he(o[i]),s.exitCode!==0)return s;return s}async function os(e,t,r){let n=tn(e),o=t?.trim();if(!o&&(o=(await Vc(`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=Qo(o),r?.(),sn.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"}`);sn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ia(s)?new ns:s}}var $h=6e4,lr=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 St(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:$h}}).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 lr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new lr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new lr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function wt(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 Rr(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 Lh(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Rh(e){return typeof e=="object"&&e!==null&&e.source==="url"}function _h(e){return typeof e=="object"&&e!==null&&e.source==="github"}function an(e,t){let r=e.source;if(Lh(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(Rh(r))return {cloneUrl:r.url,subPath:"."};if(_h(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 xt=I("claude-code.adapter");function Nh(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=So();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 tu(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=an(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=Nh(e.catalogId,r?.source),i=t.scope??"user",a;o?a=ii(s,e.name,"external"):a=join(wr(i==="user"?"global":"project"),e.name);let l=null;try{ir(e.name),l=await St(n.cloneUrl,n.ref);let c=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(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await Zi(),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],Xe(d),Hn(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return xt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await wt(l).catch(()=>{});}}async function aa(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:qo(n),version:"unknown",duration_ms:t,interface:j().interfaceType});}catch(o){xt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Qc(e,t,r){try{await v(b.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){xt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Bh={async install(e,t){if(e.origin===Kr&&!e.installCommand&&!en(e.name))return tu(e,t);if(e.origin===Kr&&e.installCommand){let r=e.type??"skill",n=await Gn(e.installCommand,t.scope);return n.exitCode===0?(await aa(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Qc(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(en(e.name)){let r=e.type??"skill",n=rn(e.name,t.scope);xt.debug(`[${e.name}] Attempting install: ${n}`);let o=await he(n);if(o.exitCode===0)return await aa(e.name,o.duration_ms,r,t.scope),{success:true};xt.debug(`[${e.name}] First attempt failed, adding marketplace`),await os(e.name,t.marketplaceSource,()=>{});let s=await he(n);return s.exitCode===0?(await aa(e.name,s.duration_ms,r,t.scope),{success:true}):(await Qc(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 ve(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return xt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await rs(e,t);},getInstallPath(e,t){return ""}};function eu(e){return {async install(t,r){if(t.origin===Kr&&!t.installCommand&&!en(t.name))return tu(t,r);if(!t.installCommand)try{let o=await ve(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return xt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}xt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Gn(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function Uh(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 la(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,la(r)]))}function ru(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(la(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(la(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=ru(s,o):r[n]=o;}return r}async function nu(e,t,r,n){let o=await Zi(),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],Xe(o);}var Fh={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=an(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ir(e.name),s=await St(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Uh(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=xo(r);me__default.mkdirSync(l,{recursive:!0});let c=qe(e.name);if(a.length===1)me__default.copyFileSync(a[0],join(l,`${c}.md`));else for(let d of a){let m=qe(basename(d,".md"));me__default.copyFileSync(d,join(l,`${c}--${m}.md`));}let u=a.length===1?join(l,`${c}.md`):l;return await nu(e.name,r,u,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return xt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await wt(s).catch(()=>{});}},async uninstall(e,t){let r=xo(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=lt(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Xe({...s,plugins:l});}else Xe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(xo(t),`${qe(e)}.md`)}},jh={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=an(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ir(e.name),s=await St(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 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=Nn();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=ru(m,c);return Fo({...d,hooks:p}),await nu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return xt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await wt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ss=class{id="claude-code";name="Claude Code";async isAvailable(){return Rr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Bh,skill:eu("skill"),mcp:eu("mcp"),agent:Fh,hook:jh}};function is(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 Vh=new Set(["gh"]),Hh=is(Vh,"use: gh copilot mcp remove <name>"),as=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Rr("gh",["--version"])?Rr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Hh}};var Jh=new Set(["opencode"]),Gh=is(Jh,"use: opencode config remove mcp <name>");function Wh(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 ou(){return {async install(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=an(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await St(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=wo(t.scope??"user"),a=join(s,".opencode","plugins");if(me__default.existsSync(a)){let l=me__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/"};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`),Wh(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 wt(o).catch(()=>{});}},async uninstall(e,t){let r=wo(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(wo(t),`${e}.js`)}}}var ls=class{id="opencode";name="OpenCode";async isAvailable(){return Rr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Gh,skill:ou(),bundle:ou()}};var It=new Xo;It.register(new ss);tr()&&(It.register(new as),It.register(new ls));function su({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(()=>{It.getAvailableProviders(t??"bundle").then(c).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 S=l.find(P=>P.name===h);S?(d(S.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let S=yc(h);S?r(S,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(S=>S.name),"Cancel"];return jsx(We,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(We,{itemName:`${e} \u2014 Choose scope`,actions:gc,descriptions:hc,onAction:f,onClose:g},"scope"):jsx(We,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function au({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=w(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,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:[c.length," artifact",c.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:c.map(f=>{let g=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(We,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ds({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=w(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 uu({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=ds({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(We,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function mu({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ds({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(We,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var un=I("bundle:installer"),fu=/already exists/i;async function ty(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Gc(t)){let r=await Wc(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(fu.test(n))return;throw new Error(n)}}else {let r=await Gn(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(fu.test(n))return;throw new Error(n)}}}async function ry(e,t){try{await v(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){un.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function ny(e,t,r){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){un.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function gu(e,t,r,n){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){un.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function oy(e,t,r,n,o){try{await v(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){un.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function fs(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 ry(i,o.length);let l=[],c=0,u=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){un.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await gu(i,g,h,"unknown artifact type"),r?.({index:p+1,total:u,artifact:f,success:false,error:"unknown artifact type"});continue}try{await ty(f),c++,await ny(i,g,h),r?.({index:p+1,total:u,artifact:f,success:!0});}catch(S){let P=S instanceof Error?S.message:String(S);un.error(`Failed to install artifact "${g}": ${P}`),l.push({name:g,type:h,reason:P}),await gu(i,g,h,P),r?.({index:p+1,total:u,artifact:f,success:false,error:P});}}let d=Date.now()-a,m=l.length;return await oy(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,fs(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(Su,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",r.artifact.name??r.artifact.flowId," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Su,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ae=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:q()})}));function xu({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 ",qt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function Iu({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 ${qt(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((g,h)=>{let S=h===o;return jsxs(Box,{children:[jsx(Text,{color:S?"cyan":void 0,children:S?"\u203A ":" "}),jsx(Text,{bold:S,color:g.danger?"yellow":void 0,dimColor:!S,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function bu(e){return e.adapter.removable!==false?4:2}function vu({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 Eu({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 Cu({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter($=>r.has(`${$.name}@${o}`)),i=t.filter($=>!r.has(`${$.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput(($,O)=>{if(O.escape){n();return}if(O.return){d(a[l]??null);return}if(O.upArrow){c(V=>Math.max(0,V-1));return}O.downArrow&&c(V=>Math.min(a.length-1,V+1));},{isActive:u===null}),u!==null)return jsx(vu,{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(Ke/2)),p=Math.min(a.length,m+Ke);p===a.length&&(m=Math.max(0,p-Ke));let f=a.slice(m,p),g=m,h=a.length-p,S=s.length>0&&m<s.length,P=p>s.length,T=f.filter($=>r.has(`${$.name}@${o}`)),k=f.filter($=>!r.has(`${$.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`:" "})}),S&&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"]}),T.map($=>jsx(Eu,{item:$,isSelected:a.indexOf($)===l,isInstalled:true},$.name))]}),P&&jsxs(Box,{flexDirection:"column",marginTop:S?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"]}),k.map($=>jsx(Eu,{item:$,isSelected:a.indexOf($)===l,isInstalled:false},$.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"})})]})}Ki();var dy=/^https?:\/\/.+/;function py(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function my(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function $u(e){let t=w(h=>h.showNotification),r=w(h=>h.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");},[]),g=useCallback(async()=>{let h=m.current,S=d.current;if(!dy.test(h)){u("URL must start with http:// or https://");return}u(null),o("adding");let P=randomUUID(),T=new nn(P,S,h);try{await T.fetchItems(),await Dt.add({id:P,name:S,source:h}),ie.register(new nn(P,S,h)),r(),e(),t(`Catalog "${S}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(k){let $=py(k)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":my(k)?k.message:k instanceof Error?`Could not reach catalog URL: ${k.message}`:"Failed to validate catalog URL";t($,"error"),o("add-url");}},[e,t,r]);return useInput((h,S)=>{if(S.escape){o("idle");return}if(S.return){d.current.trim().length>0&&o("add-url");return}if(S.backspace||S.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!S.ctrl&&!S.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,S)=>{if(S.escape){o("add-name");return}if(S.return){g();return}if(S.backspace||S.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}h&&!S.ctrl&&!S.meta&&(m.current=m.current+h,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 Mu(e){let t=w(o=>o.showNotification),r=w(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Dt.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 Ru(){let e=w(L=>L.focus),t=w(L=>L.setFocus),r=w(L=>L.showNotification),n=ae(L=>L.installedItems),[o,s]=useState(()=>ie.listAdapters().map(L=>({adapter:L,stored:null}))),[i,a]=useState(0),[l,c]=useState("list"),[u,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 S=useCallback(()=>{(async()=>{let L=ie.listAdapters(),N=await Dt.read(),F=new Map(N.map(Se=>[Se.id,Se]));s(L.map(Se=>({adapter:Se,stored:F.get(Se.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),S();},[t,S]),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(F=>{N||p({items:F,loading:false,error:null});}).catch(F=>{N||p({items:[],loading:false,error:F instanceof Error?F.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let P=$u(S),T=useCallback(()=>{S(),a(0),c("list"),p(null),g("main");},[S]),{handleRemove:k}=Mu(T),$=useCallback(async L=>{g("removing"),await k(L);},[k]),O=useCallback(async L=>{try{let N=await L.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),L.stored){let F=new Date().toISOString();await Dt.updateField(L.stored.id,{lastUpdated:F}),S();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[S,r]),V=useCallback(async L=>{if(!L.stored)return;let N=L.stored.autoUpdate!==false;await Dt.updateField(L.stored.id,{autoUpdate:!N}),S();},[S]),ge=useCallback(()=>g("browse"),[]),M=useCallback(L=>{let N=o[i-1];if(!N)return;let F=N.adapter.removable!==false;[ge,()=>{O(N);},...F?[()=>{V(N);},()=>{$(N.adapter.id);}]:[]][L]?.();},[o,i,ge,O,V,$]),x=useCallback(()=>g("main"),[]),A=useCallback(()=>{let L=o[i-1];L&&O(L);},[o,i,O]),U=useCallback(()=>{let L=o[i-1];L&&V(L);},[o,i,V]),H=useCallback(()=>{let L=o[i-1];L&&$(L.adapter.id);},[o,i,$]);if(useInput((L,N)=>{if(N.upArrow){a(F=>Math.max(0,F-1));return}if(N.downArrow){a(F=>Math.min(o.length,F+1));return}(N.return||N.tab)&&(i===0?P.startAdd():(c("detail"),d(0)));},{isActive:f==="main"&&P.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((L,N)=>{if(N.escape||N.tab){c("list");return}if(N.upArrow){d(F=>Math.max(0,F-1));return}if(N.downArrow){let F=o[i-1],Se=F?bu(F)-1:0;d(ei=>Math.min(ei+1,Se));return}N.return&&M(u);},{isActive:f==="main"&&P.phase==="idle"&&l==="detail"&&e==="marketplaces"}),P.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:P.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(P.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:P.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:P.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:P.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(P.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(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",F=new Set(n.filter(Se=>Se.marketplace===L.adapter.name).map(Se=>`${Se.name}@${N}`));return jsx(Cu,{entry:L,items:m?.items??[],installedKeys:F,onBack:x})}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 $t=o[i-1]??null,Pn=$t?n.filter(L=>L.marketplace===$t.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(xu,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&$t?jsx(Iu,{entry:$t,detailData:m,installedCount:Pn,focusPanel:l,actionIndex:u,onBrowse:ge,onUpdate:A,onToggleAutoUpdate:U,onRemove:H}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:$t?"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 _u(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=G.findIndex(i=>i.id===r.activeTab),s=G[(o-1+G.length)%G.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=G.findIndex(i=>i.id===r.activeTab),s=G[(o+1)%G.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=G.findIndex(i=>i.id===r.activeTab),s=G[(o+1)%G.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 Du(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Ou(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 Sy=new Set(G.filter(e=>e.focus!=="list").map(e=>e.focus));function ro(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=w.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}=De.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?w.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?w.getState().selectAllTypes():s.type==="toggleOriginFilter"?w.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&w.getState().selectAllOrigins();}function Nu({listLength:e}){let t=w(g=>g.focus),r=w(g=>g.selectedIndex),n=w(g=>g.actionMenuOpen),o=w(g=>g.setFocus),s=w(g=>g.setActionMenuOpen),i=De(g=>g.query),a=De(g=>g.setQuery),l=De(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=De.getState();h(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro($i(g,h,{activeTab:S}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro($i("",h,{activeTab:S}));},{isActive:Sy.has(t)}),useInput((g,h)=>{let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro(_u(g,h,{activeTab:S,selectedIndex:P},c.current));},{isActive:t==="list"}),useInput((g,h)=>{ro(Du(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let S=Ou(g,h,De.getState().query),P=S.queryUpdate;if(ro(S.actions),P==="reset")l(),d("");else if(P!==null){let{query:T,cursorPosition:k,setCursorPosition:$}=De.getState();if("backspace"in P)k>0&&(a(T.slice(0,k-1)+T.slice(k)),$(k-1));else if("append"in P)a(T.slice(0,k)+P.append+T.slice(k)),$(k+P.append.length);else if("cursorMove"in P){let O=k+P.cursorMove;O>=0&&O<=T.length&&$(O);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:S}=w.getState();g===0?h(0):S>=g&&h(g-1);},[]),f=useCallback(g=>{if(!u)return c.current=g.length,g;let h=u.toLowerCase(),S=g.filter(P=>P.name.toLowerCase().includes(h)||P.description?.toLowerCase().includes(h));return c.current=S.length,S},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Uu(){let e=w(a=>a.notification),t=w(a=>a.showNotification),r=w(a=>a.clearNotification),n=Je(a=>a.justAuthenticated),o=Je(a=>a.credentials),s=Je(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 Ce(e,t,r=false){return r?true:!ma.valid(e)||!ma.valid(t)?false:ma.gt(t,e)}var Bt=I("updater");async function wy(e,t,r,n,o,s){try{await v(b.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){Bt.warn(`Failed to send update metrics: ${String(i)}`);}}function xy(e){let t=lt(),r=`${e}@${Q}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ss(e,t={}){let r=Date.now(),n=null;try{Bt.debug(`[${e}] Acquiring lock...`),n=await sr();let o=xy(e);if(!o)throw Bt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Bt.debug(`[${e}] Fetching manifest...`);let c=(await on(e)).version;if(!i||!Ce(i,c,t.force))throw Bt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new nr(e,i??"unknown");Bt.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await ve(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await wy(u.name,i,u.version,d,s.origin??"internal",s.type??"skill"),Bt.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){Bt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await sr();let d=lt(),m=`${e}@${Q}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Xe(d),Bt.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var ws=I("dispatcher");async function Iy(e,t,r,n,o){let s=tn(e);return ws.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await os(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),ws.debug(`[${e}] Retrying install after marketplace add`),he(t)}async function Fu(e,t,r,n){let o=rn(e,n),s=tn(e);r?.onStatus?.(`Installing ${s}...`),ws.debug(`[${e}] Attempting install: ${o}`);let i=await he(o);if(i.exitCode===0)return i;ws.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Iy(e,o,a,t,r)}async function ju(e,t,r){let n=e.type??"bundle",o=await It.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 Ku(){let e=ae(i=>i.installedItems),t=ae(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await ju(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),c=l?.providerId??"claude-code",u=It.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 Jn(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Ss(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var Is=I("mcp");function no(e,t){e.silent?He({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Hu(e,t){e.silent?Re({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(te(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function by(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 fa(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 Ju(e,t,r){if(!await pe())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return no(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Is.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=by(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await yt(`Install external MCP "${s}"?
|
|
110
|
+
`),this.warned=true;}Ao().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Ao(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Ao().path}static hasExistingData(){try{let t=new Si({projectName:wi});return me.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Si({projectName:wi});me.rmSync(t.path,{force:!0});}catch{}$o=null;}};async function xi(){if(_e.hasExistingData())return new _e;switch(process.platform){case "darwin":return await Gr.isAvailable()?new Gr:new _e;case "linux":return await Yt.isAvailable()?new Yt:await Yt.ensureInstalled()?new Yt:new _e;case "win32":return await Xr.isAvailable()?new Xr:new _e;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var Qm=I("config:credentials"),Mt="flow-plugins-cli",Ii="credentials",bi="token-cache",vi="user-info",Ro=null;async function Zt(){return Ro||(Ro=xi()),Ro}function _o(){Ro=null;}async function re(){let t=await(await Zt()).getSecret(Mt,Ii);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Lt(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 Qm.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await Zt()).setSecret(Mt,Ii,JSON.stringify(e));}async function gl(){let e=await Zt();await e.deleteSecret(Mt,Ii),await e.deleteSecret(Mt,bi),await e.deleteSecret(Mt,vi);}async function hl(){return (await Zt()).getStoragePath()}async function yl(e){await(await Zt()).setSecret(Mt,bi,JSON.stringify(e));}async function Do(){let t=await(await Zt()).getSecret(Mt,bi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Oo(e){await(await Zt()).setSecret(Mt,vi,JSON.stringify(e));}async function Sl(){let t=await(await Zt()).getSecret(Mt,vi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Qt(){let e=await Do();return e?new Date(e.expiresAt)>new Date:false}function No(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")}}Mn();var Ei=I("api:auth");function of(e){if(!yr.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var xl={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 sf(e){if(e instanceof HTTPError){let t=e.response.status;Ei.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&xl[r]?new Error(xl[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?(Ei.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Ei.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function br(e){let t=qr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");of(e.tenant);let r;try{r=await Pc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await sf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Lt(e),await yl({accessToken:r.access_token,expiresAt:n});let o=No(r.access_token);await Oo({sub:o.sub,name:o.name,email:o.email});}var Il=I("lib:tokenProvider");async function er(){if(await Qt()){let n=await Do();if(n)return n.accessToken}Il.debug("Token expired or missing, re-authenticating...");let t=await re();if(!t)throw new Error("Not authenticated. Run: flow auth login");_e.clearFallbackFile(),_o(),await br(t);let r=await Do();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Il.debug("Token refreshed successfully"),r.accessToken}Mn();var Bo=I("api:metrics");function bl(){return qr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function vl(e,t,r){return Pc.post(e,{json:t,headers:r})}async function lf(e){let t=await Sl();if(t)return t;let r=No(e),n={sub:r.sub,name:r.name,email:r.email};return await Oo(n),n}async function v(e,t){let r=await er(),n=await lf(r),o=await re();if(!yr.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:ri,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await vl(bl(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Bo.debug(`Metrics event sent: ${e}`);}catch(i){throw Bo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Pl(e,t,r){try{let n=r&&yr.test(r)?r:"unknown",o={action:e,booster:ri,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await vl(bl(),o,{FlowTenant:n}),Bo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Bo.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={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 cf={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},st={...cf};function El(e){let t=Date.now();st={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function vr(e){st.currentStep=e,st.stepStart=Date.now();}function j(){return {...st}}function Rt(){return st.sessionStart===0?0:Date.now()-st.sessionStart}function Pr(){return st.stepStart===0?0:Date.now()-st.stepStart}function Cl(){st.tuiSessionStart=Date.now();}function Tl(){return st.tuiSessionStart===0?0:Date.now()-st.tuiSessionStart}var uf=3e3,df=I("abandonment");async function Uo(e){let{currentStep:t,sessionStart:r}=j();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Rt()};try{await Promise.race([v(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),uf))]);}catch(o){df.warn(`Abandonment event failed: ${String(o)}`);}}function kl(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var pf=3e3,mf=I("session-end");async function Rn(e,t,r){let n=Tl(),s=[v(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Uo(e));try{await kl(Promise.all(s).then(()=>{}),pf);}catch(i){mf.warn(`Session end event failed: ${String(i)}`);}}var yf=2e3;function $l(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=w(l=>l.pendingExit),o=w(l=>l.setPendingExit),s=w(l=>l.activeTab),i=w(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Rn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},yf);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var If=16;function Ml({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,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(If)}),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 Je=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 Er(){return de__default.join(we__default.homedir(),".claude","settings.json")}function Nn(){let e=Er();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 Fo(e){let t=Er();me__default.mkdirSync(de__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 Rl(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 ki(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 Cf=3600,Cr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Tf(e){return Ef.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Cf})}function jo(e,t={}){let r=Nn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Cr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?ki(r.settings):null,s=Tf(e),i=Rl(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function Ko(e){Fo(e.merged);}function _l(){let e=Nn();return e.status!=="ok"?false:ki(e.settings)!==null}var Dl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Dl=e.version);}catch{}var ne=Dl;function Mf(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 ft=["clientId","clientSecret","tenant"],Lf={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function Nl(){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=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:S}=Je(),P=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),T=()=>{d("fields"),p(null),t(M=>({...M,clientSecret:""})),n("clientSecret");},k=async()=>{g.current=true;let M=P();try{await Lt(M);}catch(U){a(U instanceof Error?U.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:x,...A}=M;h(A),S(true),v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{}),Bn({starterKit:A.starterKit});},$=async M=>{g.current=true;let x=P();try{Ko(M),await Lt(x);}catch(H){a(H instanceof Error?H.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:A,...U}=x;h(U),S(true),v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{}),Bn({starterKit:U.starterKit});},O=M=>{try{return jo(P(),{allowOverwriteMalformed:M})}catch(x){return x instanceof Cr?(d("malformedConfirm"),null):(a(x instanceof Error?x.message:"Failed to read settings.json"),d("fields"),null)}};useInput((M,x)=>{if(!(l||g.current)){if(u==="preview"){x.return&&m?$(m):x.escape?k():M==="q"&&T();return}if(u==="malformedConfirm"){if(x.return){let A=O(true);A&&(p(A),$(A));}else x.escape&&T();return}if(x.shift&&x.tab){let A=ft.indexOf(r);A>0&&n(ft[A-1]);}else if(x.tab){let A=ft.indexOf(r);A<ft.length-1&&n(ft[A+1]);}else if(x.return)if(r==="tenant")V();else {let A=ft.indexOf(r);n(ft[A+1]);}}},{isActive:true});let V=async()=>{let M={};for(let x of ft)e[x].trim()||(M[x]="This field is required");if(Object.keys(M).length>0){s(M);let x=ft.find(A=>M[A]);x&&n(x);return}c(true),a(null),f.current+=1;try{await br(P());let x=O(!1);x&&(p(x),d("preview"));}catch(x){let A=x instanceof Error?x.message:"Authentication failed";a(A),Pl(b.CLI_AUTH_FAILED,{error_code:Mf(x),attempt:f.current},e.tenant.trim()).catch(()=>{}),t(U=>({...U,clientSecret:""}));}finally{c(false);}},ge=M=>x=>{t(A=>({...A,[M]:x})),o[M]&&s(A=>({...A,[M]:void 0}));};return u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \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:[fo," \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:[fo," \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:ft.map(M=>jsx(Box,{marginBottom:1,children:jsx(Ml,{label:Lf[M],value:e[M],onChange:ge(M),masked:M==="clientSecret",isActive:r===M&&!l,error:o[M]})},M))}),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 Yr(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(_f,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",ne]})})]})}function Df(){let e=il();if(!me__default.existsSync(e))return {};try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ai=null;function Of(){return Ai===null&&(Ai=Df()),Ai}function tr(){return !!Of().ENABLE_EXPERIMENTAL_BETAS}var Kl=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],G=tr()?Kl:Kl.slice(0,3);function Nf(e){return G.findIndex(t=>t.id===e)}function $i(e,t,r){let n=Nf(r.activeTab);if(t.rightArrow||t.tab){let o=G[(n+1)%G.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=G[(n-1+G.length)%G.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:G[n]?.focus??"list"}]:[]}var Jl={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Gl({outdatedCount:e=0}){let t=w(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:G.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Jl[r]} (${e})`:Jl[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var De=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function zl(){let e=w(i=>i.focus),t=De(i=>i.query),r=De(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 jf=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Vr[e]})),Kf=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Za[e]}));function Xl(){let e=w(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"]})]}),jf.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"]})]}),Kf.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 ql({type:e}){let{label:t,color:r}=Vr[e];return jsx(Text,{color:r,children:t})}function Ql({origin:e}){return e===En?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Ho=Jf.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(ql,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Ql,{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 ",qt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Zr({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function rc({items:e,emptyMessage:t}){let r=w(l=>l.selectedIndex);if(e.length===0)return jsx(Zr,{message:t});let n=Math.max(0,r-Math.floor(Ke/2)),o=Math.min(e.length,n+Ke);o===e.length&&(n=Math.max(0,o-Ke));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(Ho,{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 sc({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 ac({groups:e,emptyMessage:t}){let r=w(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(Zr,{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(Ke/2)),c=Math.min(n.length,l+Ke);c===n.length&&(l=Math.max(0,c-Ke));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(sc,{label:p.label,pathHint:p.pathHint},p.key):jsx(Ho,{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 Qf={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function eg({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(zl,{}),jsx(Xl,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Qf[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(ac,{groups:n,emptyMessage:r}):jsx(rc,{items:e,emptyMessage:r})]})}function lc({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=w(l=>l.activeTab),s=w(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(eg,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var ng={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 Jo(){let e=w(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:[ng[e],t?" | Ctrl+D: debug log":""]})})}function cc({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 Go({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wu,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Wo({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 We({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=w(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 Fi=Object.entries(Cn),hc=[...Fi.map(([,e])=>e.actionLabel),"Cancel"],yc=Object.fromEntries(Fi.map(([,e])=>[e.actionLabel,e.description]));function Sc(e){let t=Fi.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var hg=I("provider.registry"),yg=3e4,Xo=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+yg}),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"&&hg.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 Sg={user:"global",project:"project",local:"local"};function qo(e){return e?Sg[e]:"global"}var Oe=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},nr=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};Mn();function gt(){return Pc.create({prefix:qr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await er();e.headers.set("Authorization",`Bearer ${t}`);let r=await re();r?.tenant&&yr.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var xg=I("catalog.registry"),Yo=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);xg.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 kg={retries:5,minTimeout:50};async function ji(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Tg.lock(e+".lock",{realpath:false,retries:kg});try{return await t()}finally{await r();}}var Zo=class{filePath;constructor(t){this.filePath=t??sl();}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 ji(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 ji(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ji(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 Ag=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function jn(e){if(!e||!Ag.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var $g=/^[^@]+@[^@]+$/;function en(e){return $g.test(e)}function tn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Mg=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Lg(e){if(!Mg.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 rn(e,t){let r=tn(e);Lg(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Rg=/^[\w./:@?&=+#%-]+$/;function Qo(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Rg.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var _g=I("catalog.flow-api"),es=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 gt().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){jn(t);try{return await gt().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 gt().head("v1/plugins/catalog"),_g.debug("ping ok"),!0}catch{return false}}};var ie=new Yo,Dt=new Zo;ie.register(new es);var Tc=false;async function kc(){if(Tc)return;Tc=true;let e=await Dt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Ki(),Cc));for(let r of e)ie.register(new t(r.id,r.name,r.source));}async function or(){return ie.fetchAll()}async function Ac(){return ie.fetchAllWithErrors()}async function on(e){jn(e);try{return await gt().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 $c(e){jn(e);try{let t=await gt().get(`v1/plugins/${e}/archive`);return Buffer.from(await t.arrayBuffer())}catch(t){throw t instanceof Error?t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to download plugin: ${t.message}`):t}}async function ts(){try{let{profiles:e}=await gt().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 Mc(e,t){let r=de.resolve(t);await ht.mkdir(r,{recursive:true});let n=de.join(de.dirname(r),`${randomUUID()}.zip`);try{await ht.writeFile(n,e),await Ug(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=de.resolve(r,o.fileName);if(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=de.normalize(r+de.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(de.resolve(de.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await ht.unlink(n);}catch{}}}async function Vi(e){await ht.rm(e,{recursive:true,force:true});}async function sr(){let e=nl();await ht.mkdir(de.dirname(e),{recursive:true});try{await ht.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Tg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Kg(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:Q,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function _c(){let e=yo();if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return null}}function Vg(){let e=_c();if(e)return e;let t=Kg(),r=yo();return me__default.mkdirSync(de__default.dirname(r),{recursive:true}),Hi(t),t}function Hi(e){let t=yo(),r=`${t}.${randomUUID()}.tmp`;me__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),me__default.renameSync(r,t);}function Hg(){let e=So(),t={};try{me__default.existsSync(e)&&(t=JSON.parse(me__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[Q])return;t[Q]={source:{source:"github",repo:"CI-T-HyperX/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 Dc(e,t){ir(e.name),Hg();let r=si(e.name);me__default.mkdirSync(de__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=Vg();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}),Hi(n));}function Ji(e){ir(e);let t=si(e);try{me__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=_c();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Hi(r);}var Gg=I("mcpConfigReader"),Wg=500,zg=512;function Xg(){return de__default.join(we__default.homedir(),".claude.json")}function qg(){return de__default.join(process.cwd(),".mcp.json")}function Nc(e){if(!me__default.existsSync(e))return null;try{return JSON.parse(me__default.readFileSync(e,"utf-8"))}catch{return Gg.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Kn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gi(e){if(!Kn(e))return {};let t=e.mcpServers;return Kn(t)?t:{}}function Wi(e,t){return Object.keys(e).slice(0,Wg).map(n=>({name:y(n.slice(0,zg)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Uc(){let e=[],t=Xg(),r=Nc(t);if(Kn(r)){let a=r,l=Gi(a);e.push(...Wi(l,"user"));let c=process.cwd();if(Kn(a.projects)){let u=a.projects[c];if(Kn(u)){let d=Gi(u);e.push(...Wi(d,"local"));}}}let n=qg(),o=Nc(n),s=Gi(o);e.push(...Wi(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=I("storage");async function Zg(e,t,r){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:j().interfaceType});}catch(n){ze.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Qg(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:j().interfaceType}).catch(o=>ze.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Yi(){return de__default.join(we__default.homedir(),".claude","plugins","installed_plugins.json")}function eh(){return de__default.join(we__default.homedir(),".claude","plugins")}function Fc(e){let t=de__default.resolve(e),r=de__default.resolve(eh()),n=de__default.resolve(de__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+de__default.sep)||t===r,s=t.startsWith(n+de__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function jc(e="user"){return e==="local"?de__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?de__default.join(process.cwd(),".claude","settings.json"):de__default.join(we__default.homedir(),".claude","settings.json")}function lt(){let e=Yi();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 Zi(){let e=Yi();try{let t=await me__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function th(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Kc(e,t){try{me__default.mkdirSync(de__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 th(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Xe(e){Kc(Yi(),e);}function Vn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function rh(e,t){let r=de__default.join(e,".claude-plugin"),n=de__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=de__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 Qi(e="user"){let t=jc(e);if(!me__default.existsSync(t))return {};try{return JSON.parse(me__default.readFileSync(t,"utf-8"))}catch{return {}}}function Vc(e,t="user"){Kc(jc(t),e);}function nh(e,t){let{name:r,marketplace:n}=Vn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Vn(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 oh(e,t){let{name:r,marketplace:n}=Vn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Vn(i).name===r)[0],o?{key:o,name:r}:null}function zi(e="user"){return Qi(e).enabledPlugins??{}}function Xi(e,t="user"){let r=Qi(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Vc(r,t);}function Hn(e,t,r="user"){let n=Qi(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Vc(n,r);}function sh(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=lt(),t=zi(),r=zi("project"),n=zi("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=Vn(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return sh(p).map(g=>{let h=rh(g.installPath,d),P=(o[g.scope]??t)[c];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:P===false?"disabled":"enabled"}})}),i=Uc(),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 rs(e,t){ze.debug(`[${e}] Acquiring lock to uninstall`);let r=await sr();try{let n=lt(),o=oh(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}`),Fc(l.installPath);let c=de__default.dirname(l.installPath);ze.debug(`[${i}] Removing directory: ${c}`),me__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;Xe({...n,plugins:m}),Xi(s,t),Ji(i);}else n.plugins[s]=u,Xe(n),Xi(s,t);}else {ze.debug(`[${i}] Resolved key: ${s}`);for(let u of a){Fc(u.installPath);let d=de__default.dirname(u.installPath);ze.debug(`[${i}] Removing directory: ${d}`),me__default.rmSync(d,{recursive:!0,force:!0}),Xi(s,u.scope);}Ji(i);let{[s]:l,...c}=n.plugins;Xe({...n,plugins:c});}await Zg(i,a[0].origin??"internal",a[0].type??"skill"),ze.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Jn(e,t,r){ze.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await sr();try{let o=lt(),{key:s,name:i}=nh(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}`),Hn(s,t==="enabled",l),Qg(i,t,c),ze.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var ih=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ah=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ir(e){if(!ih.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function lh(e){if(!ah.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 ar=I("installer");function ch(e,t){let r=`${e}@${Q}`,o=lt().plugins[r];if(o&&!t)throw new Oe(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function uh(e,t,r){r&&await Vi(t);try{ar.debug(`[${t}] Extracting archive...`),await Mc(e,t);}catch(n){throw await Vi(t),n}}function dh(e,t,r,n,o,s="claude-code",i){let a=lt(),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],Xe(a),Hn(e,true,n);}async function ph(e,t,r,n,o,s){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:j().interfaceType});}catch(i){ar.warn(`Failed to send install metrics: ${String(i)}`);}}async function mh(e,t,r,n){try{await v(b.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){ar.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function ve(e,t={}){let r=Date.now(),n=null;try{ar.debug(`[${e}] Acquiring lock...`),n=await sr();let{pluginKey:o,alreadyInstalled:s}=ch(e,t.force);ar.debug(`[${e}] Fetching manifest...`);let i=await on(e);ir(i.name),lh(i.version),ar.debug(`[${e}] Downloading archive...`);let a=await $c(e),l=t.scope??"user",c=t.type??"skill",u=tl(i.name,i.version);await uh(a,u,!!s&&!!t.force),dh(o,u,i.version,l,"internal",t.providerId,c),Dc(i,u);let d=Date.now()-r;ar.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:u,duration_ms:d};return t.skipMetrics||await ph(i.name,i.version,d,qo(l),"internal",c),m}catch(o){throw await mh(e,o,"internal",t.type??"skill"),ar.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var fh=I("commands:helpers");async function pe(){if(!await re())return E("Not authenticated. Run: flow auth login"),false;try{await er();}catch(t){return fh.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function yt(e){let t=ea.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 Hc(e){let t=ea.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var sn=I("claudeProxy"),sa="claude ",Jc="flow ",ta=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ra=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";}},gh=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,hh=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,yh=/^(flow|claude)\s+auth\s+login(\s|$)/,Gc=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function Wc(e){return Gc.test(e.trim())}function Sh(e){return Gc.exec(e.trim())?.[2]??""}async function zc(e){let t=Sh(e),r=Date.now();sn.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 ia(n)?new na:n}}function wh(e){Xc(e);let t=e.slice(sa.length);if(!gh.test(t))throw new ra(e)}var ns=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},na=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Xc(e){if(!e||!/^claude /.test(e))throw new ta(e)}async function he(e){Xc(e);let t=e.slice(sa.length).split(/\s+/).filter(Boolean),r=xh(t);sn.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 sn.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 ia(o)?new ns:o}}function xh(e){return e.length>=3?e[2]:e.join(" ")}function ia(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Ih(e){return e.startsWith(Jc)?sa+e.slice(Jc.length):e}function bh(e){return hh.test(e)||yh.test(e)}function vh(e){let t=0;for(;t<e.length&&bh(e[t]);)t++;return e.slice(t)}var Ph=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Eh(e,t){return !t||e.includes("--scope")||!Ph.test(e)?e:`${e} --scope ${t}`}async function Gn(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=vh(r).map(i=>Ih(i)).map(i=>Eh(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)wh(i);sn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await he(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await he(o[i]),s.exitCode!==0)return s;return s}async function os(e,t,r){let n=tn(e),o=t?.trim();if(!o&&(o=(await Hc(`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=Qo(o),r?.(),sn.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"}`);sn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ia(s)?new ns:s}}var $h=6e4,lr=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 St(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:$h}}).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 lr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new lr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new lr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function wt(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 Rr(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 Lh(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Rh(e){return typeof e=="object"&&e!==null&&e.source==="url"}function _h(e){return typeof e=="object"&&e!==null&&e.source==="github"}function an(e,t){let r=e.source;if(Lh(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(Rh(r))return {cloneUrl:r.url,subPath:"."};if(_h(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 xt=I("claude-code.adapter");function Nh(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=So();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 ru(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=an(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=Nh(e.catalogId,r?.source),i=t.scope??"user",a;o?a=ii(s,e.name,"external"):a=join(wr(i==="user"?"global":"project"),e.name);let l=null;try{ir(e.name),l=await St(n.cloneUrl,n.ref);let c=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(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await Zi(),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],Xe(d),Hn(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return xt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await wt(l).catch(()=>{});}}async function aa(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:qo(n),version:"unknown",duration_ms:t,interface:j().interfaceType});}catch(o){xt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function eu(e,t,r){try{await v(b.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){xt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Bh={async install(e,t){if(e.origin===Kr&&!e.installCommand&&!en(e.name))return ru(e,t);if(e.origin===Kr&&e.installCommand){let r=e.type??"skill",n=await Gn(e.installCommand,t.scope);return n.exitCode===0?(await aa(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await eu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(en(e.name)){let r=e.type??"skill",n=rn(e.name,t.scope);xt.debug(`[${e.name}] Attempting install: ${n}`);let o=await he(n);if(o.exitCode===0)return await aa(e.name,o.duration_ms,r,t.scope),{success:true};xt.debug(`[${e.name}] First attempt failed, adding marketplace`),await os(e.name,t.marketplaceSource,()=>{});let s=await he(n);return s.exitCode===0?(await aa(e.name,s.duration_ms,r,t.scope),{success:true}):(await eu(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 ve(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return xt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await rs(e,t);},getInstallPath(e,t){return ""}};function tu(e){return {async install(t,r){if(t.origin===Kr&&!t.installCommand&&!en(t.name))return ru(t,r);if(!t.installCommand)try{let o=await ve(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return xt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}xt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Gn(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function Uh(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 la(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,la(r)]))}function nu(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(la(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(la(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=nu(s,o):r[n]=o;}return r}async function ou(e,t,r,n){let o=await Zi(),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],Xe(o);}var Fh={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=an(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ir(e.name),s=await St(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Uh(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=xo(r);me__default.mkdirSync(l,{recursive:!0});let c=qe(e.name);if(a.length===1)me__default.copyFileSync(a[0],join(l,`${c}.md`));else for(let d of a){let m=qe(basename(d,".md"));me__default.copyFileSync(d,join(l,`${c}--${m}.md`));}let u=a.length===1?join(l,`${c}.md`):l;return await ou(e.name,r,u,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return xt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await wt(s).catch(()=>{});}},async uninstall(e,t){let r=xo(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=lt(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Xe({...s,plugins:l});}else Xe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(xo(t),`${qe(e)}.md`)}},jh={async install(e,t){let r=t.scope??"user",n=e.catalogId?ie.getAdapter(e.catalogId):void 0,o=an(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ir(e.name),s=await St(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 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=Nn();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=nu(m,c);return Fo({...d,hooks:p}),await ou(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return xt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await wt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ss=class{id="claude-code";name="Claude Code";async isAvailable(){return Rr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Bh,skill:tu("skill"),mcp:tu("mcp"),agent:Fh,hook:jh}};function is(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 Vh=new Set(["gh"]),Hh=is(Vh,"use: gh copilot mcp remove <name>"),as=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Rr("gh",["--version"])?Rr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Hh}};var Jh=new Set(["opencode"]),Gh=is(Jh,"use: opencode config remove mcp <name>");function Wh(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 su(){return {async install(e,t){let r=e.catalogId?ie.getAdapter(e.catalogId):void 0,n=an(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await St(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=wo(t.scope??"user"),a=join(s,".opencode","plugins");if(me__default.existsSync(a)){let l=me__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/"};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`),Wh(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 wt(o).catch(()=>{});}},async uninstall(e,t){let r=wo(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(wo(t),`${e}.js`)}}}var ls=class{id="opencode";name="OpenCode";async isAvailable(){return Rr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Gh,skill:su(),bundle:su()}};var It=new Xo;It.register(new ss);tr()&&(It.register(new as),It.register(new ls));function iu({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(()=>{It.getAvailableProviders(t??"bundle").then(c).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 S=l.find(P=>P.name===h);S?(d(S.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let S=Sc(h);S?r(S,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(S=>S.name),"Cancel"];return jsx(We,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(We,{itemName:`${e} \u2014 Choose scope`,actions:hc,descriptions:yc,onAction:f,onClose:g},"scope"):jsx(We,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function lu({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=w(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,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:[c.length," artifact",c.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:c.map(f=>{let g=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(We,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ds({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=w(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 du({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=ds({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(We,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function fu({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ds({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(We,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var un=I("bundle:installer"),gu=/already exists/i;async function ty(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(Wc(t)){let r=await zc(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(gu.test(n))return;throw new Error(n)}}else {let r=await Gn(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(gu.test(n))return;throw new Error(n)}}}async function ry(e,t){try{await v(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){un.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function ny(e,t,r){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){un.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function hu(e,t,r,n){try{await v(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){un.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function oy(e,t,r,n,o){try{await v(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){un.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function fs(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 ry(i,o.length);let l=[],c=0,u=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){un.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await hu(i,g,h,"unknown artifact type"),r?.({index:p+1,total:u,artifact:f,success:false,error:"unknown artifact type"});continue}try{await ty(f),c++,await ny(i,g,h),r?.({index:p+1,total:u,artifact:f,success:!0});}catch(S){let P=S instanceof Error?S.message:String(S);un.error(`Failed to install artifact "${g}": ${P}`),l.push({name:g,type:h,reason:P}),await hu(i,g,h,P),r?.({index:p+1,total:u,artifact:f,success:false,error:P});}}let d=Date.now()-a,m=l.length;return await oy(i,c,m,s,d),{bundleTitle:e.title,total:n.length,installed:c,skipped:s,failed:m,failures:l}}function xu({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,fs(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(wu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",r.artifact.name??r.artifact.flowId," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(wu,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ae=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:q()})}));function Iu({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 ",qt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function bu({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 ${qt(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((g,h)=>{let S=h===o;return jsxs(Box,{children:[jsx(Text,{color:S?"cyan":void 0,children:S?"\u203A ":" "}),jsx(Text,{bold:S,color:g.danger?"yellow":void 0,dimColor:!S,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function vu(e){return e.adapter.removable!==false?4:2}function Pu({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 Cu({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Tu({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter($=>r.has(`${$.name}@${o}`)),i=t.filter($=>!r.has(`${$.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput(($,O)=>{if(O.escape){n();return}if(O.return){d(a[l]??null);return}if(O.upArrow){c(V=>Math.max(0,V-1));return}O.downArrow&&c(V=>Math.min(a.length-1,V+1));},{isActive:u===null}),u!==null)return jsx(Pu,{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(Ke/2)),p=Math.min(a.length,m+Ke);p===a.length&&(m=Math.max(0,p-Ke));let f=a.slice(m,p),g=m,h=a.length-p,S=s.length>0&&m<s.length,P=p>s.length,T=f.filter($=>r.has(`${$.name}@${o}`)),k=f.filter($=>!r.has(`${$.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`:" "})}),S&&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"]}),T.map($=>jsx(Cu,{item:$,isSelected:a.indexOf($)===l,isInstalled:true},$.name))]}),P&&jsxs(Box,{flexDirection:"column",marginTop:S?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"]}),k.map($=>jsx(Cu,{item:$,isSelected:a.indexOf($)===l,isInstalled:false},$.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"})})]})}Ki();var dy=/^https?:\/\/.+/;function py(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function my(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Mu(e){let t=w(h=>h.showNotification),r=w(h=>h.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");},[]),g=useCallback(async()=>{let h=m.current,S=d.current;if(!dy.test(h)){u("URL must start with http:// or https://");return}u(null),o("adding");let P=randomUUID(),T=new nn(P,S,h);try{await T.fetchItems(),await Dt.add({id:P,name:S,source:h}),ie.register(new nn(P,S,h)),r(),e(),t(`Catalog "${S}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(k){let $=py(k)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":my(k)?k.message:k instanceof Error?`Could not reach catalog URL: ${k.message}`:"Failed to validate catalog URL";t($,"error"),o("add-url");}},[e,t,r]);return useInput((h,S)=>{if(S.escape){o("idle");return}if(S.return){d.current.trim().length>0&&o("add-url");return}if(S.backspace||S.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!S.ctrl&&!S.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,S)=>{if(S.escape){o("add-name");return}if(S.return){g();return}if(S.backspace||S.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}h&&!S.ctrl&&!S.meta&&(m.current=m.current+h,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 Lu(e){let t=w(o=>o.showNotification),r=w(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Dt.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 _u(){let e=w(L=>L.focus),t=w(L=>L.setFocus),r=w(L=>L.showNotification),n=ae(L=>L.installedItems),[o,s]=useState(()=>ie.listAdapters().map(L=>({adapter:L,stored:null}))),[i,a]=useState(0),[l,c]=useState("list"),[u,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 S=useCallback(()=>{(async()=>{let L=ie.listAdapters(),N=await Dt.read(),F=new Map(N.map(Se=>[Se.id,Se]));s(L.map(Se=>({adapter:Se,stored:F.get(Se.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),S();},[t,S]),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(F=>{N||p({items:F,loading:false,error:null});}).catch(F=>{N||p({items:[],loading:false,error:F instanceof Error?F.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let P=Mu(S),T=useCallback(()=>{S(),a(0),c("list"),p(null),g("main");},[S]),{handleRemove:k}=Lu(T),$=useCallback(async L=>{g("removing"),await k(L);},[k]),O=useCallback(async L=>{try{let N=await L.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),L.stored){let F=new Date().toISOString();await Dt.updateField(L.stored.id,{lastUpdated:F}),S();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[S,r]),V=useCallback(async L=>{if(!L.stored)return;let N=L.stored.autoUpdate!==false;await Dt.updateField(L.stored.id,{autoUpdate:!N}),S();},[S]),ge=useCallback(()=>g("browse"),[]),M=useCallback(L=>{let N=o[i-1];if(!N)return;let F=N.adapter.removable!==false;[ge,()=>{O(N);},...F?[()=>{V(N);},()=>{$(N.adapter.id);}]:[]][L]?.();},[o,i,ge,O,V,$]),x=useCallback(()=>g("main"),[]),A=useCallback(()=>{let L=o[i-1];L&&O(L);},[o,i,O]),U=useCallback(()=>{let L=o[i-1];L&&V(L);},[o,i,V]),H=useCallback(()=>{let L=o[i-1];L&&$(L.adapter.id);},[o,i,$]);if(useInput((L,N)=>{if(N.upArrow){a(F=>Math.max(0,F-1));return}if(N.downArrow){a(F=>Math.min(o.length,F+1));return}(N.return||N.tab)&&(i===0?P.startAdd():(c("detail"),d(0)));},{isActive:f==="main"&&P.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((L,N)=>{if(N.escape||N.tab){c("list");return}if(N.upArrow){d(F=>Math.max(0,F-1));return}if(N.downArrow){let F=o[i-1],Se=F?vu(F)-1:0;d(ei=>Math.min(ei+1,Se));return}N.return&&M(u);},{isActive:f==="main"&&P.phase==="idle"&&l==="detail"&&e==="marketplaces"}),P.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:P.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(P.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:P.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:P.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),P.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:P.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(P.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(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",F=new Set(n.filter(Se=>Se.marketplace===L.adapter.name).map(Se=>`${Se.name}@${N}`));return jsx(Tu,{entry:L,items:m?.items??[],installedKeys:F,onBack:x})}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 $t=o[i-1]??null,Pn=$t?n.filter(L=>L.marketplace===$t.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Iu,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&$t?jsx(bu,{entry:$t,detailData:m,installedCount:Pn,focusPanel:l,actionIndex:u,onBrowse:ge,onUpdate:A,onToggleAutoUpdate:U,onRemove:H}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:$t?"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 Du(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=G.findIndex(i=>i.id===r.activeTab),s=G[(o-1+G.length)%G.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=G.findIndex(i=>i.id===r.activeTab),s=G[(o+1)%G.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=G.findIndex(i=>i.id===r.activeTab),s=G[(o+1)%G.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 Ou(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Nu(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 Sy=new Set(G.filter(e=>e.focus!=="list").map(e=>e.focus));function ro(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=w.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}=De.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?w.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?w.getState().selectAllTypes():s.type==="toggleOriginFilter"?w.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&w.getState().selectAllOrigins();}function Bu({listLength:e}){let t=w(g=>g.focus),r=w(g=>g.selectedIndex),n=w(g=>g.actionMenuOpen),o=w(g=>g.setFocus),s=w(g=>g.setActionMenuOpen),i=De(g=>g.query),a=De(g=>g.setQuery),l=De(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=De.getState();h(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro($i(g,h,{activeTab:S}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro($i("",h,{activeTab:S}));},{isActive:Sy.has(t)}),useInput((g,h)=>{let{activeTab:S,selectedIndex:P,actionMenuOpen:T}=w.getState();ro(Du(g,h,{activeTab:S,selectedIndex:P},c.current));},{isActive:t==="list"}),useInput((g,h)=>{ro(Ou(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let S=Nu(g,h,De.getState().query),P=S.queryUpdate;if(ro(S.actions),P==="reset")l(),d("");else if(P!==null){let{query:T,cursorPosition:k,setCursorPosition:$}=De.getState();if("backspace"in P)k>0&&(a(T.slice(0,k-1)+T.slice(k)),$(k-1));else if("append"in P)a(T.slice(0,k)+P.append+T.slice(k)),$(k+P.append.length);else if("cursorMove"in P){let O=k+P.cursorMove;O>=0&&O<=T.length&&$(O);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:S}=w.getState();g===0?h(0):S>=g&&h(g-1);},[]),f=useCallback(g=>{if(!u)return c.current=g.length,g;let h=u.toLowerCase(),S=g.filter(P=>P.name.toLowerCase().includes(h)||P.description?.toLowerCase().includes(h));return c.current=S.length,S},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function Fu(){let e=w(a=>a.notification),t=w(a=>a.showNotification),r=w(a=>a.clearNotification),n=Je(a=>a.justAuthenticated),o=Je(a=>a.credentials),s=Je(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 Ce(e,t,r=false){return r?true:!ma.valid(e)||!ma.valid(t)?false:ma.gt(t,e)}var Bt=I("updater");async function wy(e,t,r,n,o,s){try{await v(b.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){Bt.warn(`Failed to send update metrics: ${String(i)}`);}}function xy(e){let t=lt(),r=`${e}@${Q}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ss(e,t={}){let r=Date.now(),n=null;try{Bt.debug(`[${e}] Acquiring lock...`),n=await sr();let o=xy(e);if(!o)throw Bt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Bt.debug(`[${e}] Fetching manifest...`);let c=(await on(e)).version;if(!i||!Ce(i,c,t.force))throw Bt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new nr(e,i??"unknown");Bt.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await ve(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await wy(u.name,i,u.version,d,s.origin??"internal",s.type??"skill"),Bt.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){Bt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await sr();let d=lt(),m=`${e}@${Q}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Xe(d),Bt.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var ws=I("dispatcher");async function Iy(e,t,r,n,o){let s=tn(e);return ws.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await os(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),ws.debug(`[${e}] Retrying install after marketplace add`),he(t)}async function ju(e,t,r,n){let o=rn(e,n),s=tn(e);r?.onStatus?.(`Installing ${s}...`),ws.debug(`[${e}] Attempting install: ${o}`);let i=await he(o);if(i.exitCode===0)return i;ws.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Iy(e,o,a,t,r)}async function Ku(e,t,r){let n=e.type??"bundle",o=await It.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 Vu(){let e=ae(i=>i.installedItems),t=ae(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Ku(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),c=l?.providerId??"claude-code",u=It.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 Jn(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Ss(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var Is=I("mcp");function no(e,t){e.silent?He({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Ju(e,t){e.silent?Re({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(te(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function by(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 fa(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 Gu(e,t,r){if(!await pe())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return no(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Is.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=by(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await yt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|
|
114
|
-
[y/N] `))return Is.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:
|
|
114
|
+
[y/N] `))return Is.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:Ka({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await he(n);return o?.stop(),s.exitCode!==0?(no(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&C(`stdout: ${s.stdout}`),1):(Ju(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),no(r,{name:e,action:"add",message:X(s)}),1}}async function Wu(e,t){if(!await pe())return 1;Is.debug(`[${e}] Starting MCP remove`);let r=fa(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await yt(`Remove MCP "${o}"?
|
|
115
115
|
This will run: ${s}
|
|
116
|
-
[y/N] `))return Is.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:ja({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await he(r);return n?.stop(),o.exitCode!==0?(no(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(Hu(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),no(t,{name:e,action:"remove",message:X(o)}),1}}function Wu({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=I("pluginHandlers"),a=w(T=>T.setLoading),{install:l,uninstall:c,toggle:u,update:d}=Ku(),m=async(T,k,$)=>{a(true,T),n();try{await k(),o(r.length),s($,"success");}catch(O){let V=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${V}`),s(V,"error");}finally{a(false);}};return {handleInstall:(T,k)=>{e&&t&&m(`Installing ${e.name}...`,()=>l(t,{scope:T,...k!==void 0?{providerId:k}:{}}),"\u2713 Installed successfully");},handleUninstall:T=>{e&&m(`Uninstalling ${e.name}...`,()=>c(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let k=e.status==="enabled";m(k?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,T),k?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{a(true,`Updating ${e.name}${T}...`),n();try{await d(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch($){if($ instanceof nr)s($.message,"info");else {let O=$ instanceof Error?$.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${O}`),s(O,"error");}}finally{a(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let k=T.length;(async()=>{a(true,`Updating ${k} plugin${k>1?"s":""}...`),n();try{let O=[];for(let M of T)O.push(await d(M.name).then(()=>({status:"fulfilled",value:void 0}),x=>({status:"rejected",reason:x})));let V=O.filter(M=>M.status==="fulfilled").length,ge=O.map((M,x)=>M.status==="rejected"?T[x].name:null).filter(M=>M!==null);o(r.length),ge.length===0?s(`\u2713 Updated ${V}/${k} plugin${k>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${ge.join(", ")}`),s(`Updated ${V}/${k}; failed: ${ge.join(", ")}`,V>0?"info":"error"));}finally{a(false);}})();},handleMcpConfigUninstall:T=>{e&&m(`Removing MCP ${e.name}...`,async()=>{let k=fa(e.name,T),$=await he(k);if($.exitCode!==0)throw new Error($.stderr||"MCP removal failed");ae.getState().loadFromDisk();},"\u2713 MCP removed");}}}var bs=I("api:bundle"),gn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},oo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}};async function vs(e){let t=encodeURIComponent(e);bs.debug(`Fetching bundle by name "${e}"`);let r;try{r=await gt().get(`v1/use-cases/by-name/${t}`).json(),bs.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){if(n instanceof HTTPError){let o=n.response.status;throw bs.error(`HTTP error fetching bundle '${e}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new gn(e):o===StatusCodes.INTERNAL_SERVER_ERROR?new oo:new Error(`Server error (${o}) \u2014 please try again later.`)}throw bs.error(`Unexpected error fetching bundle '${e}': ${n instanceof Error?n.message:String(n)}`),n}if(r.length===0)throw new gn(e);return r[0]}function Xu({closeMenu:e,notify:t}){let r=w(a=>a.bundleInstallFlow);return {handleBundleInstallStart:a=>{let{setLoading:l,setBundleInstallFlow:c}=w.getState();l(true,"Loading bundle..."),vs(a).then(u=>{l(false),w.getState().actionMenuOpen&&c({phase:"detail",bundle:u});}).catch(u=>{l(false),t(u instanceof Error?u.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=w.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=w.getState();a(null),e();},handleBundleInstallComplete:a=>{w.getState().setBundleInstallFlow(null),e(),ae.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var so=["local","project","user"],Py=new Set(["--transport","--scope","-s"]);function qu(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(Py.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Dr(e,t){return t?`${e}::${t}`:e}function ga(e){return e===Q?En:Kr}function Yu(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??En}}function ha(e,t){let r=ga(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 Zu(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 so.filter(r=>t.has(r)).map(r=>({scope:r,label:Cn[r].label,pathHint:Cn[r].pathHint,items:t.get(r)??[]}))}function Qu(e){let t=r=>{if(!r)return 1/0;let n=so.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function ed({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Dr(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=>[Dr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let S=f.get(Dr(h.name,h.author?.name))??g.get(h.name),P=S?.version,T=!!P&&!!h.version&&Ce(h.version,P);return {...h,updateAvailable:T,catalogItem:S}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Dr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?qu(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>Yu(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>ha(f,f.catalogItem)):a.map(f=>ha(f,f.catalogItem)),[r,e,s,i,a]),c=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]),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(h=>[Dr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Dr(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function ya(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=w(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await kc();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,v(b.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 td(){return {items:ae(t=>t.installedItems)}}var Ay=I("catalog");function nd(){let e=w(z=>z.bundleInstallFlow),t=w(z=>z.activeTab),r=w(z=>z.notification),n=w(z=>z.loading),o=w(z=>z.loadingMessage),s=w(z=>z.catalogError),i=w(z=>z.setCatalogError),a=w(z=>z.catalogFilters),l=De(z=>z.query),{catalog:c,isLoading:u,error:d,refetch:m}=ya(),{items:p}=td(),f=ae(z=>z.loadFromDisk),{items:g,emptyMessage:h,getSelectedCatalogItem:S,outdatedCount:P}=ed({catalog:c,installedItems:p,activeTab:t,catalogFilters:a,searchQuery:l}),{actionMenuOpen:T,closeMenu:k,selectedIndex:$,clampIndex:O,filteredItems:V}=Nu({listLength:g.length}),ge=V(g),M=useMemo(()=>t!=="installed"&&t!=="updates"?ge:Qu(ge),[t,ge]),x=useMemo(()=>t==="installed"||t==="updates"?Zu(M):[],[t,M]),A=M[$]??null,U=useMemo(()=>S(A),[S,A]),{notify:H}=Uu(),{handleInstall:$t,handleUninstall:Pn,handleToggleStatus:L,handleUpdate:N,handleBatchUpdate:F,handleMcpConfigUninstall:Se}=Wu({selectedItem:A,selectedCatalogItem:U,items:g,closeMenu:k,clampIndex:O,notify:H}),{handleBundleInstallStart:ei,handleBundleDetailConfirm:gm,handleBundleDetailBack:hm,handleBundleInstallComplete:ym}=Xu({closeMenu:k,notify:H}),Sm=useCallback(()=>F(M),[F,M]);return useEffect(()=>{f();},[]),useEffect(()=>{O(M.length);},[M.length,O]),useEffect(()=>{d&&(Ay.error(`[catalog] ${d instanceof Error?d.message:String(d)}`),i("Failed to load catalog"));},[d]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Yr,{}),jsx(Jl,{outdatedCount:P}),t==="marketplaces"&&tr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Ru,{})}):jsx(ac,{filteredItems:M,groups:x,emptyMessage:h,onBatchUpdate:Sm}),(n||u)&&jsx(Go,{message:n?o:"Loading catalog..."}),s&&!u&&t==="discover"&&jsx(Wo,{message:s,onRetry:()=>{i(null),m();},onBack:()=>i(null)}),r&&jsx(lc,{message:r.message,type:r.type}),T&&A&&(t==="discover"?U?.type==="bundle"?e?.phase==="installing"?jsx(wu,{bundle:e.bundle,onComplete:ym}):jsx(au,{itemName:A.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>ei(A.name),onConfirm:gm,onClose:e?.phase==="detail"?hm:k}):jsx(su,{itemName:A.name,itemType:U?.type,onInstall:$t,onClose:k}):A.type==="mcp"?jsx(mu,{itemName:A.name,itemScope:A.scope??"user",onUninstall:Se,onClose:k}):jsx(uu,{itemName:A.name,itemScope:A.scope??"user",itemStatus:A.status??"enabled",updateAvailable:A.updateAvailable??false,catalogVersion:U?.version,onUninstall:Pn,onToggleStatus:z=>L(z),onUpdate:N,onClose:k})),jsx(Jo,{})]})}var _=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(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});},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 Ry=3;function sd(){let e=_(l=>l.setStarterKits),t=_(l=>l.setIsLoadingStarterKits),r=_(l=>l.setStarterKitsError),n=_(l=>l.setPluginStatus),o=_(l=>l.setStep),s=_(l=>l.computeSummary),i=useCallback(async()=>{t(true),r(null);try{let l=await ts();e(l);}catch(l){r(l instanceof Error?l.message:String(l));}finally{t(false);}},[t,r,e]);useEffect(()=>{ae.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let l=_.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of l){n(u.name,"installing");let d="",m=false;for(let p=1;p<=Ry;p++)try{await ve(u.name),n(u.name,"success"),m=!0;break}catch(f){if(f instanceof Oe){n(u.name,"success"),m=true;break}d=f instanceof Error?f.message:"Unknown error";}m||(n(u.name,"failed",d),v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:d,interface:j().interfaceType}).catch(()=>{}));}let c=Pr();vr("summary_review"),v(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:c}).catch(()=>{}),ae.getState().loadFromDisk(),s(),o("summary");},[n,s,o]);return {loadStarterKits:i,installSelected:a}}var io={cursorDelta:0,confirm:false,back:false};function id(e,t){return t.upArrow?{...io,cursorDelta:-1}:t.downArrow?{...io,cursorDelta:1}:t.escape?{...io,back:true}:t.return?{...io,confirm:true}:io}var _y={cursorDelta:0,select:false};function ad(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:_y}var ld=Jf.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 va=5;function cd({onRetry:e}){let t=_(u=>u.starterKits),r=_(u=>u.selectedStarterKitIndex),n=_(u=>u.isLoadingStarterKits),o=_(u=>u.starterKitsError);if(n)return jsx(Go,{message:"Loading Starter Kits..."});if(o)return jsx(Wo,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Zr,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(va/2)),i=Math.min(t.length,s+va);i===t.length&&(s=Math.max(0,i-va));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(ld,{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 dd=Jf.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 Ca=8;function pd(){let e=_(u=>u.selectedStarterKit),t=_(u=>u.plugins),r=_(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,v(b.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(Ca/2)),i=Math.min(t.length,s+Ca);i===t.length&&(s=Math.max(0,i-Ca));let a=t.slice(s,i),l=s,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(dd,{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 Vy=["Retry failed","Continue anyway"];function md({name:e,status:t,error:r}){let n=y(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Su,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function fd({onComplete:e,onRetry:t}){let r=_(c=>c.plugins),n=_(c=>c.step),o=_(c=>c.successCount),s=_(c=>c.failedCount),i=_(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(md,{name:c.name,status:c.status,error:c.error},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(md,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Vy.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 gd(){let e=_(x=>x.step),t=_(x=>x.starterKits),r=_(x=>x.selectedStarterKitIndex),n=_(x=>x.setSelectedStarterKitIndex),o=_(x=>x.selectStarterKit),s=_(x=>x.plugins),i=_(x=>x.pluginCursorIndex),a=_(x=>x.setPluginCursorIndex),l=_(x=>x.setStep),c=_(x=>x.summaryActionIndex),u=_(x=>x.setSummaryActionIndex),d=_(x=>x.failedCount),m=_(x=>x.resetForRetry),p=_(x=>x.goBackToList),f=w(x=>x.setScreen),g=w(x=>x.setFocus),h=w(x=>x.focus),S=Je(x=>x.setJustAuthenticated),P=Je(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:k}=sd(),$=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),$.current||($.current=true,vr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let O=useCallback(async()=>{let x=_.getState().selectedStarterKit;if(x){let U=await re();U&&await Lt({...U,starterKit:x.slug});}v(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Pr()}).catch(()=>{});let{successCount:A}=_.getState();v(b.CLI_ONBOARDING_COMPLETED,{duration_ms:Rt(),tools_installed_count:A}).catch(()=>{}),S(false),g("verify"),f("verify");},[S,g,f]),V=useCallback(()=>{m(),k();},[m,k]),ge=useCallback(()=>{T();},[T]),M=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((x,A)=>{if(A.escape)Uo("esc"),M();else if(A.upArrow&&r>0)n(r-1);else if(A.downArrow&&r<t.length-1)n(r+1);else if(A.return&&t.length>0){let U=Pr();o(t[r]),vr("kit_display"),v(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:U}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,A)=>{let U=id(x,A);if(U.cursorDelta!==0){let H=i+U.cursorDelta;H>=0&&H<s.length&&a(H);}if(U.confirm){let H=_.getState().selectedStarterKit;H&&(async()=>(await re())?.starterKit!==H.slug&&v(b.CLI_KIT_ACCEPTED,{bundle_slug:H.slug}).catch(()=>{}))();let $t=Pr();vr("kit_confirmation"),v(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:$t}).catch(()=>{});let Pn=Pr();vr("tool_installation"),v(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Pn}).catch(()=>{}),l("installing"),k();}if(U.back){let H=_.getState().selectedStarterKit;H&&v(b.CLI_KIT_REJECTED,{bundle_slug:H.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((x,A)=>{if(d===0)return;let U=ad(x,A);if(U.cursorDelta!==0){let H=c+U.cursorDelta;H>=0&&H<=1&&u(H);}U.select&&(c===0?V():O());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Yr,{}),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."}),!P&&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(cd,{onRetry:ge}),e==="starterKitDetail"&&jsx(pd,{}),(e==="installing"||e==="summary")&&jsx(fd,{onComplete:O,onRetry:V})]}),jsx(Jo,{})]})}var Xy=I("moduleState");function Ls(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"modules.json")}var qy={retries:5,minTimeout:50};async function hd(e,t){me__default.mkdirSync(de__default.dirname(e),{recursive:true});let r=await Tg.lock(e+".lock",{realpath:false,retries:qy});try{return await t()}finally{await r();}}function yd(){let e=Ls();if(!me__default.existsSync(e))return [];try{let t=JSON.parse(me__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Xy.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 Nr(){return yd()}function Sd(e){let t=Ls();me__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};me__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),me__default.renameSync(r,t);}function et(e){return Nr().find(t=>t.alias===e)??null}async function Et(e){let t=Ls();await hd(t,async()=>{let r=yd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Sd(r);});}async function Br(){let e=Ls();me__default.existsSync(e)||await hd(e,async()=>{me__default.existsSync(e)||Sd([]);});}function eS(){return Z.filter(e=>e.platforms[process.platform]?.status==="supported")}function xd(e){let t=eS();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var wd={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=de__default.join(we__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=[];if(e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push(["flow-ai-obs","auth","login","--client-id",r,"--client-secret",n,"--tenant",o]);}return t.push(e.customUrl?["flow-ai-obs","init","--custom-url",e.customUrl]:["flow-ai-obs","init","--no-interactive"]),t},onDemand:null,mode:"non-interactive"}},tS={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},Z=tr()?[wd,tS]:[wd];var oS=promisify(execFile);function pr(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 oS(t,[e]),!0}catch{return false}}function jt(){return process.platform==="win32"?"npm.cmd":"npm"}var Id=promisify(execFile),Rs=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=pr(t,"npm");if(!r)return null;try{let{stdout:n}=await Id(jt(),["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=pr(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 Id(jt(),["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 bd=promisify(execFile),cS=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,_s=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=pr(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=pr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return await bd("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 bd("brew",["list","--versions",t]),n=r.trim().match(cS);return n?n[2]:null}catch{return null}}};var yn=promisify(execFile),mS=I("curlStrategy"),Pd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Ed(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"bin")}var Ds=class{type="curl";async isAvailable(){return Ct("curl")}async install(t){let r=Date.now(),n=pr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=de__default.join(Ed(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await yn(n,["--version"]),s=o.match(Pd);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){let s=de__default.join(we__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await yn("curl",["-sSL","--fail","-o",s,t]),r||mS.warn(`Installing script for "${n.alias}" without checksum verification \u2014 checksumUrl not provided`),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{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 yn("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=Ed(),i=de__default.join(s,n.binaryName),a=false;try{if(me__default.mkdirSync(s,{recursive:!0}),a=!0,await yn("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return me__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}me__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await yn(i,["--version"]),u=c.match(Pd);l=u?u[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=de__default.join(we__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await yn("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 Ae=I("moduleInstaller");function Kt(e){switch(e){case "npm":return new Rs;case "homebrew":return new _s;case "curl":return new Ds}}async function co(e,t,r){try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Ae.warn(`Failed to emit install failed event: ${String(n)}`);}}async function wn(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"){Ae.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 co(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 co(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 co(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}let i=Kt(r),a=false;try{a=await i.isAvailable();}catch(c){Ae.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 co(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ne,trigger:t});}catch(c){Ae.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);Ae.warn(`${r} install threw: ${u}`),l={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-o};}if(l.success){await Et({alias:e.alias,name:e.name,installedVersion:l.version??null,installMethod:l.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await v(b.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(u){Ae.warn(`Failed to emit install completed event: ${String(u)}`);}let c=await gS(e,t,n);return c?{...l,pendingInteractiveSetup:c}:e.configCheck&&!e.configCheck()?{...l,configCheckFailed:true}:l}return await co(e,t,l.error??{code:"UNKNOWN",message:"unknown error"}),l}async function gS(e,t,r){if(!e.postInstall)return null;let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return null;let o;if(typeof n=="function"){let s=await re(),i={credentials:s?{clientId:s.clientId,clientSecret:s.clientSecret,tenant:s.tenant}:null,customUrl:r??null};try{o=n(i);}catch(a){return Ae.warn(`postInstall function threw: ${String(a)}`),null}}else o=n;if(o.length===0)return null;if((e.postInstall.mode??"non-interactive")==="interactive")return o[0]??null;for(let s of o){if(s.length===0)continue;let i=spawnSync(s[0],s.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});i.status!==0&&(Ae.warn(`postInstall "${s.join(" ")}" exited with status ${i.status??"null"}`),i.stderr&&Ae.warn(i.stderr));}return null}async function Os(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Kt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ne,trigger:"command"});}catch(a){Ae.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Ae.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await Et({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await v(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Ae.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Ae.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Ae.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var kd=null;function Ad(){return kd}async function Ns(){let t=Nr().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 $d(n);(o||s)&&await Et({...r,installedVersion:o,installMethod:s});}}async function $d(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Kt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function xn(e){let t=await Promise.all(e.map(r=>hS(r)));return kd=t,t}async function hS(e){let t=Cd(e.versionCommand);t==="permission-denied"&&(yS(e.versionCommand[0]),t=Cd(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Kt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!et(e.alias)){let{installedVersion:l,installMethod:c}=await $d(e);await Et({alias:e.alias,name:e.name,installedVersion:l,installMethod:c,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Cd(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 yS(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 xS(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 Dd(e,t){let[r,n]=useState(()=>xS(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,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 S=f[p];S&&!S.module.required&&l(S.module.alias);}else if(m.tab){let S=f[p];if(S&&S.availableStrategies.length>1){let P=S.availableStrategies.indexOf(S.selectedStrategy??S.availableStrategies[0]),T=S.availableStrategies[(P+1)%S.availableStrategies.length];n(k=>k.map($=>$.module.alias===S.module.alias?{...$,selectedStrategy:T}:$));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Nd({probeResults:e,onConfirm:t}){let r=w(p=>p.focus),n=w(p=>p.actionMenuOpen),o=w(p=>p.setActionMenuOpen),s=w(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Dd(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 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(We,{itemName:m,actions:d,onAction:u,onClose:c})]})}var ES=/^https?:\/\/.+/;function Bd({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&&ES.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 TS(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 jd(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=TS(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 wn(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 Kd({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Su,{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 Gd({confirmedItems:e,customUrl:t}){let r=w(S=>S.setScreen),n=w(S=>S.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:c}=jd(e,t),u=o.some(S=>S.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Br().catch(()=>{}),n("list");let S=q().some(P=>P.name===ee);r(S?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!u&&!m.current){m.current=true;let S=setTimeout(p,1500);return ()=>clearTimeout(S)}},[i,l,u,p]),useInput((S,P)=>{P.return&&p();},{isActive:i});let f=o.filter(S=>S.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")),c>0&&h.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(S=>jsx(Kd,{module:S},S.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((S,P,T)=>(T>0&&S.push(jsx(Text,{children:" | "},`sep-${T}`)),S.push(P),S),[])}),jsx(Box,{paddingX:1,children:l>0||u?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function zd(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=w(p=>p.setFocus),c=w(p=>p.setScreen),u=useCallback(p=>{if(xd(p)){Br().catch(()=>{}),l("list");let g=q().some(h=>h.name===ee);c(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,c]);useEffect(()=>{let p=Ad();if(p){u(p);return}xn(Z).then(u).catch(()=>{n([]),t("selection");});},[u]);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(Nd,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Bd,{onConfirm:m}),e==="installation"&&jsx(Gd,{confirmedItems:o,customUrl:i})]})}var NS=I("ClaudeMdSuggestion"),BS=[`Install ${ee}`,"Skip for now"],US=["Retry","Skip for now"];function Yd(){let e=w(m=>m.setScreen),t=w(m=>m.setFocus),r=_(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ve(ee),o("installed");}catch(m){if(m instanceof Oe){o("installed");return}NS.warn(`Failed to install ${ee}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?US:BS;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(Yr,{}),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(qd,{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(Su,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ee,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ee," 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:["/",ee]})]}),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 ",ee]}),jsx(qd,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function qd({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 VS=promisify(execFile),Ks="@ciandt-flow/cli";async function Zd(){let e=ne;if(ma.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ks};try{let t=await fetch(`https://registry.npmjs.org/${Ks}/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:Ks}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ks}}}async function Vs(e){try{return await VS(jt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Qd(e){let r=et(e.alias)?.installedVersion??null,n=null;try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`);if(!s.ok)throw new Error(`Registry returned ${s.status}`);n=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`);if(!s.ok)throw new Error(`GitHub returned ${s.status}`);n=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=r!==null&&n!==null&&r!==n;return {moduleAlias:e.alias,currentVersion:r,latestVersion:n,isOutdated:o}}async function ep(e,t){let r=et(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Kt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await Et({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function tp(e){let r=et(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function rp(){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([Zd(),xn(Z),Promise.all(Z.map(l=>Qd(l)))]);if(Ns(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Vs(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=Z.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await ep(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:tp(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await Br(),t(l=>({...l,outcome:"done"}));}catch{await Br(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function XS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Su,{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 qS({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 np(){let{outcome:e,items:t}=rp(),r=w(o=>o.setScreen),n=w(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=q().some(i=>i.name===ee);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(XS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(qS,{outcome:e})})]})}var ew={debug:"gray",info:"cyan",warn:"yellow",error:"red"},op=10;function sp(){let[e,t]=useState(li());useEffect(()=>il(()=>{t([...li()]);}),[]);let r=e.slice(-op);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",op,") \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:ew[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var ow=I("app"),sw={auth:Ol,starterKitSetup:gd,moduleSetup:zd,claudeMdSuggestion:Yd,verify:np,main:nd};function lp(){let{setScreen:e,setFocus:t}=w.getState();e("auth"),t("auth");}function Bn(e){let{setScreen:t,setFocus:r}=w.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function cp(){v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{});}async function dp(){let e=await re();if(e&&Rl()&&await Qt()){let{clientSecret:n,...o}=e;Je.getState().setCredentials(o),cp(),Bn(e);return}if(!e){lp();return}try{await er();}catch(n){ow.debug(`Token validation failed: ${String(n)}`),lp();return}cp();let{clientSecret:t,...r}=e;Je.getState().setCredentials(r),Bn(e);}function pp(){let{columns:e,rows:t}=useWindowSize(),r=w(a=>a.screen),n=sw[r],{pendingExit:o}=Al(),s=w(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=w.getState().debugPanelOpen;w.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(sp,{}),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 Ua(e,t={}){let r=jo({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Ko(r),await Lt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var pt=I("auth");function fp(){_e.clearFallbackFile(),_o();}var iw=3,mp=3,gp=` \u2139 The data collected during setup is used solely to improve
|
|
116
|
+
[y/N] `))return Is.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:Ka({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await he(r);return n?.stop(),o.exitCode!==0?(no(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(Ju(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),no(t,{name:e,action:"remove",message:X(o)}),1}}function zu({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=I("pluginHandlers"),a=w(T=>T.setLoading),{install:l,uninstall:c,toggle:u,update:d}=Vu(),m=async(T,k,$)=>{a(true,T),n();try{await k(),o(r.length),s($,"success");}catch(O){let V=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${V}`),s(V,"error");}finally{a(false);}};return {handleInstall:(T,k)=>{e&&t&&m(`Installing ${e.name}...`,()=>l(t,{scope:T,...k!==void 0?{providerId:k}:{}}),"\u2713 Installed successfully");},handleUninstall:T=>{e&&m(`Uninstalling ${e.name}...`,()=>c(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let k=e.status==="enabled";m(k?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>u(e.name,T),k?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{a(true,`Updating ${e.name}${T}...`),n();try{await d(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch($){if($ instanceof nr)s($.message,"info");else {let O=$ instanceof Error?$.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${O}`),s(O,"error");}}finally{a(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let k=T.length;(async()=>{a(true,`Updating ${k} plugin${k>1?"s":""}...`),n();try{let O=[];for(let M of T)O.push(await d(M.name).then(()=>({status:"fulfilled",value:void 0}),x=>({status:"rejected",reason:x})));let V=O.filter(M=>M.status==="fulfilled").length,ge=O.map((M,x)=>M.status==="rejected"?T[x].name:null).filter(M=>M!==null);o(r.length),ge.length===0?s(`\u2713 Updated ${V}/${k} plugin${k>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${ge.join(", ")}`),s(`Updated ${V}/${k}; failed: ${ge.join(", ")}`,V>0?"info":"error"));}finally{a(false);}})();},handleMcpConfigUninstall:T=>{e&&m(`Removing MCP ${e.name}...`,async()=>{let k=fa(e.name,T),$=await he(k);if($.exitCode!==0)throw new Error($.stderr||"MCP removal failed");ae.getState().loadFromDisk();},"\u2713 MCP removed");}}}var bs=I("api:bundle"),gn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},oo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}};async function vs(e){let t=encodeURIComponent(e);bs.debug(`Fetching bundle by name "${e}"`);let r;try{r=await gt().get(`v1/use-cases/by-name/${t}`).json(),bs.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){if(n instanceof HTTPError){let o=n.response.status;throw bs.error(`HTTP error fetching bundle '${e}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new gn(e):o===StatusCodes.INTERNAL_SERVER_ERROR?new oo:new Error(`Server error (${o}) \u2014 please try again later.`)}throw bs.error(`Unexpected error fetching bundle '${e}': ${n instanceof Error?n.message:String(n)}`),n}if(r.length===0)throw new gn(e);return r[0]}function qu({closeMenu:e,notify:t}){let r=w(a=>a.bundleInstallFlow);return {handleBundleInstallStart:a=>{let{setLoading:l,setBundleInstallFlow:c}=w.getState();l(true,"Loading bundle..."),vs(a).then(u=>{l(false),w.getState().actionMenuOpen&&c({phase:"detail",bundle:u});}).catch(u=>{l(false),t(u instanceof Error?u.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=w.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=w.getState();a(null),e();},handleBundleInstallComplete:a=>{w.getState().setBundleInstallFlow(null),e(),ae.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var so=["local","project","user"],Py=new Set(["--transport","--scope","-s"]);function Yu(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(Py.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Dr(e,t){return t?`${e}::${t}`:e}function ga(e){return e===Q?En:Kr}function Zu(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??En}}function ha(e,t){let r=ga(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 Qu(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 so.filter(r=>t.has(r)).map(r=>({scope:r,label:Cn[r].label,pathHint:Cn[r].pathHint,items:t.get(r)??[]}))}function ed(e){let t=r=>{if(!r)return 1/0;let n=so.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function td({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Dr(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=>[Dr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let S=f.get(Dr(h.name,h.author?.name))??g.get(h.name),P=S?.version,T=!!P&&!!h.version&&Ce(h.version,P);return {...h,updateAvailable:T,catalogItem:S}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Dr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?Yu(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>Zu(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>ha(f,f.catalogItem)):a.map(f=>ha(f,f.catalogItem)),[r,e,s,i,a]),c=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]),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(h=>[Dr(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Dr(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function ya(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=w(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Ac();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,v(b.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 rd(){return {items:ae(t=>t.installedItems)}}var Ay=I("catalog");function od(){let e=w(z=>z.bundleInstallFlow),t=w(z=>z.activeTab),r=w(z=>z.notification),n=w(z=>z.loading),o=w(z=>z.loadingMessage),s=w(z=>z.catalogError),i=w(z=>z.setCatalogError),a=w(z=>z.catalogFilters),l=De(z=>z.query),{catalog:c,isLoading:u,error:d,refetch:m}=ya(),{items:p}=rd(),f=ae(z=>z.loadFromDisk),{items:g,emptyMessage:h,getSelectedCatalogItem:S,outdatedCount:P}=td({catalog:c,installedItems:p,activeTab:t,catalogFilters:a,searchQuery:l}),{actionMenuOpen:T,closeMenu:k,selectedIndex:$,clampIndex:O,filteredItems:V}=Bu({listLength:g.length}),ge=V(g),M=useMemo(()=>t!=="installed"&&t!=="updates"?ge:ed(ge),[t,ge]),x=useMemo(()=>t==="installed"||t==="updates"?Qu(M):[],[t,M]),A=M[$]??null,U=useMemo(()=>S(A),[S,A]),{notify:H}=Fu(),{handleInstall:$t,handleUninstall:Pn,handleToggleStatus:L,handleUpdate:N,handleBatchUpdate:F,handleMcpConfigUninstall:Se}=zu({selectedItem:A,selectedCatalogItem:U,items:g,closeMenu:k,clampIndex:O,notify:H}),{handleBundleInstallStart:ei,handleBundleDetailConfirm:gm,handleBundleDetailBack:hm,handleBundleInstallComplete:ym}=qu({closeMenu:k,notify:H}),Sm=useCallback(()=>F(M),[F,M]);return useEffect(()=>{f();},[]),useEffect(()=>{O(M.length);},[M.length,O]),useEffect(()=>{d&&(Ay.error(`[catalog] ${d instanceof Error?d.message:String(d)}`),i("Failed to load catalog"));},[d]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Yr,{}),jsx(Gl,{outdatedCount:P}),t==="marketplaces"&&tr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(_u,{})}):jsx(lc,{filteredItems:M,groups:x,emptyMessage:h,onBatchUpdate:Sm}),(n||u)&&jsx(Go,{message:n?o:"Loading catalog..."}),s&&!u&&t==="discover"&&jsx(Wo,{message:s,onRetry:()=>{i(null),m();},onBack:()=>i(null)}),r&&jsx(cc,{message:r.message,type:r.type}),T&&A&&(t==="discover"?U?.type==="bundle"?e?.phase==="installing"?jsx(xu,{bundle:e.bundle,onComplete:ym}):jsx(lu,{itemName:A.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>ei(A.name),onConfirm:gm,onClose:e?.phase==="detail"?hm:k}):jsx(iu,{itemName:A.name,itemType:U?.type,onInstall:$t,onClose:k}):A.type==="mcp"?jsx(fu,{itemName:A.name,itemScope:A.scope??"user",onUninstall:Se,onClose:k}):jsx(du,{itemName:A.name,itemScope:A.scope??"user",itemStatus:A.status??"enabled",updateAvailable:A.updateAvailable??false,catalogVersion:U?.version,onUninstall:Pn,onToggleStatus:z=>L(z),onUpdate:N,onClose:k})),jsx(Jo,{})]})}var _=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(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});},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 Ry=3;function id(){let e=_(l=>l.setStarterKits),t=_(l=>l.setIsLoadingStarterKits),r=_(l=>l.setStarterKitsError),n=_(l=>l.setPluginStatus),o=_(l=>l.setStep),s=_(l=>l.computeSummary),i=useCallback(async()=>{t(true),r(null);try{let l=await ts();e(l);}catch(l){r(l instanceof Error?l.message:String(l));}finally{t(false);}},[t,r,e]);useEffect(()=>{ae.getState().loadFromDisk(),i();},[i]);let a=useCallback(async()=>{let l=_.getState().plugins.filter(u=>u.selected&&u.status==="pending");for(let u of l){n(u.name,"installing");let d="",m=false;for(let p=1;p<=Ry;p++)try{await ve(u.name),n(u.name,"success"),m=!0;break}catch(f){if(f instanceof Oe){n(u.name,"success"),m=true;break}d=f instanceof Error?f.message:"Unknown error";}m||(n(u.name,"failed",d),v(b.CLI_TOOL_INSTALL_FAILED,{tool_id:u.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:d,interface:j().interfaceType}).catch(()=>{}));}let c=Pr();vr("summary_review"),v(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:c}).catch(()=>{}),ae.getState().loadFromDisk(),s(),o("summary");},[n,s,o]);return {loadStarterKits:i,installSelected:a}}var io={cursorDelta:0,confirm:false,back:false};function ad(e,t){return t.upArrow?{...io,cursorDelta:-1}:t.downArrow?{...io,cursorDelta:1}:t.escape?{...io,back:true}:t.return?{...io,confirm:true}:io}var _y={cursorDelta:0,select:false};function ld(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:_y}var cd=Jf.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 va=5;function ud({onRetry:e}){let t=_(u=>u.starterKits),r=_(u=>u.selectedStarterKitIndex),n=_(u=>u.isLoadingStarterKits),o=_(u=>u.starterKitsError);if(n)return jsx(Go,{message:"Loading Starter Kits..."});if(o)return jsx(Wo,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Zr,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(va/2)),i=Math.min(t.length,s+va);i===t.length&&(s=Math.max(0,i-va));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(cd,{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 pd=Jf.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 Ca=8;function md(){let e=_(u=>u.selectedStarterKit),t=_(u=>u.plugins),r=_(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,v(b.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(Ca/2)),i=Math.min(t.length,s+Ca);i===t.length&&(s=Math.max(0,i-Ca));let a=t.slice(s,i),l=s,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(pd,{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 Vy=["Retry failed","Continue anyway"];function fd({name:e,status:t,error:r}){let n=y(e);return t==="installing"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",n]})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",n]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",n]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",n]})})}function gd({onComplete:e,onRetry:t}){let r=_(c=>c.plugins),n=_(c=>c.step),o=_(c=>c.successCount),s=_(c=>c.failedCount),i=_(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(fd,{name:c.name,status:c.status,error:c.error},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(fd,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:Vy.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 hd(){let e=_(x=>x.step),t=_(x=>x.starterKits),r=_(x=>x.selectedStarterKitIndex),n=_(x=>x.setSelectedStarterKitIndex),o=_(x=>x.selectStarterKit),s=_(x=>x.plugins),i=_(x=>x.pluginCursorIndex),a=_(x=>x.setPluginCursorIndex),l=_(x=>x.setStep),c=_(x=>x.summaryActionIndex),u=_(x=>x.setSummaryActionIndex),d=_(x=>x.failedCount),m=_(x=>x.resetForRetry),p=_(x=>x.goBackToList),f=w(x=>x.setScreen),g=w(x=>x.setFocus),h=w(x=>x.focus),S=Je(x=>x.setJustAuthenticated),P=Je(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:k}=id(),$=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),$.current||($.current=true,vr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let O=useCallback(async()=>{let x=_.getState().selectedStarterKit;if(x){let U=await re();U&&await Lt({...U,starterKit:x.slug});}v(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Pr()}).catch(()=>{});let{successCount:A}=_.getState();v(b.CLI_ONBOARDING_COMPLETED,{duration_ms:Rt(),tools_installed_count:A}).catch(()=>{}),S(false),g("verify"),f("verify");},[S,g,f]),V=useCallback(()=>{m(),k();},[m,k]),ge=useCallback(()=>{T();},[T]),M=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((x,A)=>{if(A.escape)Uo("esc"),M();else if(A.upArrow&&r>0)n(r-1);else if(A.downArrow&&r<t.length-1)n(r+1);else if(A.return&&t.length>0){let U=Pr();o(t[r]),vr("kit_display"),v(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:U}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,A)=>{let U=ad(x,A);if(U.cursorDelta!==0){let H=i+U.cursorDelta;H>=0&&H<s.length&&a(H);}if(U.confirm){let H=_.getState().selectedStarterKit;H&&(async()=>(await re())?.starterKit!==H.slug&&v(b.CLI_KIT_ACCEPTED,{bundle_slug:H.slug}).catch(()=>{}))();let $t=Pr();vr("kit_confirmation"),v(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:$t}).catch(()=>{});let Pn=Pr();vr("tool_installation"),v(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Pn}).catch(()=>{}),l("installing"),k();}if(U.back){let H=_.getState().selectedStarterKit;H&&v(b.CLI_KIT_REJECTED,{bundle_slug:H.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((x,A)=>{if(d===0)return;let U=ld(x,A);if(U.cursorDelta!==0){let H=c+U.cursorDelta;H>=0&&H<=1&&u(H);}U.select&&(c===0?V():O());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Yr,{}),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."}),!P&&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(ud,{onRetry:ge}),e==="starterKitDetail"&&jsx(md,{}),(e==="installing"||e==="summary")&&jsx(gd,{onComplete:O,onRetry:V})]}),jsx(Jo,{})]})}var Xy=I("moduleState");function Ls(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"modules.json")}var qy={retries:5,minTimeout:50};async function yd(e,t){me__default.mkdirSync(de__default.dirname(e),{recursive:true});let r=await Tg.lock(e+".lock",{realpath:false,retries:qy});try{return await t()}finally{await r();}}function Sd(){let e=Ls();if(!me__default.existsSync(e))return [];try{let t=JSON.parse(me__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Xy.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 Nr(){return Sd()}function wd(e){let t=Ls();me__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};me__default.writeFileSync(r,JSON.stringify(n,null,2),"utf-8"),me__default.renameSync(r,t);}function et(e){return Nr().find(t=>t.alias===e)??null}async function Et(e){let t=Ls();await yd(t,async()=>{let r=Sd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,wd(r);});}async function Br(){let e=Ls();me__default.existsSync(e)||await yd(e,async()=>{me__default.existsSync(e)||wd([]);});}function eS(){return Z.filter(e=>e.platforms[process.platform]?.status==="supported")}function Id(e){let t=eS();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var xd={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=de__default.join(we__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=[];if(e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push(["flow-ai-obs","auth","login","--client-id",r,"--client-secret",n,"--tenant",o]);}return t.push(e.customUrl?["flow-ai-obs","init","--custom-url",e.customUrl]:["flow-ai-obs","init","--no-interactive"]),t},onDemand:null,mode:"non-interactive"}},tS={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=tr()?[xd,tS]:[xd];var oS=promisify(execFile);function pr(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 oS(t,[e]),!0}catch{return false}}function jt(){return process.platform==="win32"?"npm.cmd":"npm"}var bd=promisify(execFile),Rs=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=pr(t,"npm");if(!r)return null;try{let{stdout:n}=await bd(jt(),["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=pr(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 bd(jt(),["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 $a=promisify(execFile),cS=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,_s=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=pr(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=pr(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 $a("brew",["tap",o.tap]),await $a("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 $a("brew",["list","--versions",t]),n=r.trim().match(cS);return n?n[2]:null}catch{return null}}};var yn=promisify(execFile),mS=I("curlStrategy"),Pd=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Ed(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"bin")}var Ds=class{type="curl";async isAvailable(){return Ct("curl")}async install(t){let r=Date.now(),n=pr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=de__default.join(Ed(),t.binaryName);for(let n of [r,t.binaryName])try{let{stdout:o}=await yn(n,["--version"]),s=o.match(Pd);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){let s=de__default.join(we__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await yn("curl",["-sSL","--fail","-o",s,t]),r||mS.warn(`Installing script for "${n.alias}" without checksum verification \u2014 checksumUrl not provided`),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{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 yn("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=Ed(),i=de__default.join(s,n.binaryName),a=false;try{if(me__default.mkdirSync(s,{recursive:!0}),a=!0,await yn("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return me__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}me__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await yn(i,["--version"]),u=c.match(Pd);l=u?u[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=de__default.join(we__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await yn("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 Ae=I("moduleInstaller");function Kt(e){switch(e){case "npm":return new Rs;case "homebrew":return new _s;case "curl":return new Ds}}async function co(e,t,r){try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){Ae.warn(`Failed to emit install failed event: ${String(n)}`);}}async function wn(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"){Ae.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 co(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 co(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 co(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}let i=Kt(r),a=false;try{a=await i.isAvailable();}catch(c){Ae.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 co(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ne,trigger:t});}catch(c){Ae.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);Ae.warn(`${r} install threw: ${u}`),l={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-o};}if(l.success){await Et({alias:e.alias,name:e.name,installedVersion:l.version??null,installMethod:l.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await v(b.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(u){Ae.warn(`Failed to emit install completed event: ${String(u)}`);}let c=await gS(e,t,n);return c?{...l,pendingInteractiveSetup:c}:e.configCheck&&!e.configCheck()?{...l,configCheckFailed:true}:l}return await co(e,t,l.error??{code:"UNKNOWN",message:"unknown error"}),l}async function gS(e,t,r){if(!e.postInstall)return null;let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return null;let o;if(typeof n=="function"){let s=await re(),i={credentials:s?{clientId:s.clientId,clientSecret:s.clientSecret,tenant:s.tenant}:null,customUrl:r??null};try{o=n(i);}catch(a){return Ae.warn(`postInstall function threw: ${String(a)}`),null}}else o=n;if(o.length===0)return null;if((e.postInstall.mode??"non-interactive")==="interactive")return o[0]??null;for(let s of o){if(s.length===0)continue;let i=spawnSync(s[0],s.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});i.status!==0&&(Ae.warn(`postInstall "${s.join(" ")}" exited with status ${i.status??"null"}`),i.stderr&&Ae.warn(i.stderr));}return null}async function Os(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Kt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await v(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:ne,trigger:"command"});}catch(a){Ae.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);Ae.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await Et({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await v(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){Ae.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Ae.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await v(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){Ae.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var kd=null;function Ad(){return kd}async function Ns(){let t=Nr().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 $d(n);(o||s)&&await Et({...r,installedVersion:o,installMethod:s});}}async function $d(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Kt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function xn(e){let t=await Promise.all(e.map(r=>hS(r)));return kd=t,t}async function hS(e){let t=Cd(e.versionCommand);t==="permission-denied"&&(yS(e.versionCommand[0]),t=Cd(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Kt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!et(e.alias)){let{installedVersion:l,installMethod:c}=await $d(e);await Et({alias:e.alias,name:e.name,installedVersion:l,installMethod:c,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Cd(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 yS(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 xS(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 Dd(e,t){let[r,n]=useState(()=>xS(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,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 S=f[p];S&&!S.module.required&&l(S.module.alias);}else if(m.tab){let S=f[p];if(S&&S.availableStrategies.length>1){let P=S.availableStrategies.indexOf(S.selectedStrategy??S.availableStrategies[0]),T=S.availableStrategies[(P+1)%S.availableStrategies.length];n(k=>k.map($=>$.module.alias===S.module.alias?{...$,selectedStrategy:T}:$));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Nd({probeResults:e,onConfirm:t}){let r=w(p=>p.focus),n=w(p=>p.actionMenuOpen),o=w(p=>p.setActionMenuOpen),s=w(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Dd(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 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(We,{itemName:m,actions:d,onAction:u,onClose:c})]})}var ES=/^https?:\/\/.+/;function Bd({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&&ES.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 TS(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 jd(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=TS(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 wn(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 Kd({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wu,{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 Gd({confirmedItems:e,customUrl:t}){let r=w(S=>S.setScreen),n=w(S=>S.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:c}=jd(e,t),u=o.some(S=>S.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Br().catch(()=>{}),n("list");let S=q().some(P=>P.name===ee);r(S?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!u&&!m.current){m.current=true;let S=setTimeout(p,1500);return ()=>clearTimeout(S)}},[i,l,u,p]),useInput((S,P)=>{P.return&&p();},{isActive:i});let f=o.filter(S=>S.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")),c>0&&h.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(S=>jsx(Kd,{module:S},S.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((S,P,T)=>(T>0&&S.push(jsx(Text,{children:" | "},`sep-${T}`)),S.push(P),S),[])}),jsx(Box,{paddingX:1,children:l>0||u?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function zd(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=w(p=>p.setFocus),c=w(p=>p.setScreen),u=useCallback(p=>{if(Id(p)){Br().catch(()=>{}),l("list");let g=q().some(h=>h.name===ee);c(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,c]);useEffect(()=>{let p=Ad();if(p){u(p);return}xn(Z).then(u).catch(()=>{n([]),t("selection");});},[u]);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(Nd,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Bd,{onConfirm:m}),e==="installation"&&jsx(Gd,{confirmedItems:o,customUrl:i})]})}var NS=I("ClaudeMdSuggestion"),BS=[`Install ${ee}`,"Skip for now"],US=["Retry","Skip for now"];function Yd(){let e=w(m=>m.setScreen),t=w(m=>m.setFocus),r=_(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{v(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,v(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ve(ee),o("installed");}catch(m){if(m instanceof Oe){o("installed");return}NS.warn(`Failed to install ${ee}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?US:BS;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(Yr,{}),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(qd,{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(wu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ee,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ee," 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:["/",ee]})]}),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 ",ee]}),jsx(qd,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function qd({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 VS=promisify(execFile),Ks="@ciandt-flow/cli";async function Zd(){let e=ne;if(ma.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ks};try{let t=await fetch(`https://registry.npmjs.org/${Ks}/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:Ks}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ks}}}async function Vs(e){try{return await VS(jt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Qd(e){let r=et(e.alias)?.installedVersion??null,n=null;try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`);if(!s.ok)throw new Error(`Registry returned ${s.status}`);n=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`);if(!s.ok)throw new Error(`GitHub returned ${s.status}`);n=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=r!==null&&n!==null&&r!==n;return {moduleAlias:e.alias,currentVersion:r,latestVersion:n,isOutdated:o}}async function ep(e,t){let r=et(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Kt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await Et({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function tp(e){let r=et(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function rp(){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([Zd(),xn(Z),Promise.all(Z.map(l=>Qd(l)))]);if(Ns(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Vs(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=Z.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await ep(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:tp(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await Br(),t(l=>({...l,outcome:"done"}));}catch{await Br(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function XS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wu,{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 qS({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 np(){let{outcome:e,items:t}=rp(),r=w(o=>o.setScreen),n=w(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=q().some(i=>i.name===ee);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(XS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(qS,{outcome:e})})]})}var ew={debug:"gray",info:"cyan",warn:"yellow",error:"red"},op=10;function sp(){let[e,t]=useState(li());useEffect(()=>al(()=>{t([...li()]);}),[]);let r=e.slice(-op);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",op,") \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:ew[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var ow=I("app"),sw={auth:Nl,starterKitSetup:hd,moduleSetup:zd,claudeMdSuggestion:Yd,verify:np,main:od};function lp(){let{setScreen:e,setFocus:t}=w.getState();e("auth"),t("auth");}function Bn(e){let{setScreen:t,setFocus:r}=w.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function cp(){v(b.CLI_SESSION_STARTED,{cli_version:ne,os:process.platform,node_version:process.version,duration_ms:Rt(),interface:"tui"}).catch(()=>{});}async function dp(){let e=await re();if(e&&_l()&&await Qt()){let{clientSecret:n,...o}=e;Je.getState().setCredentials(o),cp(),Bn(e);return}if(!e){lp();return}try{await er();}catch(n){ow.debug(`Token validation failed: ${String(n)}`),lp();return}cp();let{clientSecret:t,...r}=e;Je.getState().setCredentials(r),Bn(e);}function pp(){let{columns:e,rows:t}=useWindowSize(),r=w(a=>a.screen),n=sw[r],{pendingExit:o}=$l(),s=w(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=w.getState().debugPanelOpen;w.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(sp,{}),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 Fa(e,t={}){let r=jo({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Ko(r),await Lt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var pt=I("auth");function fp(){_e.clearFallbackFile(),_o();}var iw=3,mp=3,gp=` \u2139 The data collected during setup is used solely to improve
|
|
117
117
|
Flow's internal tools and will not be shared externally.
|
|
118
118
|
`;function Fr(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===`
|
|
119
119
|
`){l(),process.stdout.write(`
|
|
120
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 aw(){let e=Er();return process.stdout.write(`
|
|
121
121
|
`+R.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
122
|
-
`),(await Fr(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function hp(e,t){try{await
|
|
122
|
+
`),(await Fr(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function hp(e,t){try{await Fa(e);return}catch(r){if(!(r instanceof Cr))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${Er()} and retry.`);if(!await aw())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Fa(e,{allowOverwriteMalformed:true});}}async function yp(){for(let e=1;e<=mp;e++)try{return await ts()}catch{if(e===mp)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Sp(){let e=await yp();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
123
123
|
`+R.cyan(" ? ")+`Starter Kit:
|
|
124
124
|
`),e.forEach((t,r)=>{process.stdout.write(` ${R.cyan(`${r+1})`)} ${y(t.name)}
|
|
125
125
|
`);}),process.stdout.write(`
|
|
@@ -164,27 +164,27 @@ This will run: ${s}
|
|
|
164
164
|
\u2713 Setup complete. Tenant: ${r}. JWT written to ${Er()}.
|
|
165
165
|
|
|
166
166
|
`)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=y(e instanceof Error?e.message:"unknown error");return pt.error(`[auth] Unexpected error: ${t}`),process.stderr.write(R.red(` \u2717 Unexpected error: ${t}
|
|
167
|
-
`)),1}}async function
|
|
167
|
+
`)),1}}async function ja(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return lw({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await cw()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
168
168
|
`),130;throw t}}async function uw(){try{return process.stdout.write(`
|
|
169
169
|
`),(await Fr(R.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(R.yellow(` \u26A0 Logout cancelled
|
|
170
170
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
171
171
|
`),130;throw e}}async function Ip(e){if(!await re())return process.stdout.write(R.yellow(` \u26A0 You are not authenticated
|
|
172
|
-
`)),0;if(!e){let t=await uw();if(t!==null)return t}try{return await
|
|
172
|
+
`)),0;if(!e){let t=await uw();if(t!==null)return t}try{return await gl(),process.stdout.write(R.green(` \u2713 Credentials removed successfully
|
|
173
173
|
`)),0}catch{return process.stderr.write(R.red(` \u2717 Error removing credentials
|
|
174
174
|
`)),1}}async function bp(){let e=await re();return e?await Qt()?(process.stdout.write(`
|
|
175
175
|
`+R.bold(` Authenticated
|
|
176
176
|
`)),process.stdout.write(R.dim(" Tenant: ")+y(e.tenant)+`
|
|
177
177
|
`),process.stdout.write(R.dim(" Client ID: ")+y(e.clientId)+`
|
|
178
178
|
`),process.stdout.write(R.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
179
|
-
`),process.stdout.write(R.dim(" Config: ")+y(await
|
|
179
|
+
`),process.stdout.write(R.dim(" Config: ")+y(await hl())+`
|
|
180
180
|
`),process.stdout.write(`
|
|
181
181
|
`),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function dw(e){let t=q(),r;try{r=await or();}catch{r=[];}let n=new Set(t.map(o=>o.name));return v(b.CLI_CATALOG_VIEWED,{interface:j().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(zr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Wr(["","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 pw(e){let t=q(),r=await or(),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&&Ce(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return v(b.CLI_CATALOG_VIEWED,{interface:j().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(C("All plugins are up to date."),0):e.json?(zr(o),0):(Wr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
182
182
|
${o.length} plugin(s) outdated.
|
|
183
183
|
`),0)}async function mw(e){let t=q();if(v(b.CLI_CATALOG_VIEWED,{interface:j().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return C("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return zr(t),0;let r=[];try{r=await or();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=so.indexOf(s.scope??"user"),l=so.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return Wr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??ga(s.marketplace);return [s.name??"",s.version??"n/a",Vr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",qt(s.installedAt??"")]})),process.stdout.write(`
|
|
184
184
|
${t.length} plugin(s) installed.
|
|
185
|
-
`),0}async function vp(e){if(!await pe())return 1;try{return e.available?await dw(e):e.outdated?await pw(e):await mw(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}var oe=I("manage");function Js(e,t){return t?q().find(r=>r.name===e&&r.scope===t):q().find(r=>r.name===e)}function fw(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,C(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=
|
|
185
|
+
`),0}async function vp(e){if(!await pe())return 1;try{return e.available?await dw(e):e.outdated?await pw(e):await mw(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}var oe=I("manage");function Js(e,t){return t?q().find(r=>r.name===e&&r.scope===t):q().find(r=>r.name===e)}function fw(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,C(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Ka({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function gw(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(rn(e,r.scope));if(!await yt(`${t}Install external plugin "${i}"?
|
|
186
186
|
This will run: ${a}
|
|
187
|
-
[y/N] `))return oe.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=
|
|
187
|
+
[y/N] `))return oe.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Ka({text:`${t}Installing ${e}...`}).start());}let s=o?fw(t,o):void 0;try{let i=await ju(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?He({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?Re({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):te(`${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?He({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function hw(e,t,r){let n=r.silent?void 0:Ka({text:`${t}Installing ${e}...`}).start();if(en(e))return gw(e,t,r,n);try{let o=await ve(e,r);return n?.stop(),r.silent?Re({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):te(`${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 Oe)return r.silent?Re({status:"already_installed",plugin:e,message:o.message}):C(`${t}${o.message}`),{name:e,success:true};let s=X(o);return r.silent?He({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function yw(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;C(`
|
|
188
188
|
Installation summary: ${t} succeeded, ${r} failed`);}async function Gs(e,t={}){if(!await pe())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await hw(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?Re({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}:{}}))}):yw(r)),r.some(n=>!n.success)?1:0}async function Pp(e,t){if(!await pe())return 1;if(oe.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Js(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),E(`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 yt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return oe.debug(`[${e}] Uninstall cancelled by user`),C("Operation cancelled."),0}try{return oe.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await rs(e,t.scope),oe.info(`[${e}] Uninstalled successfully`),te("Plugin removed successfully"),0}catch(r){return oe.error(`[${e}] Failed to uninstall: ${X(r)}`),E(X(r)),1}}async function Ep(e,t={}){if(!await pe())return 1;oe.debug(`[${e}] Looking up installed plugin`);let r=Js(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return oe.debug(`[${e}] Already enabled, skipping`),C(`${r.name} is already enabled`),0;try{return oe.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Jn(e,"enabled",t.scope),oe.info(`[${e}] Enabled successfully`),te(`${r.name} enabled successfully`),0}catch(n){return oe.error(`[${e}] Failed to enable: ${X(n)}`),E(X(n)),1}}async function Cp(e,t={}){if(!await pe())return 1;oe.debug(`[${e}] Looking up installed plugin`);let r=Js(e,t.scope);if(!r)return oe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return oe.debug(`[${e}] Already disabled, skipping`),C(`${r.name} is already disabled`),0;try{return oe.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Jn(e,"disabled",t.scope),oe.info(`[${e}] Disabled successfully`),te(`${r.name} disabled successfully`),0}catch(n){return oe.error(`[${e}] Failed to disable: ${X(n)}`),E(X(n)),1}}async function Tp(e,t,r){r.silent||C(`${t}Updating ${e}...`);try{let n=await Ss(e,r);return r.silent?Re({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):te(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof nr)return r.silent?Re({status:"up_to_date",plugin:e,message:n.message}):C(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=X(n);return r.silent?He({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function Sw(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;C(`
|
|
189
189
|
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function ww(e,t,r){try{let n=await on(e);Ce(t,n.version,r.force)?C(`Would update ${e}: v${t} \u2192 v${n.version}`):C(`${e} is already up to date (v${t})`);}catch(n){return E(X(n)),1}return 0}function xw(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function Iw(e,t,r){let n=t.get(e.name);return n?e.version&&Ce(e.version,n,r)?(C(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(C(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(C(`Skipping ${e.name}: not found in catalog`),false)}async function bw(e,t){try{let r=await or(),n=xw(r),o=0;for(let s of e)Iw(s,n,t.force)&&o++;o===0&&C("All plugins are up to date");}catch(r){return E(X(r)),1}return 0}async function vw(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Tp(e[n].name,o,t);r.push(s);}return t.silent?Re({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}:{}}))}):Sw(r),r.some(n=>!n.success)?1:0}async function kp(e,t={}){if(!await pe())return 1;if(e){let o=Js(e,t.scope);return o?t.dryRun?ww(e,o.version??"",t):(await Tp(e,"",t)).success?0:1:(t.silent?He({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=q().filter(o=>o.marketplace===Q);return n.length===0?(t.silent?Re({status:"empty",message:"No plugins installed"}):C("No plugins installed"),0):t.dryRun?bw(n,t):vw(n,t)}var po=I("cli:bundle");function Pw(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 Ew(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
|
|
190
190
|
Bundle: ${y(e)} (${t.length} artifacts)
|
|
@@ -197,7 +197,7 @@ ${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable
|
|
|
197
197
|
`),a===l&&process.stdout.write(`
|
|
198
198
|
`);}});if(po.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&te(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");C(`${i.skipped} unavailable: ${a}`);}return 0}var $p=I("marketplace");function Tw(e){return `claude plugin marketplace add ${e}`}async function Mp(e,t){if(!await pe())return 1;let r;try{r=Qo(e);}catch(s){let i=X(s);return t.silent?He({status:"error",source:e,message:i}):E(i),1}$p.debug(`[marketplace] Adding marketplace source: ${r}`);let n=Tw(r);if(!t.force){let s=y(r),i=y(n);if(!await yt(`Add marketplace "${s}"?
|
|
199
199
|
This will run: ${i}
|
|
200
|
-
[y/N] `))return $p.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:
|
|
200
|
+
[y/N] `))return $p.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:Ka({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await he(n);return o?.stop(),s.exitCode!==0?(t.silent?He({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&C(`stdout: ${s.stdout}`)),1):(t.silent?Re({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(te(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&C(s.stdout)),0)}catch(s){o?.stop();let i=X(s);return t.silent?He({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}async function Mw(){return await re()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function Lw(){let e=Date.now();try{await or();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function Rw(){return await Qt()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function _w(){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 Lp(){process.stdout.write(`
|
|
201
201
|
`+R.bold(` FlowSetup CLI Diagnostics
|
|
202
202
|
|
|
203
203
|
`));let e=[{name:"Credentials",fn:Mw},{name:"Prompt Manager",fn:Lw},{name:"Valid Token",fn:Rw},{name:"Claude Code",fn:_w}],t=true;for(let r of e){let n=await r.fn(),o="",s=R.green;n.passed?o=R.green("[OK] "):(o=R.red("[FAIL]"),s=R.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
|
|
@@ -206,8 +206,8 @@ This will run: ${i}
|
|
|
206
206
|
|
|
207
207
|
`)),0):(process.stdout.write(R.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
208
208
|
|
|
209
|
-
`)),1)}var Nw=["github.com","www.github.com"],Bw=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Uw=/^([^@]+)@(.+)$/;function Fw(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function
|
|
210
|
-
`,"utf-8");}async function Hp(e,t,r){let n=kn(r);await Kp(n,async()=>{let o=await Zs(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Vp(o,r);});}async function Jp(e,t){let r=kn(t);await Kp(r,async()=>{let n=await Zs(t);e in n.skills&&(delete n.skills[e],await Vp(n,t));});}var Gp=I("skillInstaller");async function ix(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:j().interfaceType});}catch(o){Gp.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function ax(e,t){try{await v(b.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){Gp.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function lx(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!
|
|
209
|
+
`)),1)}var Nw=["github.com","www.github.com"],Bw=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,Uw=/^([^@]+)@(.+)$/;function Fw(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Va(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 jw(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=Va(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Va(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Ws(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(Fw(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:")&&Nw.includes(r.hostname))return jw(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(Bw);if(s){let i=s[1],a=s[2],l=s[3],c,u=a.match(Uw);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=Va(m));}return d}}return {type:"git",url:t}}function zs(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 Rp(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 Ja=new Set(["node_modules",".git","dist","build","__pycache__"]);function Op(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function Gw(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Ha(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function mo(e){try{let t=await readFile(e,"utf-8"),{data:r}=Rp(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 Np(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Ha(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Ja.has(a.name)).map(a=>Np(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ys(e,t){let r=[],n=new Set;if(t&&!Gw(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Ha(o)){let i=await mo(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 Ha(c)){let u=await mo(join(c,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let i=await Np(o);for(let a of i){let l=await mo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function Bp(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 jp=1,Zw={retries:5,minTimeout:50};async function Kp(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Tg.lock(e+".lock",{realpath:false,retries:Zw});try{return await t()}finally{await r();}}function Up(){return {version:jp,skills:{}}}async function Zs(e){let t=kn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<jp?Up():n}catch{return Up()}}function Qw(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function Vp(e,t){let r=kn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Qw(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
|
|
210
|
+
`,"utf-8");}async function Hp(e,t,r){let n=kn(r);await Kp(n,async()=>{let o=await Zs(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await Vp(o,r);});}async function Jp(e,t){let r=kn(t);await Kp(r,async()=>{let n=await Zs(t);e in n.skills&&(delete n.skills[e],await Vp(n,t));});}var Gp=I("skillInstaller");async function ix(e,t,r,n){try{await v(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:j().interfaceType});}catch(o){Gp.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function ax(e,t){try{await v(b.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){Gp.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function lx(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Ja.has(basename(r))});}async function cx(e,t,r){let n=qe(e.name),o=wr(t),s=join(o,n);if(!Op(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 lx(e.path,s);let a=zs(r)??r.url;return await Hp(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 Wp(e,t){let r=Ws(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 St(r.url,r.ref),o=n;let s=await Ys(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?Bp(s,i):s,l=[],c=r.ref??"latest";for(let u of a){let d=Date.now(),m=await cx(u,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await ix(u.name,t.scope,c,p):await ax(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 wt(n).catch(()=>{});}}var fx=I("skills");async function gx(e){try{await v(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:j().interfaceType});}catch(t){fx.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function hx(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 yx(e){let t=Ws(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else C(`Fetching skills from ${y(e)}...`),r=await St(t.url,t.ref),n=r;let o=await Ys(n,t.subpath);if(o.length===0)return C("No skills found in this source."),0;let i=zs(t)??y(e);C(`Found ${o.length} skill(s) in ${i}:
|
|
211
211
|
`);for(let a of o){let l=y(a.name),c=y(a.description);process.stdout.write(` ${R.bold(l)} ${R.dim(c)}
|
|
212
212
|
`);}return process.stdout.write(`
|
|
213
213
|
`),0}catch(n){return n instanceof lr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await wt(r).catch(()=>{});}}function Sx(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);te(`${n} installed ${R.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
@@ -217,13 +217,13 @@ This will run: ${i}
|
|
|
217
217
|
|
|
218
218
|
`);}return 0}async function Zp(e,t){let r=t.global?"global":"project";if(!e){let i=await qp(r);if(i.length===0)return C("No skills installed."),0;C("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
|
|
219
219
|
`);return process.stdout.write(`
|
|
220
|
-
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=qe(e),o=wr(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await hx(`Remove skill "${y(n)}"?`))return C("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Jp(n,r),await gx(n),te(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var Qs=I("transfer"),
|
|
220
|
+
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=qe(e),o=wr(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await hx(`Remove skill "${y(n)}"?`))return C("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await Jp(n,r),await gx(n),te(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var Qs=I("transfer"),Wa=1;function wx(e){return e.marketplace&&e.marketplace!==Q?`${e.name}@${e.marketplace}`:e.name}function xx(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&C(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),C(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function tm(e){let t=de__default.resolve(e.output);try{let r=q(),n={version:Wa,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"),te(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=X(r);return Qs.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function rm(e,t={}){if(!await pe())return 1;let r;try{let a=me__default.readFileSync(de__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${X(a)}`),1}if(r.version!==Wa)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Wa}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return C("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let c=`entry[${a}]`;Qs.warn(`Skipping ${c}: missing or invalid name`),o.push({name:c,error:"missing or invalid name"});}else l.type==="mcp"?(Qs.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&C(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(q().map(l=>l.name));xx(n,a);}if(t.dryRun)return C("Dry-run mode: no plugins were installed"),0;if(n.length===0){C(`
|
|
221
221
|
Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}C(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=wx(a);Qs.debug(`[${a.name}] Installing as "${c}" in scope "${l}"`),await Gs([c],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}C(`
|
|
222
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function B(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var bx=I("moduleProxy");function vx(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=ea.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 nm(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{bx.warn(`Failed to emit proxy executed event: ${String(s)}`);}),B(o);}async function sm(e,t){let r=Z.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),B(1);return}if(!await Ct(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),B(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Kt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),B(1);return}if(await vx("Would you like to install it now? [Y/n] ")){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await wn(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),B(1);return}await nm(r,t);}else C(`To install manually, run: flow modules install ${e}`),await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),B(1);return}await nm(r,t);}var Tx=promisify(execFile);async function kx(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await Tx(jt(),["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/${ne}`,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 Ax(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ce(t,r)?"outdated":"installed"}async function
|
|
222
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function B(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var bx=I("moduleProxy");function vx(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=ea.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 nm(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{bx.warn(`Failed to emit proxy executed event: ${String(s)}`);}),B(o);}async function sm(e,t){let r=Z.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),B(1);return}if(!await Ct(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),B(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Kt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),B(1);return}if(await vx("Would you like to install it now? [Y/n] ")){await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await wn(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),B(1);return}await nm(r,t);}else C(`To install manually, run: flow modules install ${e}`),await v(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),B(1);return}await nm(r,t);}var Tx=promisify(execFile);async function kx(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await Tx(jt(),["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/${ne}`,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 Ax(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ce(t,r)?"outdated":"installed"}async function za(){let e=await Promise.all(Z.map(async t=>{let[r,n]=await Promise.all([Ct(t.binaryName),kx(t)]),s=et(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=Ax(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Wr(["Name","Alias","Version","Status","Platform"],e),0}async function lm(e){let t=Z.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await xn([t]);if(r.alreadyInstalled){let i=et(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return C(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Ka({text:`Installing ${t.name}...`}).start(),s;try{s=await wn(t,"on_demand",n);}finally{o.stop();}return s.success?(te(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function im(e,t){let r=Ka({text:`Updating ${e.name}...`}).start(),n;try{n=await Os(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 cm(e){if(e!==null){let n=Z.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=et(n.alias);return o?.installMethod?await im(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Nr().filter(n=>n.installMethod!==null);if(t.length===0)return C("No installed modules to update."),0;let r=0;for(let n of t){let o=Z.find(i=>i.alias===n.alias);if(!o)continue;await im(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${ne}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
223
223
|
Without arguments, opens the interactive interface (TUI).
|
|
224
224
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
225
225
|
Examples:
|
|
226
|
-
$ flow setup init`).action(async()=>{let u=await
|
|
226
|
+
$ flow setup init`).action(async()=>{let u=await ja();B(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",`
|
|
227
227
|
Examples:
|
|
228
228
|
$ flow plugin list
|
|
229
229
|
$ flow plugin list --available
|
|
@@ -274,16 +274,16 @@ Examples:
|
|
|
274
274
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
275
275
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
276
276
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
277
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(u,d,m)=>{Le("cli",{verbose:m.verbose,silent:m.silent});let p=await
|
|
277
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(u,d,m)=>{Le("cli",{verbose:m.verbose,silent:m.silent});let p=await Gu(u,d,m);B(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",`
|
|
278
278
|
Examples:
|
|
279
279
|
$ flow mcp remove notion
|
|
280
280
|
$ flow mcp remove notion --scope project
|
|
281
|
-
$ flow mcp remove playwright-mcp --force`).action(async(u,d)=>{Le("cli",{verbose:d.verbose,silent:d.silent});let m=await
|
|
281
|
+
$ flow mcp remove playwright-mcp --force`).action(async(u,d)=>{Le("cli",{verbose:d.verbose,silent:d.silent});let m=await Wu(u,d);B(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("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
282
282
|
Examples:
|
|
283
283
|
$ flow auth login
|
|
284
284
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
|
|
285
285
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
|
|
286
|
-
$ flow auth login --verbose`).action(async u=>{Le("cli",{verbose:u.verbose});let d=await
|
|
286
|
+
$ flow auth login --verbose`).action(async u=>{Le("cli",{verbose:u.verbose});let d=await ja(u);B(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
287
287
|
Examples:
|
|
288
288
|
$ flow auth logout
|
|
289
289
|
$ flow auth logout --force`).action(async u=>{let d=await Ip(u.force);B(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
@@ -307,16 +307,16 @@ Examples:
|
|
|
307
307
|
$ flow bundle install "Squad Setup Bundle"
|
|
308
308
|
$ flow bundle install "My React Kit" --verbose`).action(async(u,d)=>{Le("cli",{verbose:d.verbose});let m=await Ap(u);B(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
309
309
|
Examples:
|
|
310
|
-
$ flow health`).action(async()=>{let u=await Lp();B(u);});let c=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");c.action(async()=>{let u=await
|
|
310
|
+
$ flow health`).action(async()=>{let u=await Lp();B(u);});let c=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");c.action(async()=>{let u=await za();B(u);}),c.command("list").description("List available and installed modules").addHelpText("after",`
|
|
311
311
|
Examples:
|
|
312
|
-
$ flow modules list`).action(async()=>{let u=await
|
|
312
|
+
$ flow modules list`).action(async()=>{let u=await za();B(u);}),c.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
313
313
|
Examples:
|
|
314
314
|
$ flow modules install metrics
|
|
315
315
|
$ flow modules install dashboard`).action(async u=>{let d=await lm(u);B(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",`
|
|
316
316
|
Examples:
|
|
317
317
|
$ flow modules update
|
|
318
|
-
$ flow modules update metrics`).action(async u=>{let d=await cm(u??null);B(d);}),t.addCommand(c);for(let u of Z)t.command(u.alias).description(u.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await sm(u.alias,d);});return t.hook("preAction",()=>{Ns();}),t}function Lx(){return de__default.join(we__default.homedir(),".claude","settings.json")}function pm(){let e=Lx();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 Bx=I("updateChecker"),Ux=promisify(execFile),Fx=1440*60*1e3,mm=3e4;function jx(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"update.lock")}async function fm(e){try{let{stdout:t}=await Ux(jt(),["view",e,"version"],{timeout:mm,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Kx(e){let t=new AbortController,r=setTimeout(()=>t.abort(),mm);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 Vx(e){return e.versionCheck.type==="npm-registry"?fm(e.versionCheck.package):Kx(e.versionCheck.repo)}async function Hx(){let e=await fm("@ciandt-flow/cli");return e&&Ce(ne,e)?(Vs({currentVersion:ne,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function Jx(){let e=Nr().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<Fx)return;let s=await Vx(r);try{await Et({...t,lastChecked:new Date().toISOString()});}catch(i){Bx.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ce(t.installedVersion,s)&&Os(r,"background").catch(()=>{});}));}async function
|
|
318
|
+
$ flow modules update metrics`).action(async u=>{let d=await cm(u??null);B(d);}),t.addCommand(c);for(let u of Z)t.command(u.alias).description(u.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await sm(u.alias,d);});return t.hook("preAction",()=>{Ns();}),t}function Lx(){return de__default.join(we__default.homedir(),".claude","settings.json")}function pm(){let e=Lx();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 Bx=I("updateChecker"),Ux=promisify(execFile),Fx=1440*60*1e3,mm=3e4;function jx(){let e=process.env.FLOW_HOME??de__default.join(we__default.homedir(),".flow");return de__default.join(e,"update.lock")}async function fm(e){try{let{stdout:t}=await Ux(jt(),["view",e,"version"],{timeout:mm,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Kx(e){let t=new AbortController,r=setTimeout(()=>t.abort(),mm);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 Vx(e){return e.versionCheck.type==="npm-registry"?fm(e.versionCheck.package):Kx(e.versionCheck.repo)}async function Hx(){let e=await fm("@ciandt-flow/cli");return e&&Ce(ne,e)?(Vs({currentVersion:ne,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function Jx(){let e=Nr().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<Fx)return;let s=await Vx(r);try{await Et({...t,lastChecked:new Date().toISOString()});}catch(i){Bx.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ce(t.installedVersion,s)&&Os(r,"background").catch(()=>{});}));}async function qa(){let e=pm();if(e===false)return;let t=jx();me__default.mkdirSync(de__default.dirname(t),{recursive:true});let r=null;try{r=await Tg.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await Hx().catch(()=>null);n&&process.stdout.write(`
|
|
319
319
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
320
320
|
Restart flow to apply the update.
|
|
321
321
|
|
|
322
|
-
`);}await Jx().catch(()=>{});}finally{await r().catch(()=>{});}}var Wx=I("cli"),
|
|
322
|
+
`);}await Jx().catch(()=>{});}finally{await r().catch(()=>{});}}var Wx=I("cli"),Ya=um(async()=>{Le("tui"),El("tui"),Cl(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=w.getState();Rn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=w.getState();Rn("sigterm",t,r).finally(()=>process.exit(143));}),await qa().catch(()=>{}),await kc().catch(t=>{Wx.error(`Failed to init catalog registry: ${String(t)}`);}),await dp();let{waitUntilExit:e}=render(jsx(pp,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Ya.hook("preAction",async(e,t)=>{t!==Ya&&await qa().catch(()=>{});});Ya.parse();
|