@ciandt-flow/cli 2.9.0-beta.47 → 2.9.0-beta.48
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 +10 -10
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -13,7 +13,7 @@ import*as kt from'crypto';import {randomUUID,createHash}from'crypto';import*as C
|
|
|
13
13
|
`);}function bo(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
14
|
`);}function ve(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
15
|
`);}function Ne(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
-
`);}function $(e){return e instanceof Error?e.message:String(e)}function qa(e){let a=new Date(e);return isNaN(a.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(a)}var j=H(()=>{"use strict";});async function _h(e,a){let o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,r=setInterval(()=>{process.stderr.write(`\r${o[t++%o.length]} ${e}`);},80);try{return await a()}finally{clearInterval(r),process.stderr.write("\r\x1B[2K");}}function Xh(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim().toLowerCase());});})}var On,Nn,Vh,
|
|
16
|
+
`);}function $(e){return e instanceof Error?e.message:String(e)}function qa(e){let a=new Date(e);return isNaN(a.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(a)}var j=H(()=>{"use strict";});async function _h(e,a){let o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,r=setInterval(()=>{process.stderr.write(`\r${o[t++%o.length]} ${e}`);},80);try{return await a()}finally{clearInterval(r),process.stderr.write("\r\x1B[2K");}}function Xh(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim().toLowerCase());});})}var On,Nn,Vh,re,vo,Gn=H(()=>{"use strict";I();j();On=promisify(execFile),Nn=promisify(exec),Vh=[{name:"apt",command:"sudo apt install -y libsecret-tools"},{name:"dnf",command:"sudo dnf install -y libsecret"},{name:"pacman",command:"sudo pacman -S --noconfirm libsecret"},{name:"apk",command:"sudo apk add libsecret-tools"},{name:"zypper",command:"sudo zypper install -y libsecret-tools"}],re=P("encryption:linux-keyvault");vo=class e{static async isAvailable(){try{let{stdout:a}=await Nn("command -v secret-tool");re.debug(`secret-tool found at: ${a.trim()}`);}catch{return re.debug("secret-tool binary not found in PATH"),!1}try{return await On("secret-tool",["lookup","service","__flow_connectivity_check__"]),re.debug("Secret Service D-Bus connectivity check passed"),!0}catch(a){let t=a.stderr?.trim()??"";return t.includes("org.freedesktop.secrets")?(re.debug(`Secret Service D-Bus not available: ${t}`),!1):(re.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let a of Vh)try{return await Nn(`command -v ${a.name}`),a}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;re.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let a=await e.detectPackageManager();if(!a)return re.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let o=await Xh(" ? Install secret-tool? This requires sudo. (y/N) ");if(o!=="y"&&o!=="yes")return !1;try{return re.info(`Running: ${a.command}`),await _h("Installing secret-tool...",()=>Nn(a.command)),e.isAvailable()}catch{return re.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(a,o){try{re.debug(`Looking up secret: service=${a}, account=${o}`);let{stdout:t}=await On("secret-tool",["lookup","service",a,"account",o]),r=t.trim();return re.debug(`secret-tool lookup result: ${r?"found":"empty"}`),r||null}catch(t){let r=t;return re.debug(`secret-tool lookup failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),null}}async setSecret(a,o,t){re.debug(`Storing secret: service=${a}, account=${o}`),re.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),re.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),re.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((r,i)=>{let s=spawn("secret-tool",["store","--label",a,"service",a,"account",o]),n="";s.stderr.on("data",d=>{n+=d.toString();}),s.stdin.end(t,"utf8"),s.on("close",d=>{d===0?(re.debug("secret-tool store succeeded"),r()):(re.error(`secret-tool store failed: code=${d}, stderr=${n.trim()}`),i(new Error(`secret-tool exited with code ${d}${n?`: ${n.trim()}`:""}`)));}),s.on("error",d=>{re.error(`secret-tool store spawn error: ${d.message}`),i(d);});});}async deleteSecret(a,o){try{return re.debug(`Deleting secret: service=${a}, account=${o}`),await On("secret-tool",["clear","service",a,"account",o]),re.debug("secret-tool clear succeeded"),!0}catch(t){let r=t;return re.debug(`secret-tool clear failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function jn(e,a){return `${e}:${a}`}function pr(e){return e.replace(/'/g,"''")}function ki(e){return ["-NoProfile","-NonInteractive","-Command",e]}function ob(e){return `Add-Type -TypeDefinition @'
|
|
17
17
|
${Un}
|
|
18
18
|
'@
|
|
19
19
|
[FlowCredManager]::Read('${pr(e)}')`}function tb(e,a,o){return `Add-Type -TypeDefinition @'
|
|
@@ -107,18 +107,18 @@ public class FlowCredManager {
|
|
|
107
107
|
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${a}", account="${o}"]: ${i}`;throw ya.error(s),new Error(s)}}async deleteSecret(a,o){try{let t=jn(a,o);ya.debug(`Deleting secret: target=${t}`);let r=rb(t),{stdout:i}=await Pi(ki(r)),s=i.trim()==="True";return ya.debug(`CredDelete result: ${s}`),s}catch(t){let r=t instanceof Error?t.message.split(`
|
|
108
108
|
`)[0]:"unknown error";return ya.debug(`Failed to delete secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function db(){let e=`${Ce.hostname()}${Ce.userInfo().username}`;return kt.scryptSync(e,sb,ib)}function cb(){let e=db(),a=new cr(e),o=Mn(a);return new Wn({projectName:Jn,serialize:o.serialize,deserialize:o.deserialize,configFileMode:384})}function Di(){return wi||(wi=cb()),wi}var ib,sb,Jn,nb,wi,Ve,mr=H(()=>{"use strict";kn();qn();ib=32,sb="flow-plugins-cli-fallback",Jn="flow-plugins-cli-fallback",nb={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)"};wi=null;Ve=class{warned=!1;async getSecret(a,o){return Di().get(`${a}:${o}`)??null}async setSecret(a,o,t){if(!this.warned){let r=nb[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, ${r}.
|
|
110
|
-
`),this.warned=!0;}Di().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=Di(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return Di().path}static hasExistingData(){try{let a=new Wn({projectName:Jn});return se.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new Wn({projectName:Jn});se.rmSync(a.path,{force:!0});}catch{}wi=null;}};});async function Hn(){if(Ve.hasExistingData())return new Ve;switch(process.platform){case "darwin":return await wt.isAvailable()?new wt:new Ve;case "linux":return await vo.isAvailable()?new vo:await vo.ensureInstalled()?new vo:new Ve;case "win32":return await Ct.isAvailable()?new Ct:new Ve;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var kl=H(()=>{"use strict";Fn();Gn();zn();mr();});var Pl=H(()=>{"use strict";kn();qn();kl();Fn();Gn();zn();mr();});async function yo(){return Ri||(Ri=Hn()),Ri}function Ai(){Ri=null;}async function Y(){let a=await(await yo()).getSecret($a,Qn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function ko(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw Dl.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await yo()).setSecret($a,Qn,JSON.stringify(e));}async function wl(){let e=await yo();await e.deleteSecret($a,Qn),await e.deleteSecret($a,Vn),await e.deleteSecret($a,_n);}async function Sl(){return (await yo()).getStoragePath()}async function Cl(e){await(await yo()).setSecret($a,Vn,JSON.stringify(e));}async function xi(){let a=await(await yo()).getSecret($a,Vn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Ei(e){await(await yo()).setSecret($a,_n,JSON.stringify(e));}async function Rt(){let a=await(await yo()).getSecret($a,_n);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Po(){let e=await xi();return e?new Date(e.expiresAt)>new Date:false}function La(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,Dl.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var Dl,$a,Qn,Vn,_n,Ri,Re=H(()=>{"use strict";Pl();I();Dl=P("config:credentials"),$a="flow-plugins-cli",Qn="credentials",Vn="token-cache",_n="user-info",Ri=null;});function At(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ii=H(()=>{"use strict";});function lb(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Xn(e){if(Rl.some(o=>o.test(e)))return true;let a=lb(e);return !!(a&&Rl.some(o=>o.test(a)))}function ub(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Fa(e,a){let o=ub(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Xn(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var Rl,_o=H(()=>{"use strict";Rl=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function gb(e){if(!Ka.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function fb(e){if(e instanceof HTTPError){let a=e.response.status;Kn.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&Al[o]?new Error(Al[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Kn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Kn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Xo(e){let a=Fa("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");gb(e.tenant);let o;try{o=await Xu.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await fb(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await ko(e),await Cl({accessToken:o.access_token,expiresAt:t});let r=At(o.access_token);await Ei({sub:r.sub,name:r.name,email:r.email});}var Kn,Al,Ti=H(()=>{"use strict";Re();Ii();_o();I();U();Kn=P("api:auth");Al={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 Oa(){if(await Po()){let t=await xi();if(t)return t.accessToken}xl.debug("Token expired or missing, re-authenticating...");let a=await Y();if(!a)throw new Error("Not authenticated. Run: flow auth login");Ve.clearFallbackFile(),Ai(),await Xo(a);let o=await xi();if(!o)throw new Error("Authentication succeeded but token was not persisted");return xl.debug("Token refreshed successfully"),o.accessToken}var xl,xt=H(()=>{"use strict";Re();Ti();mr();I();xl=P("lib:tokenProvider");});function eo(){return Xu.create({prefix:Fa("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Oa();e.headers.set("Authorization",`Bearer ${a}`);let o=await Y();o?.tenant&&Ka.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var xr=H(()=>{"use strict";_o();Re();xt();U();});function Ot(e,a){let o=eo();return a?o.get(e,{searchParams:{source:a}}):o.get(e)}async function Nt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var yd=H(()=>{"use strict";xr();});function Er(e){if(!e||!uy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Gt(e){return py.test(e)}function Bt(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function Pd(e){if(!my.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 jt(e,a){let o=Bt(e);Pd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function ss(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!gy.test(a)&&!fy.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var uy,py,my,gy,fy,To=H(()=>{"use strict";uy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;py=/^[^@]+@[^@]+$/;my=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;gy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,fy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Hu={};Zc(Hu,{FlowApiAdapter:()=>Ut});var hy,Ut,Dd=H(()=>{"use strict";xr();yd();I();To();hy=P("catalog.flow-api"),Ut=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Ot("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await Nt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Er(a);try{return await Ot(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await Nt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await eo().head("v1/plugins/catalog"),hy.debug("ping ok"),!0}catch{return !1}}};});function vy(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Vu(){return Qu??=vy(),Qu}var Qu,_u=H(()=>{"use strict";});var $u={};Zc($u,{GitRepoAdapter:()=>zt});function Ku(e,a){if(!yy.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var yy,zt,wd=H(()=>{"use strict";_u();_o();yy=/^[a-zA-Z0-9_.-]+$/;zt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Xn(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return Ku(n,"owner"),Ku(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Xu.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Xu.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Vu();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.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(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(vn),origins:new Set(yn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(vn)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(yn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Re();xt();Ii();U();_o();I();var Mi=P("api:metrics");function El(){return Fa("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Il(e,a,o){return Xu.post(e,{json:a,headers:o})}async function bb(e){let a=await Rt();if(a)return a;let o=At(e),t={sub:o.sub,name:o.name,email:o.email};return await Ei(t),t}async function C(e,a){let o=await Oa(),t=await bb(o),r=await Y();if(!Ka.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:bn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await Il(El(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Mi.debug(`Metrics event sent: ${e}`);}catch(s){throw Mi.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function Tl(e,a,o){try{let t=o&&Ka.test(o)?o:"unknown",r={action:e,booster:bn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Il(El(),r,{FlowTenant:t}),Mi.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Mi.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var vb={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ka={...vb};function Ml(e){let a=Date.now();ka={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Ko(e){ka.currentStep=e,ka.stepStart=Date.now();}function Z(){return {...ka}}function Do(){return ka.sessionStart===0?0:Date.now()-ka.sessionStart}function $o(){return ka.stepStart===0?0:Date.now()-ka.stepStart}function ql(){ka.tuiSessionStart=Date.now();}function Ll(){return ka.tuiSessionStart===0?0:Date.now()-ka.tuiSessionStart}I();var yb=3e3,kb=P("abandonment");async function qi(e){let{currentStep:a,sessionStart:o}=Z();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:Do()};try{await Promise.race([C(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),yb))]);}catch(r){kb.warn(`Abandonment event failed: ${String(r)}`);}}function Fl(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var Pb=3e3,Db=P("session-end");async function fr(e,a,o){let t=Ll(),i=[C(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(qi(e));try{await Fl(Promise.all(i).then(()=>{}),Pb);}catch(s){Db.warn(`Session end event failed: ${String(s)}`);}}var Rb=2e3;function Nl(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),fr("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},Rb);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var Ib=16;function Gl({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(Ib)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function Bl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();vt.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:yt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function jl({plan:e}){return 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:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function Ul(){return 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"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Ti();U();function et(){return de__default.join(Ce__default.homedir(),".claude","settings.json")}function Wl(e){return `${(e&&e.trim().length>0?e.trim():ni).replace(/\/+$/,"")}/flow-litellm/`}function Dr(){let e=et();if(!se__default.existsSync(e))return {status:"missing"};let a=se__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function Fi(e){let a=et();se__default.mkdirSync(de__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;se__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,a);}function Jl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function td(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Hl(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var Nb=3600,at=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function wr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function Gb(e){return Ob.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Nb})}function Oi(e,a={}){let o=Dr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new at;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?td(o.settings):null,i=o.status==="ok"?Hl(o.settings):null,s=a.jwtOverride??Gb(e),n=Wl(e.customUrl),d=Jl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function Ni(e){Fi(e.merged);}function Ql(){let e=Dr();return e.status!=="ok"?false:td(e.settings)!==null}Re();Oe();function Bb(){let e=nl();if(!se__default.existsSync(e))return {};try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return {}}}var rd=null;function jb(){return rd===null&&(rd=Bb()),rd}function Co(){return !!jb().ENABLE_EXPERIMENTAL_BETAS}U();function Jb(){return ce.filter(e=>e.platforms[process.platform]?.status==="supported")}function _l(e){let a=Jb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Gi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=de__default.join(Ce__default.homedir(),".claude","settings.json"),o=se__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}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 a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??ni),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},Hb={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},ce=Co()?[Gi,Hb]:[Gi];Re();I();var Xb=P("moduleState");function ji(){let e=process.env.FLOW_HOME??de__default.join(Ce__default.homedir(),".flow");return de__default.join(e,"modules.json")}var Kb={retries:5,minTimeout:50};async function Xl(e,a){se__default.mkdirSync(de__default.dirname(e),{recursive:true});let o=await _b.lock(e+".lock",{realpath:false,retries:Kb});try{return await a()}finally{await o();}}function Kl(){let e=ji();if(!se__default.existsSync(e))return [];try{let a=JSON.parse(se__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(Xb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),se__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return se__default.rmSync(e,{force:true}),[]}}function ot(){return Kl()}function $l(e){let a=ji();se__default.mkdirSync(de__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};se__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,a);}function ta(e){return ot().find(a=>a.alias===e)??null}async function Pa(e){let a=ji();await Xl(a,async()=>{let o=Kl(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,$l(o);});}async function tt(){let e=ji();se__default.existsSync(e)||await Xl(e,async()=>{se__default.existsSync(e)||$l([]);});}var Zb=promisify(execFile);function Ro(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function Ga(e){let a=process.platform==="win32"?"where":"which";try{return await Zb(a,[e]),!0}catch{return false}}function Ya(){return process.platform==="win32"?"npm.cmd":"npm"}var Yl=promisify(execFile),It=class{type="npm";async isAvailable(){return Ga("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=Ro(a,"npm");if(!o)return null;try{let{stdout:t}=await Yl(Ya(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=Ro(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await Yl(Ya(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Ui=promisify(execFile),rv=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,zi=class{type="homebrew";async isAvailable(){return Ga("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=Ro(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=Ro(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Ui("brew",["tap",r.tap]),await Ui("brew",["trust",r.tap])),await Ui("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Ui("brew",["list","--versions",a]),t=o.trim().match(rv);return t?t[2]:null}catch{return null}}};var Tt=promisify(execFile),eu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function au(){let e=process.env.FLOW_HOME??de__default.join(Ce__default.homedir(),".flow");return de__default.join(e,"bin")}var Wi=class{type="curl";async isAvailable(){return Ga("curl")}async install(a){let o=Date.now(),t=Ro(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=de__default.join(au(),de__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await Tt(t,["--version"]),i=r.match(eu);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=de__default.join(Ce__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Tt("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{se__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return se__default.chmodSync(i,448),await Tt("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{se__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=au(),s=de__default.join(i,de__default.basename(t.binaryName)),n=false;try{if(se__default.mkdirSync(i,{recursive:!0}),n=!0,await Tt("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return se__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}se__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await Tt(s,["--version"]),c=l.match(eu);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{se__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=de__default.join(Ce__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Tt("curl",["-L","--fail","-o",t,o]);let r=se__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=se__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{se__default.unlinkSync(t);}catch{}}}};I();var ou="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(ou=e.version);}catch{}var re=ou;var Te=P("moduleInstaller");function ja(e){switch(e){case "npm":return new It;case "homebrew":return new zi;case "curl":return new Wi}}async function Sr(e,a,o){try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Te.warn(`Failed to emit install failed event: ${String(t)}`);}}async function xo(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=ja(o),l=false;try{l=await d.isAvailable();}catch(u){Te.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:re,trigger:a});}catch(u){Te.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let p=u instanceof Error?u.message:String(u);Te.warn(`${o} install threw: ${p}`),c={success:false,error:{code:"INSTALL_THREW",message:p},durationMs:Date.now()-s};}if(c.success){await Pa({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(m){Te.warn(`Failed to emit install completed event: ${String(m)}`);}let{pendingCmd:u,failed:p}=await uv(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:p?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Sr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function uv(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Y(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Te.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Te.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Te.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Te.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Ji(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=ja(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:re,trigger:"command"});}catch(n){Te.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Te.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await Pa({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Te.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await C(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Te.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Te.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Hi=P("flowAiObsSetup");async function Qi(e,a){try{if(!await new It().isAvailable().catch(()=>!1))return Hi.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await xo(Gi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Hi.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Hi.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Hi.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function tu(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var pv=P("useAuthSetup");function ru(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,p]=useState("fields"),[m,g]=useState(null),f=useRef(0),h=useRef(false),{setCredentials:v,setJustAuthenticated:k}=oa(),T=()=>{p("fields"),g(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{C(w.CLI_SESSION_STARTED,{cli_version:re,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});},A=async W=>{h.current=true;let _={...o.current,customUrl:t.current??void 0};try{W&&Ni(W),await ko(_);}catch(Q){d(Q instanceof Error?Q.message:"Failed to persist credentials"),T(),h.current=false;return}let{clientSecret:E,...B}=_;v(B),k(true),L(),await Qi(t.current,r.current).catch(Q=>pv.warn(`installFlowAiObs threw unexpectedly: ${String(Q)}`)),Vi({starterKit:B.starterKit});},M=async()=>A(),F=async W=>A(W),N=W=>{try{let _={...o.current,customUrl:t.current??void 0};return Oi(_,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(_){return _ instanceof at?(p("malformedConfirm"),null):(d(_ instanceof Error?_.message:"Failed to read settings.json"),p("fields"),null)}},oe=()=>{let W=N(true);W&&(g(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let _;try{_=wr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=_,p("customUrl");},J=W=>{t.current=W,p("email");},ae=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&La(W),c(true),d(null),f.current+=1;try{await Xo(o.current);let _=N(!1);_&&(g(_),p("preview"));}catch(_){let E=_ instanceof Error?_.message:"Authentication failed";d(E),Tl(w.CLI_AUTH_FAILED,{error_code:tu(_),attempt:f.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,p("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:m,isCommittingRef:h,setJwtValue:a,setJwtError:s,cancelToFields:T,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ae,commitAndProceed:F,skipJwtAndProceed:M,planPersistOverwrite:oe}}U();j();function iu(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:p,commitAndProceed:m,skipJwtAndProceed:g,planPersistOverwrite:f}=ru(),[h,v]=useState("confirm"),[k,T]=useState(""),L=useRef(""),[A,M]=useState(false);return useEffect(()=>{r==="customUrl"&&(v("confirm"),L.current="",T(""),M(false));},[r]),useInput((F,N)=>{if(!(t||s.current)){if(r==="preview"){N.return&&i?m(i):N.escape?g():F==="q"&&l();return}if(r==="malformedConfirm"){N.return?f():N.escape&&l();return}if(r==="customUrl"){if(h==="confirm")F==="y"||F==="Y"?v("input"):(F==="n"||F==="N"||N.return)&&u(null);else if(N.escape)L.current="",T(""),v("confirm");else if(N.return){let oe=L.current.trim();oe.length>0&&ht.test(oe)?(M(false),u(oe)):oe.length>0&&M(true);}else N.backspace||N.delete?(L.current=L.current.slice(0,-1),T(L.current)):F&&!N.ctrl&&!N.meta&&(L.current=L.current+F,T(L.current),M(false));return}r!=="email"&&N.return&&c();}},{isActive:true}),r==="customUrl"?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,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:k}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:bt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Bl,{onConfirm:p})]}):r==="preview"&&i?jsx(jl,{plan:i}):r==="malformedConfirm"?jsx(Ul,{}):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:jsx(Box,{marginBottom:1,children:jsx(Gl,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",b(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function qt(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(bv,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",re]})})]})}var cu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ie=Co()?cu:cu.slice(0,3);function vv(e){return ie.findIndex(a=>a.id===e)}function nd(e,a,o){let t=vv(o.activeTab);if(a.rightArrow||a.tab){let r=ie[(t+1)%ie.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=ie[(t-1+ie.length)%ie.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:ie[t]?.focus??"list"}]:[]}var pu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function mu({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ie.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${pu[o]} (${e})`:pu[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function fu(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var hu=Object.keys(ho).map((e,a)=>({key:a<3?String(a+2):String((a+5)%10),type:e,...ho[e]})),bu=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...el[e]}));function vu(){let e=y(t=>t.catalogFilters),a=hu.every(t=>e.types.has(t.type)),o=bu.every(t=>e.origins.has(t.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),hu.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.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:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),bu.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function yu({type:e}){let{label:a,color:o}=ho[e];return jsx(Text,{color:o,children:a})}U();function Du({origin:e}){return e===dr?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}j();var Xi=Sv.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx(yu,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(Du,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",qa(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function Lt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function Cu({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(Lt,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(Xi,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function xu({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function Iu({groups:e,emptyMessage:a}){let o=y(m=>m.selectedIndex),t=[],r=0;for(let m of e){t.push({kind:"header",label:m.label,pathHint:m.pathHint,key:`h-${m.scope}`});for(let g of m.items)t.push({kind:"item",item:g,itemIndex:r,key:`i-${m.scope}-${g.name}-${g.marketplace??""}`}),r++;}if(r===0)return jsx(Lt,{message:a});let s=t.findIndex(m=>m.kind==="item"&&m.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,p=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(m=>m.kind==="header"?jsx(xu,{label:m.label,pathHint:m.pathHint},m.key):jsx(Xi,{item:m.item,isSelected:m.itemIndex===o},m.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:p>0?`\u2193 ${p} more below`:" "})})]})}var Mv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function qv({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(fu,{}),jsx(vu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Mv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(Iu,{groups:t,emptyMessage:o}):jsx(Cu,{items:e,emptyMessage:o})]})}function Tu({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(qv,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var Ov={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 Ki(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Ov[e],a?" | Ctrl+D: debug log":""]})})}j();function Mu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",b(e)]})}):null}function $i({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function gd(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Ou=20;function Yi(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*Ou),i="\u2588".repeat(r)+"\u2591".repeat(Ou-r),s=`${gd(e)} / ${gd(a)}`;return {bar:i,percent:t,label:s}}function Zi({received:e,total:a}){let{bar:o,percent:t,label:r}=Yi(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function es({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="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:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var vd=Object.entries(Xa),ju=[...vd.map(([,e])=>e.actionLabel),"Cancel"],Uu=Object.fromEntries(vd.map(([,e])=>[e.actionLabel,e.description]));function zu(e){let a=vd.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var $v=P("provider.registry"),Yv=3e4,os=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+Yv}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&$v.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var Zv={user:"global",project:"project",local:"local"};function ts(e){return e?Zv[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Io=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};xr();yd();I();var oy=P("catalog.registry"),rs=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);oy.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};Oe();var ly={retries:5,minTimeout:50};async function kd(e,a){mkdirSync(dirname(e),{recursive:true});let o=await _b.lock(e+".lock",{realpath:false,retries:ly});try{return await a()}finally{await o();}}var is=class{filePath;constructor(a){this.filePath=a??sl();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await kd(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await kd(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await kd(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};Dd();var ge=new rs,ao=new is,ky=["flow-harness"];function Py(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?ky:e.split(",").map(a=>a.trim()).filter(Boolean)}ge.register(new Ut);for(let e of Py())ge.register(new Ut(e));var Yu=false;async function Zu(){if(Yu)return;Yu=true;let e=await ao.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(wd(),$u));for(let o of e)ge.register(new a(o.id,o.name,o.source));}To();var ep=2;async function oo(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(Dd(),Hu));return new a(e).fetchItems()}return ge.fetchAll()}async function ap(){return ge.fetchAllWithErrors()}async function Wt(e,a){Er(e);try{return await Ot(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await Nt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function op(e,a,o){Er(e);try{let t=await Ot(`v1/plugins/${e}/archive`,o),r=t.headers.get("x-archive-size"),i=r?Number(r):NaN,s=Number.isFinite(i)&&i>0?i:0,n=s>0,d=t.body;if(!d)throw new Error("Failed to download plugin: response has no body");let l=d.getReader(),c=[],u=0;for(;;){let{done:p,value:m}=await l.read();if(p)break;if(u+=m.byteLength,n&&u>s*ep)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*ep}`);c.push(m),n&&a?.(u,s);}return Buffer.concat(c)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await Nt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function ns(){try{let{profiles:e}=await eo().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}}Oe();Oe();async function tp(e,a){let o=de.resolve(a);await Ua.mkdir(o,{recursive:true});let t=de.join(de.dirname(o),`${randomUUID()}.zip`);try{await Ua.writeFile(t,e);let r=await wy.Open.file(t),i=de.normalize(o+de.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=de.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(de.resolve(de.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await Ua.unlink(t);}catch{}}}async function Sd(e){await Ua.rm(e,{recursive:true,force:true});}async function Mo(){let e=rl();await Ua.mkdir(de.dirname(e),{recursive:true});try{await Ua.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await _b.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();U();function Ry(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||pe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function sp(e){let a=ui(e);if(!se__default.existsSync(a))return null;try{return JSON.parse(se__default.readFileSync(a,"utf-8"))}catch{return null}}function Ay(e){let a=sp(e);if(a)return a;let o=Ry(e),t=ui(e);return se__default.mkdirSync(de__default.dirname(t),{recursive:true}),Cd(o,e),o}function Cd(e,a){let o=ui(a),t=`${o}.${randomUUID()}.tmp`;se__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(t,o);}function xy(e){let a=e||pe,o=Jo(),t={};try{se__default.existsSync(o)&&(t=JSON.parse(se__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:tl(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(r,o);}function np(e,a,o){ia(e.name),xy(o);let t=wn(e.name,o);se__default.mkdirSync(de__default.dirname(t),{recursive:true});try{se__default.lstatSync(t),se__default.rmSync(t,{recursive:!0,force:!0});}catch{}se__default.cpSync(a,t,{recursive:true,dereference:true});let r=Ay(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Cd(r,o));}function Rd(e,a){ia(e);let o=wn(e,a);try{se__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=sp(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&Cd(t,a);}j();I();var Iy=P("mcpConfigReader"),Ty=500,My=512;function qy(){return de__default.join(Ce__default.homedir(),".claude.json")}function Ly(){return de__default.join(process.cwd(),".mcp.json")}function cp(e){if(!se__default.existsSync(e))return null;try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return Iy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e){if(!Ir(e))return {};let a=e.mcpServers;return Ir(a)?a:{}}function xd(e,a){return Object.keys(e).slice(0,Ty).map(t=>({name:b(t.slice(0,My)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function up(){let e=[],a=qy(),o=cp(a);if(Ir(o)){let n=o,d=Ad(n);e.push(...xd(d,"user"));let l=process.cwd();if(Ir(n.projects)){let c=n.projects[l];if(Ir(c)){let u=Ad(c);e.push(...xd(u,"local"));}}}let t=Ly(),r=cp(t),i=Ad(r);e.push(...xd(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var sa=P("storage");async function Oy(e,a,o){try{await C(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:Z().interfaceType});}catch(t){sa.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function Ny(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;C(t,{tool_id:e,source:o,interface:Z().interfaceType}).catch(r=>sa.warn(`Failed to send ${a} metrics: ${String(r)}`));}function Md(){return de__default.join(Ce__default.homedir(),".claude","plugins","installed_plugins.json")}function Gy(){return de__default.join(Ce__default.homedir(),".claude","plugins")}function ds(e){let a;try{a=se__default.realpathSync(e);}catch{a=de__default.resolve(e);}let o=de__default.resolve(Gy()),t=de__default.resolve(de__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+de__default.sep),i=a.startsWith(t+de__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function mp(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(Ce__default.homedir(),".claude","settings.json")}function Ae(){let e=Md();if(!se__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function qd(){let e=Md();try{let a=await se__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function By(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function gp(e,a){try{se__default.mkdirSync(de__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;se__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,e);}catch(o){throw By(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function na(e){gp(Md(),e);}function Tr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function jy(e,a){let o=de__default.join(e,".claude-plugin"),t=de__default.join(o,"plugin.json");if(se__default.existsSync(t))try{return JSON.parse(se__default.readFileSync(t,"utf-8"))}catch{return null}let r=de__default.join(o,"marketplace.json");if(se__default.existsSync(r))try{let i=JSON.parse(se__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function Mr(e="user"){let a=mp(e);if(!se__default.existsSync(a))return {};try{return JSON.parse(se__default.readFileSync(a,"utf-8"))}catch{return {}}}function cs(e,a="user"){gp(mp(a),e);}function Uy(e,a){let{name:o,marketplace:t}=Tr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],!r)throw sa.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function zy(e,a){let{name:o,marketplace:t}=Tr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],r?{key:r,name:o}:null}function Ed(e="user"){return Mr(e).enabledPlugins??{}}function Id(e,a="user"){let o=Mr(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,cs(o,a);}function qr(e,a,o="user"){let t=Mr(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},cs(t,o);}function Wy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function le(){let e=Ae(),a=Ed(),o=Ed("project"),t=Ed("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:p}=Tr(l),m=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return Wy(m).map(f=>{let h=jy(f.installPath,u),k=(r[f.scope]??a)[l];return {name:u,marketplace:p,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:h?.description,author:h?.author,status:k===false?"disabled":"enabled"}})}),s=up(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function pp(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Lr(e,a){sa.debug(`[${e}] Acquiring lock to uninstall`);let o=await Mo();try{let t=Ae(),r=zy(e,t.plugins);if(!r)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:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);sa.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),ds(d.installPath);let l=de__default.dirname(d.installPath);ds(l),sa.debug(`[${s}] Removing directory: ${l}`),se__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...p}=t.plugins;na({...t,plugins:p}),Id(i,a),Rd(s,pp(i));}else t.plugins[i]=c,na(t),Id(i,a);}else {sa.debug(`[${s}] Resolved key: ${i}`);for(let c of n){ds(c.installPath);let u=de__default.dirname(c.installPath);ds(u),sa.debug(`[${s}] Removing directory: ${u}`),se__default.rmSync(u,{recursive:!0,force:!0}),Id(i,c.scope);}Rd(s,pp(i));let{[i]:d,...l}=t.plugins;na({...t,plugins:l});}await Oy(s,n[0].origin??"internal",n[0].type??"skill"),sa.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Fr(e,a,o){sa.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Mo();try{let r=Ae(),{key:i,name:s}=Uy(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";sa.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),qr(i,a==="enabled",d),Ny(s,a,l),sa.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}Oe();function Ld(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,Ld(o)]))}function Or(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(Ld(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(Ld(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=Or(i,r):o[t]=r;}return o}I();var Fd=P("bundleContent"),ls="${CLAUDE_PLUGIN_ROOT}/hooks/";function Jy(e){return e.split(ls).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Od(e){return typeof e=="string"?Jy(e):Array.isArray(e)?e.map(Od):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Od(o)])):e}function Hy(e,a){let o=de__default.join(e,"rules");if(!se__default.existsSync(o))return 0;let t=se__default.readdirSync(o).filter(i=>i.endsWith(".md")&&se__default.lstatSync(de__default.join(o,i)).isFile());if(t.length===0)return 0;let r=Pt(a);se__default.mkdirSync(r,{recursive:true});for(let i of t)se__default.copyFileSync(de__default.join(o,i),de__default.join(r,i));return t.length}function Qy(e,a){let o=de__default.join(e,"hooks","hooks.json");if(!se__default.existsSync(o))return 0;let t;try{t=JSON.parse(se__default.readFileSync(o,"utf-8"));}catch(g){return Fd.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(g)}`),0}let r=t.hooks;if(!r||typeof r!="object"||Array.isArray(r))return 0;let i=de__default.join(e,"hooks"),s=Cn(a),n=new Set,d=g=>{if(typeof g=="string"&&g.includes(ls)){let f=g.slice(g.indexOf(ls)+ls.length),h=/^([^"'\s]+)/.exec(f);h&&n.add(h[1]);}else Array.isArray(g)?g.forEach(d):g!==null&&typeof g=="object"&&Object.values(g).forEach(d);};d(r);let l=0;if(n.size>0){se__default.mkdirSync(s,{recursive:true});for(let g of n){let f=de__default.join(i,g);se__default.existsSync(f)&&(se__default.copyFileSync(f,de__default.join(s,g)),l++);}}let c=Od(r),u=Mr(a),p=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},m=Or(p,c);return cs({...u,hooks:m},a),l}function fp(e,a){let o=Hy(e,a),t=Qy(e,a);o>0&&Fd.debug(`Copied ${o} rule file(s) to ${Pt(a)}`),t>0&&Fd.debug(`Copied ${t} hook script(s) to ${Cn(a)}`);}U();I();var Vy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,_y=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ia(e){if(!Vy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Xy(e){if(!_y.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 Lo=P("installer");function Ky(e,a,o){let t=`${e}@${o||pe}`,i=Ae().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function $y(e,a,o){o&&await Sd(a);try{Lo.debug(`[${a}] Extracting archive...`),await tp(e,a);}catch(t){throw await Sd(a),t}}function Yy(e,a,o,t,r,i="claude-code",s){let n=Ae(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],na(n),qr(e,true,t);}async function Zy(e,a,o,t,r,i){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:Z().interfaceType});}catch(s){Lo.warn(`Failed to send install metrics: ${String(s)}`);}}async function ek(e,a,o,t){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(r){Lo.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function je(e,a={}){let o=Date.now(),t=null;try{Lo.debug(`[${e}] Acquiring lock...`),t=await Mo();let{pluginKey:r,alreadyInstalled:i}=Ky(e,a.force,a.source),{source:s}=a;Lo.debug(`[${e}] Fetching manifest...`);let n=await Wt(e,s);ia(n.name),Xy(n.version),Lo.debug(`[${e}] Downloading archive...`);let d=await op(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=ol(n.name,n.version,a.source);await $y(d,u,!!i&&!!a.force),fp(u,l),Yy(r,u,n.version,l,"internal",a.providerId,c),np(n,u,a.source);let p=Date.now()-o;Lo.debug(`[${e}] Installed successfully in ${p}ms`);let m={name:n.name,version:n.version,path:u,duration_ms:p};return a.skipMetrics||await Zy(n.name,n.version,p,ts(l),"internal",c),m}catch(r){throw await ek(e,r,"internal",a.type??"skill"),Lo.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();j();Re();xt();I();var ak=P("commands:helpers");async function he(){let e=await Y();if(!e)return S("Not authenticated. Run: flow auth login"),false;e.customUrl&&La(e.customUrl);try{await Oa();}catch(a){return ak.debug(`Token validation failed: ${String(a)}`),S("Session expired. Run: flow auth login"),false}return true}async function ee(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function Fo(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim());});})}var ok="\x1B[A",tk="\x1B[B";function hp(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function rk(e,a){return e.map((o,t)=>hp(o,t===a)).join(`
|
|
110
|
+
`),this.warned=!0;}Di().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=Di(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return Di().path}static hasExistingData(){try{let a=new Wn({projectName:Jn});return se.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new Wn({projectName:Jn});se.rmSync(a.path,{force:!0});}catch{}wi=null;}};});async function Hn(){if(Ve.hasExistingData())return new Ve;switch(process.platform){case "darwin":return await wt.isAvailable()?new wt:new Ve;case "linux":return await vo.isAvailable()?new vo:await vo.ensureInstalled()?new vo:new Ve;case "win32":return await Ct.isAvailable()?new Ct:new Ve;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var kl=H(()=>{"use strict";Fn();Gn();zn();mr();});var Pl=H(()=>{"use strict";kn();qn();kl();Fn();Gn();zn();mr();});async function yo(){return Ri||(Ri=Hn()),Ri}function Ai(){Ri=null;}async function Y(){let a=await(await yo()).getSecret($a,Qn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function ko(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw Dl.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await yo()).setSecret($a,Qn,JSON.stringify(e));}async function wl(){let e=await yo();await e.deleteSecret($a,Qn),await e.deleteSecret($a,Vn),await e.deleteSecret($a,_n);}async function Sl(){return (await yo()).getStoragePath()}async function Cl(e){await(await yo()).setSecret($a,Vn,JSON.stringify(e));}async function xi(){let a=await(await yo()).getSecret($a,Vn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Ei(e){await(await yo()).setSecret($a,_n,JSON.stringify(e));}async function Rt(){let a=await(await yo()).getSecret($a,_n);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function Po(){let e=await xi();return e?new Date(e.expiresAt)>new Date:false}function La(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,Dl.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var Dl,$a,Qn,Vn,_n,Ri,Re=H(()=>{"use strict";Pl();I();Dl=P("config:credentials"),$a="flow-plugins-cli",Qn="credentials",Vn="token-cache",_n="user-info",Ri=null;});function At(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Ii=H(()=>{"use strict";});function lb(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Xn(e){if(Rl.some(o=>o.test(e)))return true;let a=lb(e);return !!(a&&Rl.some(o=>o.test(a)))}function ub(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Fa(e,a){let o=ub(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Xn(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var Rl,_o=H(()=>{"use strict";Rl=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function gb(e){if(!Ka.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function fb(e){if(e instanceof HTTPError){let a=e.response.status;Kn.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&Al[o]?new Error(Al[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Kn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Kn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Xo(e){let a=Fa("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");gb(e.tenant);let o;try{o=await Xu.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await fb(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await ko(e),await Cl({accessToken:o.access_token,expiresAt:t});let r=At(o.access_token);await Ei({sub:r.sub,name:r.name,email:r.email});}var Kn,Al,Ti=H(()=>{"use strict";Re();Ii();_o();I();U();Kn=P("api:auth");Al={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 Oa(){if(await Po()){let t=await xi();if(t)return t.accessToken}xl.debug("Token expired or missing, re-authenticating...");let a=await Y();if(!a)throw new Error("Not authenticated. Run: flow auth login");Ve.clearFallbackFile(),Ai(),await Xo(a);let o=await xi();if(!o)throw new Error("Authentication succeeded but token was not persisted");return xl.debug("Token refreshed successfully"),o.accessToken}var xl,xt=H(()=>{"use strict";Re();Ti();mr();I();xl=P("lib:tokenProvider");});function eo(){return Xu.create({prefix:Fa("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Oa();e.headers.set("Authorization",`Bearer ${a}`);let o=await Y();o?.tenant&&Ka.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var xr=H(()=>{"use strict";_o();Re();xt();U();});function Ot(e,a){let o=eo();return a?o.get(e,{searchParams:{source:a}}):o.get(e)}async function Nt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var yd=H(()=>{"use strict";xr();});function Er(e){if(!e||!uy.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Gt(e){return py.test(e)}function Bt(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function Pd(e){if(!my.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 jt(e,a){let o=Bt(e);Pd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function ss(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!gy.test(a)&&!fy.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var uy,py,my,gy,fy,To=H(()=>{"use strict";uy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;py=/^[^@]+@[^@]+$/;my=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;gy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,fy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Hu={};Zc(Hu,{FlowApiAdapter:()=>Ut});var hy,Ut,Dd=H(()=>{"use strict";xr();yd();I();To();hy=P("catalog.flow-api"),Ut=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Ot("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await Nt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Er(a);try{return await Ot(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await Nt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await eo().head("v1/plugins/catalog"),hy.debug("ping ok"),!0}catch{return !1}}};});function vy(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Vu(){return Qu??=vy(),Qu}var Qu,_u=H(()=>{"use strict";});var $u={};Zc($u,{GitRepoAdapter:()=>zt});function Ku(e,a){if(!yy.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var yy,zt,wd=H(()=>{"use strict";_u();_o();yy=/^[a-zA-Z0-9_.-]+$/;zt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Xn(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return Ku(n,"owner"),Ku(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Xu.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Xu.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Vu();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.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(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(vn),origins:new Set(yn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(vn)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(yn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Re();xt();Ii();U();_o();I();var Mi=P("api:metrics");function El(){return Fa("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Il(e,a,o){return Xu.post(e,{json:a,headers:o})}async function bb(e){let a=await Rt();if(a)return a;let o=At(e),t={sub:o.sub,name:o.name,email:o.email};return await Ei(t),t}async function C(e,a){let o=await Oa(),t=await bb(o),r=await Y();if(!Ka.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:bn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await Il(El(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Mi.debug(`Metrics event sent: ${e}`);}catch(s){throw Mi.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function Tl(e,a,o){try{let t=o&&Ka.test(o)?o:"unknown",r={action:e,booster:bn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Il(El(),r,{FlowTenant:t}),Mi.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Mi.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var vb={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ka={...vb};function Ml(e){let a=Date.now();ka={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Ko(e){ka.currentStep=e,ka.stepStart=Date.now();}function Z(){return {...ka}}function Do(){return ka.sessionStart===0?0:Date.now()-ka.sessionStart}function $o(){return ka.stepStart===0?0:Date.now()-ka.stepStart}function ql(){ka.tuiSessionStart=Date.now();}function Ll(){return ka.tuiSessionStart===0?0:Date.now()-ka.tuiSessionStart}I();var yb=3e3,kb=P("abandonment");async function qi(e){let{currentStep:a,sessionStart:o}=Z();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:Do()};try{await Promise.race([C(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),yb))]);}catch(r){kb.warn(`Abandonment event failed: ${String(r)}`);}}function Fl(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var Pb=3e3,Db=P("session-end");async function fr(e,a,o){let t=Ll(),i=[C(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(qi(e));try{await Fl(Promise.all(i).then(()=>{}),Pb);}catch(s){Db.warn(`Session end event failed: ${String(s)}`);}}var Rb=2e3;function Nl(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),fr("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},Rb);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var Ib=16;function Gl({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(Ib)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function Bl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();vt.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:yt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function jl({plan:e}){return 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:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function Ul(){return 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"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Ti();U();function et(){return de__default.join(Ce__default.homedir(),".claude","settings.json")}function Wl(e){return `${(e&&e.trim().length>0?e.trim():ni).replace(/\/+$/,"")}/flow-litellm/`}function Dr(){let e=et();if(!se__default.existsSync(e))return {status:"missing"};let a=se__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function Fi(e){let a=et();se__default.mkdirSync(de__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;se__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,a);}function Jl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function td(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Hl(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var Nb=3600,at=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function wr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function Gb(e){return Ob.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Nb})}function Oi(e,a={}){let o=Dr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new at;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?td(o.settings):null,i=o.status==="ok"?Hl(o.settings):null,s=a.jwtOverride??Gb(e),n=Wl(e.customUrl),d=Jl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function Ni(e){Fi(e.merged);}function Ql(){let e=Dr();return e.status!=="ok"?false:td(e.settings)!==null}Re();Oe();function Bb(){let e=nl();if(!se__default.existsSync(e))return {};try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return {}}}var rd=null;function jb(){return rd===null&&(rd=Bb()),rd}function Co(){return !!jb().ENABLE_EXPERIMENTAL_BETAS}U();function Jb(){return ce.filter(e=>e.platforms[process.platform]?.status==="supported")}function _l(e){let a=Jb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Gi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=de__default.join(Ce__default.homedir(),".claude","settings.json"),o=se__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}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 a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??ni),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},Hb={alias:"dashboard",name:"ccboard",binaryName:"ccboard",description:"Claude Code session monitoring dashboard",docs:"https://github.com/FlorianBruniaux/ccboard",platforms:{darwin:{status:"supported",strategies:[{type:"homebrew",formula:"ccboard",tap:"FlorianBruniaux/tap"},{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},linux:{status:"supported",strategies:[{type:"curl",url:"https://raw.githubusercontent.com/FlorianBruniaux/ccboard/main/install.sh",mode:"script"}]},win32:{status:"experimental"}},versionCheck:{type:"github-releases",repo:"florianbruniaux/ccboard"},versionCommand:["ccboard","--version"],hasOwnUpdateCheck:false},ce=Co()?[Gi,Hb]:[Gi];Re();I();var Xb=P("moduleState");function ji(){let e=process.env.FLOW_HOME??de__default.join(Ce__default.homedir(),".flow");return de__default.join(e,"modules.json")}var Kb={retries:5,minTimeout:50};async function Xl(e,a){se__default.mkdirSync(de__default.dirname(e),{recursive:true});let o=await _b.lock(e+".lock",{realpath:false,retries:Kb});try{return await a()}finally{await o();}}function Kl(){let e=ji();if(!se__default.existsSync(e))return [];try{let a=JSON.parse(se__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(Xb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),se__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return se__default.rmSync(e,{force:true}),[]}}function ot(){return Kl()}function $l(e){let a=ji();se__default.mkdirSync(de__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};se__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,a);}function ta(e){return ot().find(a=>a.alias===e)??null}async function Pa(e){let a=ji();await Xl(a,async()=>{let o=Kl(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,$l(o);});}async function tt(){let e=ji();se__default.existsSync(e)||await Xl(e,async()=>{se__default.existsSync(e)||$l([]);});}var Zb=promisify(execFile);function Ro(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function Ga(e){let a=process.platform==="win32"?"where":"which";try{return await Zb(a,[e]),!0}catch{return false}}function Ya(){return process.platform==="win32"?"npm.cmd":"npm"}var Yl=promisify(execFile),It=class{type="npm";async isAvailable(){return Ga("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=Ro(a,"npm");if(!o)return null;try{let{stdout:t}=await Yl(Ya(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=Ro(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await Yl(Ya(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Ui=promisify(execFile),rv=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,zi=class{type="homebrew";async isAvailable(){return Ga("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=Ro(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=Ro(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Ui("brew",["tap",r.tap]),await Ui("brew",["trust",r.tap])),await Ui("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Ui("brew",["list","--versions",a]),t=o.trim().match(rv);return t?t[2]:null}catch{return null}}};var Tt=promisify(execFile),eu=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function au(){let e=process.env.FLOW_HOME??de__default.join(Ce__default.homedir(),".flow");return de__default.join(e,"bin")}var Wi=class{type="curl";async isAvailable(){return Ga("curl")}async install(a){let o=Date.now(),t=Ro(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=de__default.join(au(),de__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await Tt(t,["--version"]),i=r.match(eu);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=de__default.join(Ce__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await Tt("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{se__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return se__default.chmodSync(i,448),await Tt("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{se__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=au(),s=de__default.join(i,de__default.basename(t.binaryName)),n=false;try{if(se__default.mkdirSync(i,{recursive:!0}),n=!0,await Tt("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return se__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}se__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await Tt(s,["--version"]),c=l.match(eu);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{se__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=de__default.join(Ce__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await Tt("curl",["-L","--fail","-o",t,o]);let r=se__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=se__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{se__default.unlinkSync(t);}catch{}}}};I();var ou="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(ou=e.version);}catch{}var oe=ou;var Te=P("moduleInstaller");function ja(e){switch(e){case "npm":return new It;case "homebrew":return new zi;case "curl":return new Wi}}async function Sr(e,a,o){try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Te.warn(`Failed to emit install failed event: ${String(t)}`);}}async function xo(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Te.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=ja(o),l=false;try{l=await d.isAvailable();}catch(u){Te.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Sr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:a});}catch(u){Te.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let p=u instanceof Error?u.message:String(u);Te.warn(`${o} install threw: ${p}`),c={success:false,error:{code:"INSTALL_THREW",message:p},durationMs:Date.now()-s};}if(c.success){await Pa({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(m){Te.warn(`Failed to emit install completed event: ${String(m)}`);}let{pendingCmd:u,failed:p}=await uv(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:p?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Sr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function uv(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Y(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Te.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Te.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Te.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Te.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Ji(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=ja(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await C(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:"command"});}catch(n){Te.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Te.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await Pa({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await C(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Te.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await C(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Te.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await C(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Te.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Hi=P("flowAiObsSetup");async function Qi(e,a){try{if(!await new It().isAvailable().catch(()=>!1))return Hi.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await xo(Gi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Hi.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Hi.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Hi.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function tu(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var pv=P("useAuthSetup");function ru(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,p]=useState("fields"),[m,g]=useState(null),f=useRef(0),h=useRef(false),{setCredentials:v,setJustAuthenticated:k}=oa(),T=()=>{p("fields"),g(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{C(w.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});},A=async W=>{h.current=true;let _={...o.current,customUrl:t.current??void 0};try{W&&Ni(W),await ko(_);}catch(Q){d(Q instanceof Error?Q.message:"Failed to persist credentials"),T(),h.current=false;return}let{clientSecret:E,...B}=_;v(B),k(true),L(),await Qi(t.current,r.current).catch(Q=>pv.warn(`installFlowAiObs threw unexpectedly: ${String(Q)}`)),Vi({starterKit:B.starterKit});},M=async()=>A(),F=async W=>A(W),N=W=>{try{let _={...o.current,customUrl:t.current??void 0};return Oi(_,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(_){return _ instanceof at?(p("malformedConfirm"),null):(d(_ instanceof Error?_.message:"Failed to read settings.json"),p("fields"),null)}},te=()=>{let W=N(true);W&&(g(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let _;try{_=wr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=_,p("customUrl");},J=W=>{t.current=W,p("email");},ae=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&La(W),c(true),d(null),f.current+=1;try{await Xo(o.current);let _=N(!1);_&&(g(_),p("preview"));}catch(_){let E=_ instanceof Error?_.message:"Authentication failed";d(E),Tl(w.CLI_AUTH_FAILED,{error_code:tu(_),attempt:f.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,p("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:m,isCommittingRef:h,setJwtValue:a,setJwtError:s,cancelToFields:T,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ae,commitAndProceed:F,skipJwtAndProceed:M,planPersistOverwrite:te}}U();j();function iu(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:p,commitAndProceed:m,skipJwtAndProceed:g,planPersistOverwrite:f}=ru(),[h,v]=useState("confirm"),[k,T]=useState(""),L=useRef(""),[A,M]=useState(false);return useEffect(()=>{r==="customUrl"&&(v("confirm"),L.current="",T(""),M(false));},[r]),useInput((F,N)=>{if(!(t||s.current)){if(r==="preview"){N.return&&i?m(i):N.escape?g():F==="q"&&l();return}if(r==="malformedConfirm"){N.return?f():N.escape&&l();return}if(r==="customUrl"){if(h==="confirm")F==="y"||F==="Y"?v("input"):(F==="n"||F==="N"||N.return)&&u(null);else if(N.escape)L.current="",T(""),v("confirm");else if(N.return){let te=L.current.trim();te.length>0&&ht.test(te)?(M(false),u(te)):te.length>0&&M(true);}else N.backspace||N.delete?(L.current=L.current.slice(0,-1),T(L.current)):F&&!N.ctrl&&!N.meta&&(L.current=L.current+F,T(L.current),M(false));return}r!=="email"&&N.return&&c();}},{isActive:true}),r==="customUrl"?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,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&h==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&h==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:k}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:bt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[fo," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(Bl,{onConfirm:p})]}):r==="preview"&&i?jsx(jl,{plan:i}):r==="malformedConfirm"?jsx(Ul,{}):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:jsx(Box,{marginBottom:1,children:jsx(Gl,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",b(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function qt(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(bv,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",oe]})})]})}var cu=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ie=Co()?cu:cu.slice(0,3);function vv(e){return ie.findIndex(a=>a.id===e)}function nd(e,a,o){let t=vv(o.activeTab);if(a.rightArrow||a.tab){let r=ie[(t+1)%ie.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=ie[(t-1+ie.length)%ie.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:ie[t]?.focus??"list"}]:[]}var pu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function mu({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ie.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${pu[o]} (${e})`:pu[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function fu(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var hu=Object.keys(ho).map((e,a)=>({key:a<3?String(a+2):String((a+5)%10),type:e,...ho[e]})),bu=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...el[e]}));function vu(){let e=y(t=>t.catalogFilters),a=hu.every(t=>e.types.has(t.type)),o=bu.every(t=>e.origins.has(t.origin));return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,flexWrap:"wrap",children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),hu.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.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:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),bu.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function yu({type:e}){let{label:a,color:o}=ho[e];return jsx(Text,{color:o,children:a})}U();function Du({origin:e}){return e===dr?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}j();var Xi=Sv.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx(yu,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(Du,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",qa(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function Lt({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function Cu({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(Lt,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(Xi,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function xu({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function Iu({groups:e,emptyMessage:a}){let o=y(m=>m.selectedIndex),t=[],r=0;for(let m of e){t.push({kind:"header",label:m.label,pathHint:m.pathHint,key:`h-${m.scope}`});for(let g of m.items)t.push({kind:"item",item:g,itemIndex:r,key:`i-${m.scope}-${g.name}-${g.marketplace??""}`}),r++;}if(r===0)return jsx(Lt,{message:a});let s=t.findIndex(m=>m.kind==="item"&&m.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,p=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(m=>m.kind==="header"?jsx(xu,{label:m.label,pathHint:m.pathHint},m.key):jsx(Xi,{item:m.item,isSelected:m.itemIndex===o},m.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:p>0?`\u2193 ${p} more below`:" "})})]})}var Mv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function qv({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(fu,{}),jsx(vu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Mv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(Iu,{groups:t,emptyMessage:o}):jsx(Cu,{items:e,emptyMessage:o})]})}function Tu({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(qv,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var Ov={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 Ki(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Ov[e],a?" | Ctrl+D: debug log":""]})})}j();function Mu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",b(e)]})}):null}function $i({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function gd(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Ou=20;function Yi(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*Ou),i="\u2588".repeat(r)+"\u2591".repeat(Ou-r),s=`${gd(e)} / ${gd(a)}`;return {bar:i,percent:t,label:s}}function Zi({received:e,total:a}){let{bar:o,percent:t,label:r}=Yi(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function es({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="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:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var vd=Object.entries(Xa),ju=[...vd.map(([,e])=>e.actionLabel),"Cancel"],Uu=Object.fromEntries(vd.map(([,e])=>[e.actionLabel,e.description]));function zu(e){let a=vd.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var $v=P("provider.registry"),Yv=3e4,os=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+Yv}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&$v.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var Zv={user:"global",project:"project",local:"local"};function ts(e){return e?Zv[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Io=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};xr();yd();I();var oy=P("catalog.registry"),rs=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);oy.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};Oe();var ly={retries:5,minTimeout:50};async function kd(e,a){mkdirSync(dirname(e),{recursive:true});let o=await _b.lock(e+".lock",{realpath:false,retries:ly});try{return await a()}finally{await o();}}var is=class{filePath;constructor(a){this.filePath=a??sl();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await kd(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await kd(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await kd(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};Dd();var ge=new rs,ao=new is,ky=["flow-harness"];function Py(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?ky:e.split(",").map(a=>a.trim()).filter(Boolean)}ge.register(new Ut);for(let e of Py())ge.register(new Ut(e));var Yu=false;async function Zu(){if(Yu)return;Yu=true;let e=await ao.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(wd(),$u));for(let o of e)ge.register(new a(o.id,o.name,o.source));}To();var ep=2;async function oo(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(Dd(),Hu));return new a(e).fetchItems()}return ge.fetchAll()}async function ap(){return ge.fetchAllWithErrors()}async function Wt(e,a){Er(e);try{return await Ot(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await Nt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function op(e,a,o){Er(e);try{let t=await Ot(`v1/plugins/${e}/archive`,o),r=t.headers.get("x-archive-size"),i=r?Number(r):NaN,s=Number.isFinite(i)&&i>0?i:0,n=s>0,d=t.body;if(!d)throw new Error("Failed to download plugin: response has no body");let l=d.getReader(),c=[],u=0;for(;;){let{done:p,value:m}=await l.read();if(p)break;if(u+=m.byteLength,n&&u>s*ep)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*ep}`);c.push(m),n&&a?.(u,s);}return Buffer.concat(c)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await Nt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function ns(){try{let{profiles:e}=await eo().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}}Oe();Oe();async function tp(e,a){let o=de.resolve(a);await Ua.mkdir(o,{recursive:true});let t=de.join(de.dirname(o),`${randomUUID()}.zip`);try{await Ua.writeFile(t,e);let r=await wy.Open.file(t),i=de.normalize(o+de.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=de.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(de.resolve(de.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await Ua.unlink(t);}catch{}}}async function Sd(e){await Ua.rm(e,{recursive:true,force:true});}async function Mo(){let e=rl();await Ua.mkdir(de.dirname(e),{recursive:true});try{await Ua.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await _b.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}Oe();U();function Ry(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||pe,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function sp(e){let a=ui(e);if(!se__default.existsSync(a))return null;try{return JSON.parse(se__default.readFileSync(a,"utf-8"))}catch{return null}}function Ay(e){let a=sp(e);if(a)return a;let o=Ry(e),t=ui(e);return se__default.mkdirSync(de__default.dirname(t),{recursive:true}),Cd(o,e),o}function Cd(e,a){let o=ui(a),t=`${o}.${randomUUID()}.tmp`;se__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(t,o);}function xy(e){let a=e||pe,o=Jo(),t={};try{se__default.existsSync(o)&&(t=JSON.parse(se__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:tl(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(r,o);}function np(e,a,o){ia(e.name),xy(o);let t=wn(e.name,o);se__default.mkdirSync(de__default.dirname(t),{recursive:true});try{se__default.lstatSync(t),se__default.rmSync(t,{recursive:!0,force:!0});}catch{}se__default.cpSync(a,t,{recursive:true,dereference:true});let r=Ay(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Cd(r,o));}function Rd(e,a){ia(e);let o=wn(e,a);try{se__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=sp(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&Cd(t,a);}j();I();var Iy=P("mcpConfigReader"),Ty=500,My=512;function qy(){return de__default.join(Ce__default.homedir(),".claude.json")}function Ly(){return de__default.join(process.cwd(),".mcp.json")}function cp(e){if(!se__default.existsSync(e))return null;try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return Iy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e){if(!Ir(e))return {};let a=e.mcpServers;return Ir(a)?a:{}}function xd(e,a){return Object.keys(e).slice(0,Ty).map(t=>({name:b(t.slice(0,My)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function up(){let e=[],a=qy(),o=cp(a);if(Ir(o)){let n=o,d=Ad(n);e.push(...xd(d,"user"));let l=process.cwd();if(Ir(n.projects)){let c=n.projects[l];if(Ir(c)){let u=Ad(c);e.push(...xd(u,"local"));}}}let t=Ly(),r=cp(t),i=Ad(r);e.push(...xd(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var sa=P("storage");async function Oy(e,a,o){try{await C(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:Z().interfaceType});}catch(t){sa.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function Ny(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;C(t,{tool_id:e,source:o,interface:Z().interfaceType}).catch(r=>sa.warn(`Failed to send ${a} metrics: ${String(r)}`));}function Md(){return de__default.join(Ce__default.homedir(),".claude","plugins","installed_plugins.json")}function Gy(){return de__default.join(Ce__default.homedir(),".claude","plugins")}function ds(e){let a;try{a=se__default.realpathSync(e);}catch{a=de__default.resolve(e);}let o=de__default.resolve(Gy()),t=de__default.resolve(de__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+de__default.sep),i=a.startsWith(t+de__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function mp(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(Ce__default.homedir(),".claude","settings.json")}function Ae(){let e=Md();if(!se__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(se__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function qd(){let e=Md();try{let a=await se__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function By(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function gp(e,a){try{se__default.mkdirSync(de__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;se__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),se__default.renameSync(o,e);}catch(o){throw By(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function na(e){gp(Md(),e);}function Tr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function jy(e,a){let o=de__default.join(e,".claude-plugin"),t=de__default.join(o,"plugin.json");if(se__default.existsSync(t))try{return JSON.parse(se__default.readFileSync(t,"utf-8"))}catch{return null}let r=de__default.join(o,"marketplace.json");if(se__default.existsSync(r))try{let i=JSON.parse(se__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function Mr(e="user"){let a=mp(e);if(!se__default.existsSync(a))return {};try{return JSON.parse(se__default.readFileSync(a,"utf-8"))}catch{return {}}}function cs(e,a="user"){gp(mp(a),e);}function Uy(e,a){let{name:o,marketplace:t}=Tr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],!r)throw sa.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function zy(e,a){let{name:o,marketplace:t}=Tr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>Tr(s).name===o)[0],r?{key:r,name:o}:null}function Ed(e="user"){return Mr(e).enabledPlugins??{}}function Id(e,a="user"){let o=Mr(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,cs(o,a);}function qr(e,a,o="user"){let t=Mr(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},cs(t,o);}function Wy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function le(){let e=Ae(),a=Ed(),o=Ed("project"),t=Ed("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:p}=Tr(l),m=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return Wy(m).map(f=>{let h=jy(f.installPath,u),k=(r[f.scope]??a)[l];return {name:u,marketplace:p,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:h?.description,author:h?.author,status:k===false?"disabled":"enabled"}})}),s=up(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function pp(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Lr(e,a){sa.debug(`[${e}] Acquiring lock to uninstall`);let o=await Mo();try{let t=Ae(),r=zy(e,t.plugins);if(!r)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:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);sa.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),ds(d.installPath);let l=de__default.dirname(d.installPath);ds(l),sa.debug(`[${s}] Removing directory: ${l}`),se__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...p}=t.plugins;na({...t,plugins:p}),Id(i,a),Rd(s,pp(i));}else t.plugins[i]=c,na(t),Id(i,a);}else {sa.debug(`[${s}] Resolved key: ${i}`);for(let c of n){ds(c.installPath);let u=de__default.dirname(c.installPath);ds(u),sa.debug(`[${s}] Removing directory: ${u}`),se__default.rmSync(u,{recursive:!0,force:!0}),Id(i,c.scope);}Rd(s,pp(i));let{[i]:d,...l}=t.plugins;na({...t,plugins:l});}await Oy(s,n[0].origin??"internal",n[0].type??"skill"),sa.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Fr(e,a,o){sa.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Mo();try{let r=Ae(),{key:i,name:s}=Uy(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";sa.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),qr(i,a==="enabled",d),Ny(s,a,l),sa.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}Oe();function Ld(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,Ld(o)]))}function Or(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(Ld(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(Ld(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=Or(i,r):o[t]=r;}return o}I();var Fd=P("bundleContent"),ls="${CLAUDE_PLUGIN_ROOT}/hooks/";function Jy(e){return e.split(ls).join("$CLAUDE_PROJECT_DIR/.claude/hooks/")}function Od(e){return typeof e=="string"?Jy(e):Array.isArray(e)?e.map(Od):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Od(o)])):e}function Hy(e,a){let o=de__default.join(e,"rules");if(!se__default.existsSync(o))return 0;let t=se__default.readdirSync(o).filter(i=>i.endsWith(".md")&&se__default.lstatSync(de__default.join(o,i)).isFile());if(t.length===0)return 0;let r=Pt(a);se__default.mkdirSync(r,{recursive:true});for(let i of t)se__default.copyFileSync(de__default.join(o,i),de__default.join(r,i));return t.length}function Qy(e,a){let o=de__default.join(e,"hooks","hooks.json");if(!se__default.existsSync(o))return 0;let t;try{t=JSON.parse(se__default.readFileSync(o,"utf-8"));}catch(g){return Fd.warn(`hooks/hooks.json is not valid JSON \u2014 skipping: ${String(g)}`),0}let r=t.hooks;if(!r||typeof r!="object"||Array.isArray(r))return 0;let i=de__default.join(e,"hooks"),s=Cn(a),n=new Set,d=g=>{if(typeof g=="string"&&g.includes(ls)){let f=g.slice(g.indexOf(ls)+ls.length),h=/^([^"'\s]+)/.exec(f);h&&n.add(h[1]);}else Array.isArray(g)?g.forEach(d):g!==null&&typeof g=="object"&&Object.values(g).forEach(d);};d(r);let l=0;if(n.size>0){se__default.mkdirSync(s,{recursive:true});for(let g of n){let f=de__default.join(i,g);se__default.existsSync(f)&&(se__default.copyFileSync(f,de__default.join(s,g)),l++);}}let c=Od(r),u=Mr(a),p=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},m=Or(p,c);return cs({...u,hooks:m},a),l}function fp(e,a){let o=Hy(e,a),t=Qy(e,a);o>0&&Fd.debug(`Copied ${o} rule file(s) to ${Pt(a)}`),t>0&&Fd.debug(`Copied ${t} hook script(s) to ${Cn(a)}`);}U();I();var Vy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,_y=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ia(e){if(!Vy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Xy(e){if(!_y.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 Lo=P("installer");function Ky(e,a,o){let t=`${e}@${o||pe}`,i=Ae().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function $y(e,a,o){o&&await Sd(a);try{Lo.debug(`[${a}] Extracting archive...`),await tp(e,a);}catch(t){throw await Sd(a),t}}function Yy(e,a,o,t,r,i="claude-code",s){let n=Ae(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],na(n),qr(e,true,t);}async function Zy(e,a,o,t,r,i){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:Z().interfaceType});}catch(s){Lo.warn(`Failed to send install metrics: ${String(s)}`);}}async function ek(e,a,o,t){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(r){Lo.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function je(e,a={}){let o=Date.now(),t=null;try{Lo.debug(`[${e}] Acquiring lock...`),t=await Mo();let{pluginKey:r,alreadyInstalled:i}=Ky(e,a.force,a.source),{source:s}=a;Lo.debug(`[${e}] Fetching manifest...`);let n=await Wt(e,s);ia(n.name),Xy(n.version),Lo.debug(`[${e}] Downloading archive...`);let d=await op(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=ol(n.name,n.version,a.source);await $y(d,u,!!i&&!!a.force),fp(u,l),Yy(r,u,n.version,l,"internal",a.providerId,c),np(n,u,a.source);let p=Date.now()-o;Lo.debug(`[${e}] Installed successfully in ${p}ms`);let m={name:n.name,version:n.version,path:u,duration_ms:p};return a.skipMetrics||await Zy(n.name,n.version,p,ts(l),"internal",c),m}catch(r){throw await ek(e,r,"internal",a.type??"skill"),Lo.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();j();Re();xt();I();var ak=P("commands:helpers");async function he(){let e=await Y();if(!e)return S("Not authenticated. Run: flow auth login"),false;e.customUrl&&La(e.customUrl);try{await Oa();}catch(a){return ak.debug(`Token validation failed: ${String(a)}`),S("Session expired. Run: flow auth login"),false}return true}async function ee(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function Fo(e){let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim());});})}var ok="\x1B[A",tk="\x1B[B";function hp(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function rk(e,a){return e.map((o,t)=>hp(o,t===a)).join(`
|
|
111
111
|
`)}async function us(e,a){if(a.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((o,t)=>{let r=0;process.stdout.write(`${b(e)}
|
|
112
112
|
`),process.stdout.write(rk(a,r));let i="",s=c=>{if(i+=c,i===""){d(),t(new Error("SIGINT"));return}if(i==="\r"||i===`
|
|
113
113
|
`){d(),process.stdout.write(`
|
|
114
114
|
`),o(a[r].value);return}if(i===ok){r=(r-1+a.length)%a.length,n(),i="";return}if(i===tk){r=(r+1)%a.length,n(),i="";return}i.startsWith("\x1B")&&i.length<3||(i="");};function n(){process.stdout.write(`\x1B[${a.length-1}A`);for(let c=0;c<a.length;c++)process.stdout.write(`\r\x1B[2K${hp(a[c],c===r)}`),c<a.length-1&&process.stdout.write(`
|
|
115
115
|
`);}function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",s),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s);})}To();var Ht=P("claudeProxy"),zd="claude ",bp="flow ",Bd=class extends Error{constructor(a){super(`Invalid install command: "${a}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Jt=class extends Error{constructor(a){super(`Disallowed subcommand: "${a}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},ik=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,sk=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,nk={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},dk=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,ck=/^(flow|claude)\s+auth\s+login(\s|$)/,vp=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function yp(e){return vp.test(e.trim())}function lk(e){return vp.exec(e.trim())?.[2]??""}async function kp(e){let a=lk(e);Pd(a);let o=Date.now();Ht.debug(`[${a}] Executing: flow plugin install ${a}`);try{let t=await execa("flow",["plugin","install",a],{reject:!1});return {name:a,command:`flow plugin install ${a}`,exitCode:t.exitCode??1,stdout:t.stdout,stderr:t.stderr,duration_ms:Date.now()-o}}catch(t){throw Wd(t)?new jd:t}}function uk(e){Pp(e);let a=e.slice(zd.length);if(!ik.test(a))throw new Jt(e)}var ps=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},jd=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Pp(e){if(!e||!/^claude /.test(e))throw new Bd(e)}function pk(e){for(let a=0;a<e.length;a++){let o=e[a];if(o==="--")return;if(!o.startsWith("-"))continue;if(!sk.test(o))throw new Jt(`Unexpected flag: ${o}`);let t=nk[o];if(t!==void 0){let r=e[a+1];if(r===void 0||r.startsWith("-"))throw new Jt(`Flag ${o} requires a value`);if(!t.test(r))throw new Jt(`Unsafe value for flag ${o}`);a++;}}}async function qe(e){Pp(e);let a=e.slice(zd.length).split(/\s+/).filter(Boolean);pk(a);let o=mk(a);Ht.debug(`[${o}] Executing proxy command: claude ${a.join(" ")}`);let t=Date.now();try{let r=await execa("claude",a,{reject:!1}),i=Date.now()-t;return Ht.debug(`[${o}] Proxy command finished with exit code ${r.exitCode} in ${i}ms`),{name:o,command:e,exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr,duration_ms:i}}catch(r){throw Wd(r)?new ps:r}}function mk(e){return e.length>=3?e[2]:e.join(" ")}function Wd(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function gk(e){return e.startsWith(bp)?zd+e.slice(bp.length):e}function fk(e){return dk.test(e)||ck.test(e)}function hk(e){let a=0;for(;a<e.length&&fk(e[a]);)a++;return e.slice(a)}var bk=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function vk(e,a){return !a||e.includes("--scope")||!bk.test(e)?e:`${e} --scope ${a}`}async function Nr(e,a){let o=e.split("&&").map(s=>s.trim()).filter(Boolean),r=hk(o).map(s=>gk(s)).map(s=>vk(s,a));if(r.length===0)throw new Error("Empty install command");for(let s of r)uk(s);Ht.debug(`[installCommand] Executing ${r.length} command(s)`);let i=await qe(r[0]);if(i.exitCode!==0)return i;for(let s=1;s<r.length;s++)if(i=await qe(r[s]),i.exitCode!==0)return i;return i}async function ms(e,a,o){let t=Bt(e),r=a?.trim();if(!r&&(r=(await Fo(`Plugin "${t}" could not be installed.
|
|
116
116
|
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!r))throw new Error("No marketplace source provided. Cannot retry install.");r=ss(r),o?.(),Ht.debug(`[${t}] Adding marketplace via: claude plugin marketplace add ${r}`);try{let i=await execa("claude",["plugin","marketplace","add",r],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Ht.debug(`[${t}] Marketplace added successfully`);}catch(i){throw Wd(i)?new ps:i}}To();U();Oe();I();var wk=6e4,Oo=class extends Error{url;isTimeout;isAuthError;constructor(a,o,t=false,r=false){super(a),this.name="GitCloneError",this.url=o,this.isTimeout=t,this.isAuthError=r;}};async function Ca(e,a){let o=await mkdtemp(join(tmpdir(),"flow-skills-")),t=simpleGit({timeout:{block:wk}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),r=a?["--depth","1","--branch",a]:["--depth","1"];try{return await t.clone(e,o,r),o}catch(i){await rm(o,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),n=s.includes("block timeout")||s.includes("timed out"),d=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw n?new Oo("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):d?new Oo(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Oo(`Failed to clone ${e}: ${s}`,e,false,false)}}async function Ra(e){let a=normalize(resolve(e)),o=normalize(resolve(tmpdir()));if(!a.startsWith(o+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}async function ct(e,a=["--version"]){try{return (await execa(e,a,{reject:!1})).exitCode===0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return false;throw o}}function Ck(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Rk(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Ak(e){return typeof e=="object"&&e!==null&&e.source==="github"}function lt(e,a){let o=e.source;if(Ck(o)){let t=o.path?o.path.replace(/^\.\//,""):".",r=o.ref&&!/^[0-9a-f]{40}$/i.test(o.ref)?o.ref:void 0;return {cloneUrl:o.url,subPath:t||".",ref:r}}if(Rk(o))return {cloneUrl:o.url,subPath:"."};if(Ak(o))return {cloneUrl:`https://github.com/${o.repo}`,subPath:"."};if(typeof o=="string"){if(o.startsWith("https://")||o.startsWith("git@"))return {cloneUrl:o,subPath:"."};if((o.startsWith("./")||o===".")&&a){let t=o==="."?".":o.replace(/^\.\//,"")||".";return {cloneUrl:a,subPath:t}}}return null}function da(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Aa=P("claude-code.adapter");function Ek(e,a){let o=e??"external";if(!a)return o;let t=a.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!t)return o;let r=t[1],i=Jo();if(!se__default.existsSync(i))return o;try{let s=JSON.parse(se__default.readFileSync(i,"utf-8"));for(let[n,d]of Object.entries(s))if(d.source?.repo===r)return n}catch{}return o}async function Ep(e,a){let o=e.catalogId?ge.getAdapter(e.catalogId):void 0,t=lt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=e.type==="bundle"||e.type==null,i=Ek(e.catalogId,o?.source),s=a.scope??"user",n;r?n=Sn(i,e.name,"external"):n=join(Ho(s==="user"?"global":"project"),e.name);let d=null;try{ia(e.name),d=await Ca(t.cloneUrl,t.ref);let l=t.subPath==="."?d:join(d,t.subPath);if(se__default.existsSync(n)&&se__default.rmSync(n,{recursive:!0,force:!0}),se__default.mkdirSync(dirname(n),{recursive:!0}),se__default.cpSync(l,n,{recursive:!0}),r){let c=`${e.name}@${i}`,u=await qd(),p={scope:s,installPath:n,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},m=u.plugins[c]??[];u.plugins[c]=[...m.filter(g=>g.scope!==s),p],na(u),qr(c,!0,s);}return {success:!0,message:`Installed ${e.name} from ${t.cloneUrl}`}}catch(l){return Aa.debug(`[${e.name}] External catalog install failed: ${String(l)}`),{success:false,message:l instanceof Error?l.message:String(l)}}finally{d&&await Ra(d).catch(()=>{});}}async function Jd(e,a,o,t){try{await C(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:o,source:"external",scope:ts(t),version:"unknown",duration_ms:a,interface:Z().interfaceType});}catch(r){Aa.warn(`Failed to send external install metrics: ${String(r)}`);}}async function Rp(e,a,o){try{await C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:o,source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(t){Aa.warn(`Failed to send external install-failed metrics: ${String(t)}`);}}var Ik={async install(e,a){if(e.origin===ft&&!e.installCommand&&!Gt(e.name))return Ep(e,a);if(e.origin===ft&&e.installCommand){let o=e.type??"skill",t=await Nr(e.installCommand,a.scope);return t.exitCode===0?(await Jd(e.name,t.duration_ms,o,a.scope),{success:true,message:`Installed ${e.name}`}):(await Rp(e.name,new Error(t.stderr||"Install failed"),o),{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`})}if(Gt(e.name)){let o=e.type??"skill",t=jt(e.name,a.scope);Aa.debug(`[${e.name}] Attempting install: ${t}`);let r=await qe(t);if(r.exitCode===0)return await Jd(e.name,r.duration_ms,o,a.scope),{success:true};Aa.debug(`[${e.name}] First attempt failed, adding marketplace`),await ms(e.name,a.marketplaceSource,()=>{});let i=await qe(t);return i.exitCode===0?(await Jd(e.name,i.duration_ms,o,a.scope),{success:true}):(await Rp(e.name,new Error(i.stderr||"Install failed"),o),{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`})}try{let o=await je(e.name,{...a,type:e.type});return {success:!0,message:`Installed ${e.name}@${o.version}`}}catch(o){return Aa.debug(`[${e.name}] Plugin install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}},async uninstall(e,a){await Lr(e,a);},getInstallPath(e,a){return ""}};function Ap(e){return {async install(a,o){if(a.origin===ft&&!a.installCommand&&!Gt(a.name))return Ep(a,o);if(!a.installCommand)try{let r=await je(a.name,{...o,type:e});return {success:!0,message:`Installed ${a.name}@${r.version}`}}catch(r){return Aa.debug(`[${a.name}] ${e} install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}Aa.debug(`[${a.name}] Executing install command: ${a.installCommand}`);let t=await Nr(a.installCommand,o.scope);return t.exitCode===0?{success:true}:{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`}},async uninstall(a,o){let t=Ae(),r=`${a}@${pe}`;if(t.plugins[r]){await Lr(a,o);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${a}`)},getInstallPath(a,o){return ""}}}function Tk(e){for(let a of [join(e,".claude","agents"),join(e,"agents")]){if(!se__default.existsSync(a))continue;let o=se__default.readdirSync(a).filter(t=>t.endsWith(".md")&&se__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}function Mk(e){for(let a of [join(e,".claude","rules"),join(e,"rules")]){if(!se__default.existsSync(a))continue;let o=se__default.readdirSync(a).filter(t=>t.endsWith(".md")&&se__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}async function Hd(e,a,o,t){let r=await qd(),i=`${e}@claude-code`,s={scope:a,installPath:o,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:t},n=r.plugins[i]??[];r.plugins[i]=[...n.filter(d=>d.scope!==a),s],na(r);}var qk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Ca(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=Tk(s);if(n.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let d=mi(o);se__default.mkdirSync(d,{recursive:!0});let l=da(e.name);if(n.length===1)se__default.copyFileSync(n[0],join(d,`${l}.md`));else for(let u of n){let p=da(basename(u,".md"));se__default.copyFileSync(u,join(d,`${l}--${p}.md`));}let c=n.length===1?join(d,`${l}.md`):d;return await Hd(e.name,o,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(s){return Aa.debug(`[${e.name}] Agent install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ra(i).catch(()=>{});}},async uninstall(e,a){let o=mi(a),t=da(e);if(se__default.existsSync(o))for(let n of se__default.readdirSync(o).filter(d=>d===`${t}.md`||d.startsWith(`${t}--`)&&d.endsWith(".md")))se__default.rmSync(join(o,n),{force:true});let r=`${e}@claude-code`,i=Ae(),s=(i.plugins[r]??[]).filter(n=>n.scope!==a);if(s.length===0){let{[r]:n,...d}=i.plugins;na({...i,plugins:d});}else na({...i,plugins:{...i.plugins,[r]:s}});},getInstallPath(e,a){return join(mi(a),`${da(e)}.md`)}},Lk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Ca(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=Mk(s);if(n.length===0)return {success:!1,message:`No rule files found in "${e.name}"`};let d=Pt(o);se__default.mkdirSync(d,{recursive:!0});for(let l of n)se__default.copyFileSync(l,join(d,basename(l)));return await Hd(e.name,o,d,"rule"),{success:!0,message:`Installed rule(s) from ${e.name}`}}catch(s){return Aa.debug(`[${e.name}] Rule install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ra(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Rule uninstall not supported \u2014 remove files manually from .claude/rules/")},getInstallPath(e,a){return Pt(a)}},Fk={async install(e,a){let o=a.scope??"user",t=e.catalogId?ge.getAdapter(e.catalogId):void 0,r=lt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{ia(e.name),i=await Ca(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=join(s,"settings.json");if(!se__default.existsSync(n))return {success:!1,message:`No settings.json found in "${e.name}"`};let d;try{d=JSON.parse(se__default.readFileSync(n,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let l=d.hooks;if(!l||typeof l!="object"||Array.isArray(l))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=Dr();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let u=c.status==="ok"?c.settings:{},p=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},m=Or(p,l);return Fi({...u,hooks:m}),await Hd(e.name,o,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(s){return Aa.debug(`[${e.name}] Hook install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ra(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,a){return ""}},gs=class{id="claude-code";name="Claude Code";async isAvailable(){return ct("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Ik,skill:Ap("skill"),mcp:Ap("mcp"),agent:qk,hook:Fk,rule:Lk}};function fs(e,a){return {async install(o,t){if(!o.installCommand)return {success:false,message:"No install command provided"};let[r,...i]=o.installCommand.split(/\s+/).filter(Boolean);if(!r||!e.has(r))return {success:false,message:`Disallowed command: "${r??""}"`};let s=await execa(r,i,{reject:false});return s.exitCode===0?{success:true}:{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`}},async uninstall(o,t){throw new Error(`MCP uninstall not supported \u2014 ${a.replace("<name>",o)}`)},getInstallPath(o,t){return ""}}}var Nk=new Set(["gh"]),Gk=fs(Nk,"use: gh copilot mcp remove <name>"),hs=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await ct("gh",["--version"])?ct("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Gk}};Oe();var Bk=new Set(["opencode"]),jk=fs(Bk,"use: opencode config remove mcp <name>");function Uk(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
117
|
-
`)}function Ip(){return {async install(e,a){try{ia(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?ge.getAdapter(e.catalogId):void 0,t=lt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Ca(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=pi(a.scope??"user"),n=join(i,".opencode","plugins");if(se__default.existsSync(n)){let d=se__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};se__default.mkdirSync(s,{recursive:!0}),se__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);se__default.existsSync(d)&&se__default.rmSync(d,{recursive:!0,force:!0}),se__default.mkdirSync(d,{recursive:!0}),se__default.cpSync(i,d,{recursive:!0}),se__default.mkdirSync(s,{recursive:!0}),se__default.writeFileSync(join(s,`${e.name}.js`),Uk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ra(r).catch(()=>{});}},async uninstall(e,a){ia(e);let o=pi(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);se__default.existsSync(t)&&se__default.rmSync(t,{force:true}),se__default.existsSync(r)&&se__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(pi(a),`${e}.js`)}}}var bs=class{id="opencode";name="OpenCode";async isAvailable(){return ct("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:jk,skill:Ip(),bundle:Ip()}};var Wa=new os;Wa.register(new gs);Co()&&(Wa.register(new hs),Wa.register(new bs));function Tp({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Wa.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let p=useCallback(h=>{h==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),m=useCallback(h=>{if(h==="Cancel"){n(false);return}let v=d.find(k=>k.name===h);v?(u(v.id),n(false),i(true)):n(false);},[d]),g=useCallback(h=>{let v=zu(h);v?o(v,c):i(false);},[o,c]),f=useCallback(()=>{i(false);},[]);if(s){let h=[...d.map(v=>v.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:m,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:ju,descriptions:Uu,onAction:g,onClose:f},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:p,onClose:t},"main")}j();function qp({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(g=>g.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(g=>g.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let p=useCallback((g,f)=>{f.upArrow?n(h=>Math.max(0,h-1)):f.downArrow?n(h=>Math.min(u.length-1,h+1)):f.return?u[s]==="Confirm Install"?t():r():f.escape&&r();},[u,s,t,r]);useInput(p,{isActive:i==="actionMenu"&&a!==void 0});let m=useCallback(g=>{g==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(g=>{let f=b(g.name??g.flowId),h=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:u.map((g,f)=>jsx(Box,{children:jsxs(Text,{bold:f===s,color:f===s?"cyan":void 0,children:[f===s?"\u203A ":" ",g]})},g))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:m,onClose:r})}function ks({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}j();function Op({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=ks({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)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 u=o==="enabled"?"Disable":"Enable",p=r&&b(r),m=p?`Update to v${p}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,m,"Cancel"]:["Uninstall",u,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===u?s(a):h.startsWith("Update")?n?.():d();},onClose:d})}function Bp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=ks({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?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(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var _t=P("bundle:installer"),jp=/already exists/i;async function Xk(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if(yp(a)){let o=await kp(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(jp.test(t))return;throw new Error(t)}}else {let o=await Nr(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(jp.test(t))return;throw new Error(t)}}}async function Kk(e,a){try{await C(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){_t.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function $k(e,a,o){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){_t.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function Up(e,a,o,t){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){_t.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function Yk(e,a,o,t,r){try{await C(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){_t.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function ws(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(m=>m.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await Kk(s,r.length);let d=[],l=0,c=r.length;for(let[m,g]of r.entries()){let f=g.name??g.flowId,h=g.type??"unknown";if(!g.type){_t.warn(`Artifact "${f}" has no type \u2014 treated as failed`),d.push({name:f,type:h,reason:"unknown artifact type"}),await Up(s,f,h,"unknown artifact type"),o?.({index:m+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await Xk(g),l++,await $k(s,f,h),o?.({index:m+1,total:c,artifact:g,success:!0});}catch(v){let k=v instanceof Error?v.message:String(v);_t.error(`Failed to install artifact "${f}": ${k}`),d.push({name:f,type:h,reason:k}),await Up(s,f,h,k),o?.({index:m+1,total:c,artifact:g,success:false,error:k});}}let u=Date.now()-n,p=d.length;return await Yk(s,l,p,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:p,failures:d}}j();function Hp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,ws(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",b(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ye=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:le()})}));j();function Qp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",qa(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}j();function Vp({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,p=c?.autoUpdate!==false,m=t==="detail",g=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return m?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${qa(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),p?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:g.map((f,h)=>{let v=h===r;return jsxs(Box,{children:[jsx(Text,{color:v?"cyan":void 0,children:v?"\u203A ":" "}),jsx(Text,{bold:v,color:f.danger?"yellow":void 0,dimColor:!v,children:f.label})]},f.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function _p(e){return e.adapter.removable!==false?4:2}U();j();function Xp({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",b(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:b(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",b(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",b(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:b(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 ",b(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",b(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",b(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function $p({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Yp({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,M)=>{if(M.escape){t();return}if(M.return){u(n[d]??null);return}if(M.upArrow){l(F=>Math.max(0,F-1));return}M.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(Xp,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.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 p=Math.max(0,d-Math.floor(ea/2)),m=Math.min(n.length,p+ea);m===n.length&&(p=Math.max(0,m-ea));let g=n.slice(p,m),f=p,h=n.length-m,v=i.length>0&&p<i.length,k=m>i.length,T=g.filter(A=>o.has(`${A.name}@${r}`)),L=g.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2191 ${f} more above`:" "})}),v&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),T.map(A=>jsx($p,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),k&&jsxs(Box,{flexDirection:"column",marginTop:v?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx($p,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}wd();var iP=/^https?:\/\/.+/;function sP(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function nP(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function om(e){let a=y(h=>h.showNotification),o=y(h=>h.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),p=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{p.current=n;},[n]);let m=useCallback(()=>{u.current="",p.current="",s(""),d(""),c(null),r("add-name");},[]),g=useCallback(()=>{r("idle");},[]),f=useCallback(async()=>{let h=p.current,v=u.current;if(!iP.test(h)){c("URL must start with http:// or https://");return}c(null),r("adding");let k=randomUUID(),T=new zt(k,v,h);try{await T.fetchItems(),await ao.add({id:k,name:v,source:h}),ge.register(new zt(k,v,h)),o(),e(),a(`Catalog "${v}" added`,"success"),s(""),d(""),u.current="",p.current="",r("idle");}catch(L){let A=sP(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":nP(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((h,v)=>{if(v.escape){r("idle");return}if(v.return){u.current.trim().length>0&&r("add-url");return}if(v.backspace||v.delete){u.current=u.current.slice(0,-1),s(u.current);return}h&&!v.ctrl&&!v.meta&&(u.current=u.current+h,s(u.current));},{isActive:t==="add-name"}),useInput((h,v)=>{if(v.escape){r("add-name");return}if(v.return){f();return}if(v.backspace||v.delete){p.current=p.current.slice(0,-1),d(p.current),c(null);return}h&&!v.ctrl&&!v.meta&&(p.current=p.current+h,d(p.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:m,cancelAdd:g}}function tm(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await ao.remove(r),ge.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function im(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=ye(E=>E.installedItems),[r,i]=useState(()=>ge.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[p,m]=useState(null),[g,f]=useState("main"),h=useRef(r);useEffect(()=>{h.current=r;},[r]),useEffect(()=>{g==="browse"&&!r[s-1]&&f("main");},[g,r,s]);let v=useCallback(()=>{(async()=>{let E=ge.listAdapters(),B=await ao.read(),Q=new Map(B.map(Fe=>[Fe.id,Fe]));i(E.map(Fe=>({adapter:Fe,stored:Q.get(Fe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),v();},[a,v]),useEffect(()=>{if(s===0){m(null);return}let E=h.current[s-1];if(!E)return;let B=false;return m({items:[],loading:true,error:null}),E.adapter.fetchItems().then(Q=>{B||m({items:Q,loading:false,error:null});}).catch(Q=>{B||m({items:[],loading:false,error:Q instanceof Error?Q.message:"Failed to load catalog"});}),()=>{B=true;}},[s]);let k=om(v),T=useCallback(()=>{v(),n(0),l("list"),m(null),f("main");},[v]),{handleRemove:L}=tm(T),A=useCallback(async E=>{f("removing"),await L(E);},[L]),M=useCallback(async E=>{try{let B=await E.adapter.fetchItems();if(m({items:B,loading:!1,error:null}),E.stored){let Q=new Date().toISOString();await ao.updateField(E.stored.id,{lastUpdated:Q}),v();}o("Marketplace updated","success");}catch(B){o(B instanceof Error?B.message:"Update failed","error");}},[v,o]),F=useCallback(async E=>{if(!E.stored)return;let B=E.stored.autoUpdate!==false;await ao.updateField(E.stored.id,{autoUpdate:!B}),v();},[v]),N=useCallback(()=>f("browse"),[]),oe=useCallback(E=>{let B=r[s-1];if(!B)return;let Q=B.adapter.removable!==false;[N,()=>{M(B);},...Q?[()=>{F(B);},()=>{A(B.adapter.id);}]:[]][E]?.();},[r,s,N,M,F,A]),x=useCallback(()=>f("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&M(E);},[r,s,M]),ae=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,B)=>{if(B.upArrow){n(Q=>Math.max(0,Q-1));return}if(B.downArrow){n(Q=>Math.min(r.length,Q+1));return}(B.return||B.tab)&&(s===0?k.startAdd():(l("detail"),u(0)));},{isActive:g==="main"&&k.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,B)=>{if(B.escape||B.tab){l("list");return}if(B.upArrow){u(Q=>Math.max(0,Q-1));return}if(B.downArrow){let Q=r[s-1],Fe=Q?_p(Q)-1:0;u(si=>Math.min(si+1,Fe));return}B.return&&oe(c);},{isActive:g==="main"&&k.phase==="idle"&&d==="detail"&&e==="marketplaces"}),k.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:k.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.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(k.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:k.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:k.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:k.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(k.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let E=r[s-1];if(!E)return jsx(Box,{});let B=E.adapter.id??"default",Q=new Set(t.filter(Fe=>Fe.marketplace===E.adapter.name).map(Fe=>`${Fe.name}@${B}`));return jsx(Yp,{entry:E,items:p?.items??[],installedKeys:Q,onBack:x})}if(r.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 W=r[s-1]??null,_=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Qp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx(Vp,{entry:W,detailData:p,installedCount:_,focusPanel:d,actionIndex:c,onBrowse:N,onUpdate:J,onToggleAutoUpdate:ae,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="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 sm(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r-1+ie.length)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r+1)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r+1)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function nm(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function dm(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var pP=new Set(ie.filter(e=>e.focus!=="list").map(e=>e.focus));function Vr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function cm({listLength:e}){let a=y(f=>f.focus),o=y(f=>f.selectedIndex),t=y(f=>f.actionMenuOpen),r=y(f=>f.setFocus),i=y(f=>f.setActionMenuOpen),s=_e(f=>f.query),n=_e(f=>f.setQuery),d=_e(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:f,setCursorPosition:h}=_e.getState();h(f.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let f=setTimeout(()=>u(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,h)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(nd(f,h,{activeTab:v}));},{isActive:a==="tabs"}),useInput((f,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(nd("",h,{activeTab:v}));},{isActive:pP.has(a)}),useInput((f,h)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(sm(f,h,{activeTab:v,selectedIndex:k},l.current));},{isActive:a==="list"}),useInput((f,h)=>{Vr(nm(f,h));},{isActive:a==="actionMenu"}),useInput((f,h)=>{let v=dm(f,h,_e.getState().query),k=v.queryUpdate;if(Vr(v.actions),k==="reset")d(),u("");else if(k!==null){let{query:T,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in k)L>0&&(n(T.slice(0,L-1)+T.slice(L)),A(L-1));else if("append"in k)n(T.slice(0,L)+k.append+T.slice(L)),A(L+k.append.length);else if("cursorMove"in k){let M=L+k.cursorMove;M>=0&&M<=T.length&&A(M);}}},{isActive:a==="search"});let p=useCallback(()=>{i(false),r("list");},[i,r]),m=useCallback(f=>{let{setSelectedIndex:h,selectedIndex:v}=y.getState();f===0?h(0):v>=f&&h(f-1);},[]),g=useCallback(f=>{if(!c)return l.current=f.length,f;let h=c.toLowerCase(),v=f.filter(k=>k.name.toLowerCase().includes(h)||k.description?.toLowerCase().includes(h));return l.current=v.length,v},[c]);return {actionMenuOpen:t,closeMenu:p,selectedIndex:o,clampIndex:m,filteredItems:g}}function um(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function ze(e,a,o=false){return o?true:!Kd.valid(e)||!Kd.valid(a)?false:Kd.gt(a,e)}U();I();var io=P("updater");async function mP(e,a,o,t,r,i){try{await C(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:Z().interfaceType});}catch(s){io.warn(`Failed to send update metrics: ${String(s)}`);}}function gP(e){let a=Ae(),o=`${e}@${pe}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function As(e,a={}){let o=Date.now(),t=null;try{io.debug(`[${e}] Acquiring lock...`),t=await Mo();let r=gP(e);if(!r)throw io.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;io.debug(`[${e}] Fetching manifest...`);let l=(await Wt(e,a.source)).version;if(!s||!ze(s,l,a.force))throw io.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Io(e,s??"unknown");io.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await je(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await mP(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),io.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){io.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Mo();let u=Ae(),p=`${e}@${pe}`;throw u.plugins[p]&&(u.plugins[p][0].version=s,u.plugins[p][0].installPath=n,na(u),io.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}To();I();var xs=P("dispatcher");async function fP(e,a,o,t,r){let i=Bt(e);return xs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await ms(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),xs.debug(`[${e}] Retrying install after marketplace add`),qe(a)}async function pm(e,a,o,t){let r=jt(e,t),i=Bt(e);o?.onStatus?.(`Installing ${i}...`),xs.debug(`[${e}] Attempting install: ${r}`);let s=await qe(r);if(s.exitCode===0)return s;xs.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return fP(e,r,n,a,o)}async function mm(e,a,o){let t=e.type??"bundle",r=await Wa.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function gm(){let e=ye(s=>s.installedItems),a=ye(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await mm(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=le().find(m=>m.name===s),l=d?.providerId??"claude-code",c=Wa.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",p=c.installers[u];if(!p)throw new Error(`Provider "${l}" does not support type "${u}"`);await p.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Fr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await As(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}j();I();var Is=P("mcp");function _r(e,a){e.silent?Ne({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):S(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function hm(e,a){e.silent?ve({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):(K(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&D(a.stdout));}function hP(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function $d(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function bm(e,a,o){if(!await he())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return _r(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Is.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=hP(e,a,o.transport,o.scope);if(!o.force){let i=b(e),s=b(t);if(!await ee(`Install external MCP "${i}"?
|
|
117
|
+
`)}function Ip(){return {async install(e,a){try{ia(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?ge.getAdapter(e.catalogId):void 0,t=lt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Ca(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=pi(a.scope??"user"),n=join(i,".opencode","plugins");if(se__default.existsSync(n)){let d=se__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};se__default.mkdirSync(s,{recursive:!0}),se__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);se__default.existsSync(d)&&se__default.rmSync(d,{recursive:!0,force:!0}),se__default.mkdirSync(d,{recursive:!0}),se__default.cpSync(i,d,{recursive:!0}),se__default.mkdirSync(s,{recursive:!0}),se__default.writeFileSync(join(s,`${e.name}.js`),Uk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ra(r).catch(()=>{});}},async uninstall(e,a){ia(e);let o=pi(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);se__default.existsSync(t)&&se__default.rmSync(t,{force:true}),se__default.existsSync(r)&&se__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(pi(a),`${e}.js`)}}}var bs=class{id="opencode";name="OpenCode";async isAvailable(){return ct("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:jk,skill:Ip(),bundle:Ip()}};var Wa=new os;Wa.register(new gs);Co()&&(Wa.register(new hs),Wa.register(new bs));function Tp({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Wa.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let p=useCallback(h=>{h==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),m=useCallback(h=>{if(h==="Cancel"){n(false);return}let v=d.find(k=>k.name===h);v?(u(v.id),n(false),i(true)):n(false);},[d]),g=useCallback(h=>{let v=zu(h);v?o(v,c):i(false);},[o,c]),f=useCallback(()=>{i(false);},[]);if(s){let h=[...d.map(v=>v.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:m,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:ju,descriptions:Uu,onAction:g,onClose:f},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:p,onClose:t},"main")}j();function qp({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(g=>g.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(g=>g.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let p=useCallback((g,f)=>{f.upArrow?n(h=>Math.max(0,h-1)):f.downArrow?n(h=>Math.min(u.length-1,h+1)):f.return?u[s]==="Confirm Install"?t():r():f.escape&&r();},[u,s,t,r]);useInput(p,{isActive:i==="actionMenu"&&a!==void 0});let m=useCallback(g=>{g==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(g=>{let f=b(g.name??g.flowId),h=g.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},g.flowId)})}),jsx(Box,{flexDirection:"column",children:u.map((g,f)=>jsx(Box,{children:jsxs(Text,{bold:f===s,color:f===s?"cyan":void 0,children:[f===s?"\u203A ":" ",g]})},g))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:m,onClose:r})}function ks({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}j();function Op({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=ks({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)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 u=o==="enabled"?"Disable":"Enable",p=r&&b(r),m=p?`Update to v${p}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,m,"Cancel"]:["Uninstall",u,"Cancel"],onAction:h=>{h==="Uninstall"?c():h===u?s(a):h.startsWith("Update")?n?.():d();},onClose:d})}function Bp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=ks({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?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(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var _t=P("bundle:installer"),jp=/already exists/i;async function Xk(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if(yp(a)){let o=await kp(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(jp.test(t))return;throw new Error(t)}}else {let o=await Nr(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(jp.test(t))return;throw new Error(t)}}}async function Kk(e,a){try{await C(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){_t.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function $k(e,a,o){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){_t.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function Up(e,a,o,t){try{await C(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){_t.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function Yk(e,a,o,t,r){try{await C(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){_t.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function ws(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(m=>m.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await Kk(s,r.length);let d=[],l=0,c=r.length;for(let[m,g]of r.entries()){let f=g.name??g.flowId,h=g.type??"unknown";if(!g.type){_t.warn(`Artifact "${f}" has no type \u2014 treated as failed`),d.push({name:f,type:h,reason:"unknown artifact type"}),await Up(s,f,h,"unknown artifact type"),o?.({index:m+1,total:c,artifact:g,success:false,error:"unknown artifact type"});continue}try{await Xk(g),l++,await $k(s,f,h),o?.({index:m+1,total:c,artifact:g,success:!0});}catch(v){let k=v instanceof Error?v.message:String(v);_t.error(`Failed to install artifact "${f}": ${k}`),d.push({name:f,type:h,reason:k}),await Up(s,f,h,k),o?.({index:m+1,total:c,artifact:g,success:false,error:k});}}let u=Date.now()-n,p=d.length;return await Yk(s,l,p,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:p,failures:d}}j();function Hp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,ws(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",b(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ye=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:le()})}));j();function Qp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",qa(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}j();function Vp({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,p=c?.autoUpdate!==false,m=t==="detail",g=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return m?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${qa(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),p?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:g.map((f,h)=>{let v=h===r;return jsxs(Box,{children:[jsx(Text,{color:v?"cyan":void 0,children:v?"\u203A ":" "}),jsx(Text,{bold:v,color:f.danger?"yellow":void 0,dimColor:!v,children:f.label})]},f.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function _p(e){return e.adapter.removable!==false?4:2}U();j();function Xp({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",b(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:b(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",b(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",b(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:b(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 ",b(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",b(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",b(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function $p({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Yp({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,M)=>{if(M.escape){t();return}if(M.return){u(n[d]??null);return}if(M.upArrow){l(F=>Math.max(0,F-1));return}M.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(Xp,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.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 p=Math.max(0,d-Math.floor(ea/2)),m=Math.min(n.length,p+ea);m===n.length&&(p=Math.max(0,m-ea));let g=n.slice(p,m),f=p,h=n.length-m,v=i.length>0&&p<i.length,k=m>i.length,T=g.filter(A=>o.has(`${A.name}@${r}`)),L=g.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2191 ${f} more above`:" "})}),v&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),T.map(A=>jsx($p,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),k&&jsxs(Box,{flexDirection:"column",marginTop:v?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx($p,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}wd();var iP=/^https?:\/\/.+/;function sP(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function nP(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function om(e){let a=y(h=>h.showNotification),o=y(h=>h.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),p=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{p.current=n;},[n]);let m=useCallback(()=>{u.current="",p.current="",s(""),d(""),c(null),r("add-name");},[]),g=useCallback(()=>{r("idle");},[]),f=useCallback(async()=>{let h=p.current,v=u.current;if(!iP.test(h)){c("URL must start with http:// or https://");return}c(null),r("adding");let k=randomUUID(),T=new zt(k,v,h);try{await T.fetchItems(),await ao.add({id:k,name:v,source:h}),ge.register(new zt(k,v,h)),o(),e(),a(`Catalog "${v}" added`,"success"),s(""),d(""),u.current="",p.current="",r("idle");}catch(L){let A=sP(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":nP(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((h,v)=>{if(v.escape){r("idle");return}if(v.return){u.current.trim().length>0&&r("add-url");return}if(v.backspace||v.delete){u.current=u.current.slice(0,-1),s(u.current);return}h&&!v.ctrl&&!v.meta&&(u.current=u.current+h,s(u.current));},{isActive:t==="add-name"}),useInput((h,v)=>{if(v.escape){r("add-name");return}if(v.return){f();return}if(v.backspace||v.delete){p.current=p.current.slice(0,-1),d(p.current),c(null);return}h&&!v.ctrl&&!v.meta&&(p.current=p.current+h,d(p.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:m,cancelAdd:g}}function tm(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await ao.remove(r),ge.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function im(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=ye(E=>E.installedItems),[r,i]=useState(()=>ge.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[p,m]=useState(null),[g,f]=useState("main"),h=useRef(r);useEffect(()=>{h.current=r;},[r]),useEffect(()=>{g==="browse"&&!r[s-1]&&f("main");},[g,r,s]);let v=useCallback(()=>{(async()=>{let E=ge.listAdapters(),B=await ao.read(),Q=new Map(B.map(Fe=>[Fe.id,Fe]));i(E.map(Fe=>({adapter:Fe,stored:Q.get(Fe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),v();},[a,v]),useEffect(()=>{if(s===0){m(null);return}let E=h.current[s-1];if(!E)return;let B=false;return m({items:[],loading:true,error:null}),E.adapter.fetchItems().then(Q=>{B||m({items:Q,loading:false,error:null});}).catch(Q=>{B||m({items:[],loading:false,error:Q instanceof Error?Q.message:"Failed to load catalog"});}),()=>{B=true;}},[s]);let k=om(v),T=useCallback(()=>{v(),n(0),l("list"),m(null),f("main");},[v]),{handleRemove:L}=tm(T),A=useCallback(async E=>{f("removing"),await L(E);},[L]),M=useCallback(async E=>{try{let B=await E.adapter.fetchItems();if(m({items:B,loading:!1,error:null}),E.stored){let Q=new Date().toISOString();await ao.updateField(E.stored.id,{lastUpdated:Q}),v();}o("Marketplace updated","success");}catch(B){o(B instanceof Error?B.message:"Update failed","error");}},[v,o]),F=useCallback(async E=>{if(!E.stored)return;let B=E.stored.autoUpdate!==false;await ao.updateField(E.stored.id,{autoUpdate:!B}),v();},[v]),N=useCallback(()=>f("browse"),[]),te=useCallback(E=>{let B=r[s-1];if(!B)return;let Q=B.adapter.removable!==false;[N,()=>{M(B);},...Q?[()=>{F(B);},()=>{A(B.adapter.id);}]:[]][E]?.();},[r,s,N,M,F,A]),x=useCallback(()=>f("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&M(E);},[r,s,M]),ae=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,B)=>{if(B.upArrow){n(Q=>Math.max(0,Q-1));return}if(B.downArrow){n(Q=>Math.min(r.length,Q+1));return}(B.return||B.tab)&&(s===0?k.startAdd():(l("detail"),u(0)));},{isActive:g==="main"&&k.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,B)=>{if(B.escape||B.tab){l("list");return}if(B.upArrow){u(Q=>Math.max(0,Q-1));return}if(B.downArrow){let Q=r[s-1],Fe=Q?_p(Q)-1:0;u(si=>Math.min(si+1,Fe));return}B.return&&te(c);},{isActive:g==="main"&&k.phase==="idle"&&d==="detail"&&e==="marketplaces"}),k.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:k.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.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(k.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:k.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:k.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:k.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(k.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(g==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(g==="browse"){let E=r[s-1];if(!E)return jsx(Box,{});let B=E.adapter.id??"default",Q=new Set(t.filter(Fe=>Fe.marketplace===E.adapter.name).map(Fe=>`${Fe.name}@${B}`));return jsx(Yp,{entry:E,items:p?.items??[],installedKeys:Q,onBack:x})}if(r.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 W=r[s-1]??null,_=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Qp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx(Vp,{entry:W,detailData:p,installedCount:_,focusPanel:d,actionIndex:c,onBrowse:N,onUpdate:J,onToggleAutoUpdate:ae,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="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 sm(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r-1+ie.length)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r+1)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=ie.findIndex(s=>s.id===o.activeTab),i=ie[(r+1)%ie.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="8"?[{type:"toggleTypeFilter",catalogType:"agent"}]:e==="9"?[{type:"toggleTypeFilter",catalogType:"hook"}]:e==="0"?[{type:"toggleTypeFilter",catalogType:"plugin"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function nm(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function dm(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var pP=new Set(ie.filter(e=>e.focus!=="list").map(e=>e.focus));function Vr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function cm({listLength:e}){let a=y(f=>f.focus),o=y(f=>f.selectedIndex),t=y(f=>f.actionMenuOpen),r=y(f=>f.setFocus),i=y(f=>f.setActionMenuOpen),s=_e(f=>f.query),n=_e(f=>f.setQuery),d=_e(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:f,setCursorPosition:h}=_e.getState();h(f.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let f=setTimeout(()=>u(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,h)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(nd(f,h,{activeTab:v}));},{isActive:a==="tabs"}),useInput((f,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(nd("",h,{activeTab:v}));},{isActive:pP.has(a)}),useInput((f,h)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();Vr(sm(f,h,{activeTab:v,selectedIndex:k},l.current));},{isActive:a==="list"}),useInput((f,h)=>{Vr(nm(f,h));},{isActive:a==="actionMenu"}),useInput((f,h)=>{let v=dm(f,h,_e.getState().query),k=v.queryUpdate;if(Vr(v.actions),k==="reset")d(),u("");else if(k!==null){let{query:T,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in k)L>0&&(n(T.slice(0,L-1)+T.slice(L)),A(L-1));else if("append"in k)n(T.slice(0,L)+k.append+T.slice(L)),A(L+k.append.length);else if("cursorMove"in k){let M=L+k.cursorMove;M>=0&&M<=T.length&&A(M);}}},{isActive:a==="search"});let p=useCallback(()=>{i(false),r("list");},[i,r]),m=useCallback(f=>{let{setSelectedIndex:h,selectedIndex:v}=y.getState();f===0?h(0):v>=f&&h(f-1);},[]),g=useCallback(f=>{if(!c)return l.current=f.length,f;let h=c.toLowerCase(),v=f.filter(k=>k.name.toLowerCase().includes(h)||k.description?.toLowerCase().includes(h));return l.current=v.length,v},[c]);return {actionMenuOpen:t,closeMenu:p,selectedIndex:o,clampIndex:m,filteredItems:g}}function um(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function ze(e,a,o=false){return o?true:!Kd.valid(e)||!Kd.valid(a)?false:Kd.gt(a,e)}U();I();var io=P("updater");async function mP(e,a,o,t,r,i){try{await C(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:Z().interfaceType});}catch(s){io.warn(`Failed to send update metrics: ${String(s)}`);}}function gP(e){let a=Ae(),o=`${e}@${pe}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function As(e,a={}){let o=Date.now(),t=null;try{io.debug(`[${e}] Acquiring lock...`),t=await Mo();let r=gP(e);if(!r)throw io.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;io.debug(`[${e}] Fetching manifest...`);let l=(await Wt(e,a.source)).version;if(!s||!ze(s,l,a.force))throw io.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Io(e,s??"unknown");io.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await je(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await mP(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),io.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){io.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Mo();let u=Ae(),p=`${e}@${pe}`;throw u.plugins[p]&&(u.plugins[p][0].version=s,u.plugins[p][0].installPath=n,na(u),io.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}To();I();var xs=P("dispatcher");async function fP(e,a,o,t,r){let i=Bt(e);return xs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await ms(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),xs.debug(`[${e}] Retrying install after marketplace add`),qe(a)}async function pm(e,a,o,t){let r=jt(e,t),i=Bt(e);o?.onStatus?.(`Installing ${i}...`),xs.debug(`[${e}] Attempting install: ${r}`);let s=await qe(r);if(s.exitCode===0)return s;xs.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return fP(e,r,n,a,o)}async function mm(e,a,o){let t=e.type??"bundle",r=await Wa.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function gm(){let e=ye(s=>s.installedItems),a=ye(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await mm(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=le().find(m=>m.name===s),l=d?.providerId??"claude-code",c=Wa.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",p=c.installers[u];if(!p)throw new Error(`Provider "${l}" does not support type "${u}"`);await p.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Fr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await As(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}j();I();var Is=P("mcp");function _r(e,a){e.silent?Ne({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):S(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function hm(e,a){e.silent?ve({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):(K(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&D(a.stdout));}function hP(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function $d(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function bm(e,a,o){if(!await he())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return _r(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Is.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=hP(e,a,o.transport,o.scope);if(!o.force){let i=b(e),s=b(t);if(!await ee(`Install external MCP "${i}"?
|
|
118
118
|
This will run: ${s}
|
|
119
119
|
[y/N] `))return Is.debug(`[${e}] Installation cancelled by user`),D("Operation cancelled."),0}let r=o.silent?void 0:Sc({text:`Adding MCP "${b(e)}"...`}).start();try{let i=await qe(t);return r?.stop(),i.exitCode!==0?(_r(o,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!o.silent&&o.verbose&&i.stdout&&D(`stdout: ${i.stdout}`),1):(hm(o,{name:e,actionPastTense:"added",command:t,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return r?.stop(),_r(o,{name:e,action:"add",message:$(i)}),1}}async function vm(e,a){if(!await he())return 1;Is.debug(`[${e}] Starting MCP remove`);let o=$d(e,a.scope);if(!a.force){let r=b(e),i=b(o);if(!await ee(`Remove MCP "${r}"?
|
|
120
120
|
This will run: ${i}
|
|
121
|
-
[y/N] `))return Is.debug(`[${e}] Removal cancelled by user`),D("Operation cancelled."),0}let t=a.silent?void 0:Sc({text:`Removing MCP "${b(e)}"...`}).start();try{let r=await qe(o);return t?.stop(),r.exitCode!==0?(_r(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&D(`stdout: ${r.stdout}`),1):(hm(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),_r(a,{name:e,action:"remove",message:$(r)}),1}}I();function ym({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=P("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:p,update:m}=gm(),g=async(A,M,F)=>{d(true,A),t();try{await M(),r(o.length),i(F,"success");}catch(N){let oe=N instanceof Error?N.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${oe}`),i(oe,"error");}finally{d(false);}};return {handleInstall:(A,M)=>{e&&a&&(n.current=0,g(`Installing ${e.name}...`,()=>c(a,{scope:A,...M!==void 0?{providerId:M}:{},onDownloadProgress:(F,N)=>{let oe=Date.now();(oe-n.current>100||F>=N)&&(n.current=oe,l(F,N));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&g(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let M=e.status==="enabled";g(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>p(e.name,A),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await m(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Io)i(F.message,"info");else {let N=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${N}`),i(N,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let M=A.length;(async()=>{d(true,`Updating ${M} plugin${M>1?"s":""}...`),t();try{let N=[];for(let J of A)N.push(await m(J.name).then(()=>({status:"fulfilled",value:void 0}),ae=>({status:"rejected",reason:ae})));let oe=N.filter(J=>J.status==="fulfilled").length,x=N.map((J,ae)=>J.status==="rejected"?A[ae].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${oe}/${M} plugin${M>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${oe}/${M}; failed: ${x.join(", ")}`,oe>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let M=$d(e.name,A),F=await qe(M);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");ye.getState().loadFromDisk();},"\u2713 MCP removed");}}}xr();I();var Xr=P("api:bundle"),Zt=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Kr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},yP=/^[a-zA-Z0-9_-]{1,128}$/;async function Pm(e,a){if(e instanceof HTTPError){let o=e.response.status;throw Xr.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new Zt(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Kr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw Xr.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function Dm(e){if(!yP.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by flowId "${e}"`);try{return await eo().get(`v1/use-cases/${a}`).json()}catch(o){return Pm(o,e)}}async function Ts(e){let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by name "${e}"`);let o;try{o=await eo().get(`v1/use-cases/by-name/${a}`).json(),Xr.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return Pm(t,e)}if(o.length===0)throw new Zt(e);return o[0]}I();var kP=P("tui:bundle-flow");function wm({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();kP.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?Dm(u):Ts(n)).then(m=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:m});}).catch(m=>{l(false),a(m instanceof Error?m.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),ye.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}j();U();var $r=["local","project","user"],PP=new Set(["--transport","--scope","-s"]);function Sm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(PP.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function pt(e,a){return a?`${e}::${a}`:e}function Yd(e){return e===pe?dr:ft}function Cm(e){return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??dr,flowId:e.flowId}}function Zd(e,a){let o=Yd(e.marketplace);return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function Rm(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return $r.filter(o=>a.has(o)).map(o=>({scope:o,label:Xa[o].label,pathHint:Xa[o].pathHint,items:a.get(o)??[]}))}function Am(e){let a=o=>{if(!o)return 1/0;let t=$r.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function xm({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(g=>pt(g.name,g.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[a]),n=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return a.map(h=>{let v=g.get(pt(h.name,h.author?.name))??f.get(h.name),k=v?.version,T=!!k&&!!h.version&&ze(h.version,k);return {...h,updateAvailable:T,catalogItem:v}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(g=>{if(i.has(pt(g.name,g.author?.name)))return false;if(g.type==="mcp"){let f=g.installCommand?Sm(g.installCommand)?.toLowerCase():null;if(s.has(g.name.toLowerCase())||f&&s.has(f))return false}return true}).map(g=>Cm(g)):o==="updates"?n.filter(g=>g.updateAvailable).map(g=>Zd(g,g.catalogItem)):n.map(g=>Zd(g,g.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(g=>{let f=g.type??"bundle";if(!t.types.has(f))return false;let h=g.origin??"internal";return t.origins.has(h)}),[d,t]),c=useMemo(()=>{let{types:g}=t;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),p=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return h=>h?g.get(pt(h.name,h.authorName))??f.get(h.name)??null:null},[e]),m=useMemo(()=>n.filter(g=>g.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:p,outdatedCount:m}}function ec(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:p}=await ap();if(a(u),p.length>0){let m=p.map(g=>g.adapterName).join(", ");n(`Some catalogs failed to load: ${m}`);}d.current||(d.current=!0,C(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function Em(){return {items:ye(a=>a.installedItems)}}I();var RP=P("catalog");function Tm(){let e=y(X=>X.bundleInstallFlow),a=y(X=>X.activeTab),o=y(X=>X.notification),t=y(X=>X.loading),r=y(X=>X.loadingMessage),i=y(X=>X.downloadProgress),s=y(X=>X.downloadTotal),n=y(X=>X.catalogError),d=y(X=>X.setCatalogError),l=y(X=>X.catalogFilters),c=_e(X=>X.query),{catalog:u,isLoading:p,error:m,refetch:g}=ec(),{items:f}=Em(),h=ye(X=>X.loadFromDisk),{items:v,emptyMessage:k,getSelectedCatalogItem:T,outdatedCount:L}=xm({catalog:u,installedItems:f,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:M,selectedIndex:F,clampIndex:N,filteredItems:oe}=cm({listLength:v.length}),x=oe(v),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:Am(x),[a,x]),ae=useMemo(()=>a==="installed"||a==="updates"?Rm(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>T(z),[T,z]),{notify:_}=um(),{handleInstall:E,handleUninstall:B,handleToggleStatus:Q,handleUpdate:Fe,handleBatchUpdate:si,handleMcpConfigUninstall:Dh}=ym({selectedItem:z,selectedCatalogItem:W,items:v,closeMenu:M,clampIndex:N,notify:_}),{handleBundleInstallStart:wh,handleBundleDetailConfirm:Sh,handleBundleDetailBack:Ch,handleBundleInstallComplete:Rh}=wm({closeMenu:M,notify:_}),Ah=useCallback(()=>si(J),[si,J]);return useEffect(()=>{h();},[]),useEffect(()=>{N(J.length);},[J.length,N]),useEffect(()=>{m&&(RP.error(`[catalog] ${m instanceof Error?m.message:String(m)}`),d("Failed to load catalog"));},[m]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsx(mu,{outdatedCount:L}),a==="marketplaces"&&Co()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(im,{})}):jsx(Tu,{filteredItems:J,groups:ae,emptyMessage:k,onBatchUpdate:Ah}),(t||p)&&jsxs(Fragment,{children:[jsx($i,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:i,total:s})})]}),n&&!p&&a==="discover"&&jsx(es,{message:n,onRetry:()=>{d(null),g();},onBack:()=>d(null)}),o&&jsx(Mu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Hp,{bundle:e.bundle,onComplete:Rh}):jsx(qp,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>wh(z.name,z.flowId),onConfirm:Sh,onClose:e?.phase==="detail"?Ch:M}):jsx(Tp,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:M}):z.type==="mcp"?jsx(Bp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:Dh,onClose:M}):jsx(Op,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:B,onToggleStatus:X=>Q(X),onUpdate:Fe,onClose:M})),jsx(Ki,{})]})}var q=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(ye.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Re();var TP=3;function qm(){let e=q(c=>c.setStarterKits),a=q(c=>c.setIsLoadingStarterKits),o=q(c=>c.setStarterKitsError),t=q(c=>c.setPluginStatus),r=q(c=>c.setPluginDownloadProgress),i=q(c=>c.setStep),s=q(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await ns();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{ye.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=q.getState().plugins.filter(p=>p.selected&&p.status==="pending");for(let p of c){t(p.name,"installing"),d.current=0;let m="",g=false;for(let f=1;f<=TP;f++)try{await je(p.name,{onDownloadProgress:(h,v)=>{let k=Date.now();(k-d.current>100||h>=v)&&(d.current=k,r(p.name,h,v));}}),t(p.name,"success"),g=!0;break}catch(h){if(h instanceof Xe){t(p.name,"success"),g=true;break}m=h instanceof Error?h.message:"Unknown error";}g||(t(p.name,"failed",m),C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:p.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:m,interface:Z().interfaceType}).catch(()=>{}));}let u=$o();Ko("summary_review"),C(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),ye.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var Yr={cursorDelta:0,confirm:false,back:false};function Lm(e,a){return a.upArrow?{...Yr,cursorDelta:-1}:a.downArrow?{...Yr,cursorDelta:1}:a.escape?{...Yr,back:true}:a.return?{...Yr,confirm:true}:Yr}var MP={cursorDelta:0,select:false};function Fm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:MP}j();var Om=Sv.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:b(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:b(a.description)})})]})});var nc=5;function Nm({onRetry:e}){let a=q(c=>c.starterKits),o=q(c=>c.selectedStarterKitIndex),t=q(c=>c.isLoadingStarterKits),r=q(c=>c.starterKitsError);if(t)return jsx($i,{message:"Loading Starter Kits..."});if(r)return jsx(es,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(Lt,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(nc/2)),s=Math.min(a.length,i+nc);s===a.length&&(i=Math.max(0,s-nc));let n=a.slice(i,s),d=i,l=a.length-s;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"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Om,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var Bm=Sv.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",b(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});j();var lc=8;function jm(){let e=q(c=>c.selectedStarterKit),a=q(c=>c.plugins),o=q(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,C(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(lc/2)),s=Math.min(a.length,i+lc);s===a.length&&(i=Math.max(0,s-lc));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:b(e.name)}),jsx(Text,{dimColor:true,children:b(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Bm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var UP=["Retry failed","Continue anyway"];function Um({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=b(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function zm({onComplete:e,onRetry:a}){let o=q(l=>l.plugins),t=q(l=>l.step),r=q(l=>l.successCount),i=q(l=>l.failedCount),s=q(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="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:n.map(l=>jsx(Um,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.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:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(Um,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:UP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Wm(){let e=q(x=>x.step),a=q(x=>x.starterKits),o=q(x=>x.selectedStarterKitIndex),t=q(x=>x.setSelectedStarterKitIndex),r=q(x=>x.selectStarterKit),i=q(x=>x.plugins),s=q(x=>x.pluginCursorIndex),n=q(x=>x.setPluginCursorIndex),d=q(x=>x.setStep),l=q(x=>x.summaryActionIndex),c=q(x=>x.setSummaryActionIndex),u=q(x=>x.failedCount),p=q(x=>x.resetForRetry),m=q(x=>x.goBackToList),g=y(x=>x.setScreen),f=y(x=>x.setFocus),h=y(x=>x.focus),v=oa(x=>x.setJustAuthenticated),k=oa(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:L}=qm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),A.current||(A.current=true,Ko("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let M=useCallback(async()=>{let x=q.getState().selectedStarterKit;if(x){let ae=await Y();ae&&await ko({...ae,starterKit:x.slug});}C(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:$o()}).catch(()=>{});let{successCount:J}=q.getState();C(w.CLI_ONBOARDING_COMPLETED,{duration_ms:Do(),tools_installed_count:J}).catch(()=>{}),v(false),f("verify"),g("verify");},[v,f,g]),F=useCallback(()=>{p(),L();},[p,L]),N=useCallback(()=>{T();},[T]),oe=useCallback(()=>{f("verify"),g("verify");},[f,g]);return useInput((x,J)=>{if(J.escape)qi("esc"),oe();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ae=$o();r(a[o]),Ko("kit_display"),C(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ae}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,J)=>{let ae=Lm(x,J);if(ae.cursorDelta!==0){let z=s+ae.cursorDelta;z>=0&&z<i.length&&n(z);}if(ae.confirm){let z=q.getState().selectedStarterKit;z&&(async()=>(await Y())?.starterKit!==z.slug&&C(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=$o();Ko("kit_confirmation"),C(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let _=$o();Ko("tool_installation"),C(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:_}).catch(()=>{}),d("installing"),L();}if(ae.back){let z=q.getState().selectedStarterKit;z&&C(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),m();}},{isActive:h==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ae=Fm(x,J);if(ae.cursorDelta!==0){let z=l+ae.cursorDelta;z>=0&&z<=1&&c(z);}ae.select&&(l===0?F():M());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),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."}),!k&&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(Nm,{onRetry:N}),e==="starterKitDetail"&&jsx(jm,{}),(e==="installing"||e==="summary")&&jsx(zm,{onComplete:M,onRetry:F})]}),jsx(Ki,{})]})}U();var Qm=null;function Vm(){return Qm}async function Bs(){let a=ot().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=ce.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await _m(t);(r||i)&&await Pa({...o,installedVersion:r,installMethod:i});}}async function _m(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await ja(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function ar(e){let a=await Promise.all(e.map(o=>JP(o)));return Qm=a,a}async function JP(e){let a=Jm(e.versionCommand);a==="permission-denied"&&(HP(e.versionCommand[0]),a=Jm(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await ja(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await _m(e);await Pa({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function Jm(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function HP(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=se__default.realpathSync(o),{mode:r}=se__default.statSync(t);se__default.chmodSync(t,r|73);}catch{}}function _P(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function Zm(e,a){let[o,t]=useState(()=>_P(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(p=>p.map(m=>m.module.alias!==u||m.module.required?m:{...m,checked:!m.checked}));},[]),l=useCallback((u,p)=>{t(m=>m.map(g=>g.module.alias===u?{...g,selectedStrategy:p}:g));},[]);useInput((u,p)=>{let m=s.current,g=n.current,f=p.upArrow||u==="[A",h=p.downArrow||u==="[B";if(f||h)f&&m>0?i(m-1):h&&m<g.length-1&&i(m+1);else if(u===" "){let v=g[m];v&&!v.module.required&&d(v.module.alias);}else if(p.tab){let v=g[m];if(v&&v.availableStrategies.length>1){let k=v.availableStrategies.indexOf(v.selectedStrategy??v.availableStrategies[0]),T=v.availableStrategies[(k+1)%v.availableStrategies.length];t(L=>L.map(A=>A.module.alias===v.module.alias?{...A,selectedStrategy:T}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}j();function ag({probeResults:e,onConfirm:a}){let o=y(m=>m.focus),t=y(m=>m.actionMenuOpen),r=y(m=>m.setActionMenuOpen),i=y(m=>m.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=Zm(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(m=>{(m==="Install"||m==="Skip")&&a(d),l();},[d,a,l]);useInput((m,g)=>{g.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],p=d.length>0?`Install ${d.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:s.map((m,g)=>{let f=g===n,h=b(m.module.name);return m.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},m.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:f?"cyan":void 0,children:[f?"\u25B6":" ",m.checked?" [\u2713] ":" [ ] ",h]}),m.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",m.selectedStrategy??""]}),m.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",m.availableStrategies.indexOf(m.selectedStrategy??m.availableStrategies[0])+1,"/",m.availableStrategies.length," \u2194)"]})]}),m.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:b(m.module.description)})})]},m.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"})}),t&&jsx(ra,{itemName:p,actions:u,onAction:c,onClose:l})]})}var ZP=/^https?:\/\/.+/;function og({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&ZP.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(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:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="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:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&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 aD(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function ig(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,p)=>{t(m=>m.map(g=>g.alias===u?{...g,...p}:g));},[]),n=useCallback(async()=>{for(let u of e){let p=aD(u);if(!u.selectedStrategy){let m=p?`No package manager available. Install manually: ${p}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:m,manualInstallHint:p||void 0});continue}s(u.module.alias,{status:"installing"});try{let m=await xo(u.module,"onboarding",u.selectedStrategy,a);m.success?s(u.module.alias,{status:"installed",pendingSetupCommand:m.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":m.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:m.error?.message??"Installation failed",manualInstallHint:p});}catch(m){s(u.module.alias,{status:"failed",error:m instanceof Error?m.message:"Unknown error",manualInstallHint:p});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();j();function sg({module:e}){let a=b(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:b(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",b(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function lg({confirmedItems:e,customUrl:a}){let o=y(v=>v.setScreen),t=y(v=>v.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=ig(e,a),c=r.some(v=>v.pendingSetupCommand),u=useRef(false),p=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let m=useCallback(()=>{tt().catch(()=>{}),t("list");let v=le().some(k=>k.name===me);o(v?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!p.current){p.current=true;let v=setTimeout(m,1500);return ()=>clearTimeout(v)}},[s,d,c,m]),useInput((v,k)=>{k.return&&m();},{isActive:s});let g=r.filter(v=>v.pendingSetupCommand).length,f=n-g,h=[];return f>0&&h.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),g>0&&h.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),d>0&&h.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&h.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(v=>jsx(sg,{module:v},v.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((v,k,T)=>(T>0&&v.push(jsx(Text,{children:" | "},`sep-${T}`)),v.push(k),v),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function pg(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(m=>m.setFocus),l=y(m=>m.setScreen),c=useCallback(m=>{if(_l(m)){tt().catch(()=>{}),d("list");let f=le().some(h=>h.name===me);l(f?"main":"claudeMdSuggestion");}else t(m),a("selection");},[d,l]);useEffect(()=>{let m=Vm();if(m){c(m);return}ar(ce).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(m=>{i(m);let g=m.some(f=>f.module.alias==="metrics");a(g?"customUrl":"installation");},[]),p=useCallback(m=>{n(m),a("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(ag,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(og,{onConfirm:p}),e==="installation"&&jsx(lg,{confirmedItems:r,customUrl:s})]})}U();I();var uD=P("ClaudeMdSuggestion"),pD=[`Install ${me}`,"Skip for now"],mD=["Retry","Skip for now"];function fg(){let e=y(p=>p.setScreen),a=y(p=>p.setFocus),o=q(p=>p.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{C(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,C(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await je(me),r("installed");}catch(p){if(p instanceof Xe){r("installed");return}uD.warn(`Failed to install ${me}: ${p instanceof Error?p.message:p}`),r("error");}},[]),u=t==="error"?mD:pD;return useInput((p,m)=>{if(m.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){m.upArrow&&i>0?s(i-1):m.downArrow&&i<u.length-1?s(i+1):m.return&&(i===0?(s(0),c()):l());return}t==="installed"&&m.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="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(gg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",me,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",me," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",me]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",me]}),jsx(gg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function gg({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var bD=promisify(execFile),Js="@ciandt-flow/cli";async function hg(){let e=re;if(Kd.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js};try{let a=await fetch(`https://registry.npmjs.org/${Js}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Js}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js}}}async function Hs(e){try{return await bD(Ya(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function vD(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await ja(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await Pa({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function bg(e){let a=await vD(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function vg(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await ja(o.installMethod).update(e,a.currentVersion??"");return r.success?(await Pa({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function yg(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function kg(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ce.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([hg(),ar(ce),Promise.all(ce.map(d=>bg(d)))]);if(Bs(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Hs(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=ce.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await vg(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:yg(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await tt(),a(d=>({...d,outcome:"done"}));}catch{await tt(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function SD({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{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 CD({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 Pg(){let{outcome:e,items:a}=kg(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=le().some(s=>s.name===me);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),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:a.map(r=>jsx(SD,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(CD,{outcome:e})})]})}Re();xt();I();xn();var ED={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Dg=10;function wg(){let[e,a]=useState(An());useEffect(()=>ul(()=>{a([...An()]);}),[]);let o=e.slice(-Dg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Dg,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:ED[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var qD=P("app"),LD={auth:iu,starterKitSetup:Wm,moduleSetup:pg,claudeMdSuggestion:fg,verify:Pg,main:Tm};function Rg(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Vi(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function Ag(){C(w.CLI_SESSION_STARTED,{cli_version:re,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});}async function Eg(){let e=await Y();if(e&&Ql()&&await Po()){e.customUrl&&La(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),Ag(),Vi(e);return}if(!e){Rg();return}try{e.customUrl&&La(e.customUrl),await Oa();}catch(t){qD.debug(`Token validation failed: ${String(t)}`),Rg();return}Ag();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Vi(e);}function Ig(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=LD[o],{pendingExit:r}=Nl(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(wg,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Re();Ti();j();U();I();mr();Re();async function Dc(e,a={}){let o=Oi({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return Ni(o),await ko(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Ta=P("auth");function Mg(){Ve.clearFallbackFile(),Ai();}var FD=3,Tg=3,qg=` \u2139 The data collected during setup is used solely to improve
|
|
121
|
+
[y/N] `))return Is.debug(`[${e}] Removal cancelled by user`),D("Operation cancelled."),0}let t=a.silent?void 0:Sc({text:`Removing MCP "${b(e)}"...`}).start();try{let r=await qe(o);return t?.stop(),r.exitCode!==0?(_r(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&D(`stdout: ${r.stdout}`),1):(hm(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),_r(a,{name:e,action:"remove",message:$(r)}),1}}I();function ym({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=P("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:p,update:m}=gm(),g=async(A,M,F)=>{d(true,A),t();try{await M(),r(o.length),i(F,"success");}catch(N){let te=N instanceof Error?N.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${te}`),i(te,"error");}finally{d(false);}};return {handleInstall:(A,M)=>{e&&a&&(n.current=0,g(`Installing ${e.name}...`,()=>c(a,{scope:A,...M!==void 0?{providerId:M}:{},onDownloadProgress:(F,N)=>{let te=Date.now();(te-n.current>100||F>=N)&&(n.current=te,l(F,N));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&g(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let M=e.status==="enabled";g(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>p(e.name,A),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await m(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Io)i(F.message,"info");else {let N=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${N}`),i(N,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let M=A.length;(async()=>{d(true,`Updating ${M} plugin${M>1?"s":""}...`),t();try{let N=[];for(let J of A)N.push(await m(J.name).then(()=>({status:"fulfilled",value:void 0}),ae=>({status:"rejected",reason:ae})));let te=N.filter(J=>J.status==="fulfilled").length,x=N.map((J,ae)=>J.status==="rejected"?A[ae].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${te}/${M} plugin${M>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${te}/${M}; failed: ${x.join(", ")}`,te>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&g(`Removing MCP ${e.name}...`,async()=>{let M=$d(e.name,A),F=await qe(M);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");ye.getState().loadFromDisk();},"\u2713 MCP removed");}}}xr();I();var Xr=P("api:bundle"),Zt=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Kr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},yP=/^[a-zA-Z0-9_-]{1,128}$/;async function Pm(e,a){if(e instanceof HTTPError){let o=e.response.status;throw Xr.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new Zt(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Kr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw Xr.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function Dm(e){if(!yP.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by flowId "${e}"`);try{return await eo().get(`v1/use-cases/${a}`).json()}catch(o){return Pm(o,e)}}async function Ts(e){let a=encodeURIComponent(e);Xr.debug(`Fetching bundle by name "${e}"`);let o;try{o=await eo().get(`v1/use-cases/by-name/${a}`).json(),Xr.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return Pm(t,e)}if(o.length===0)throw new Zt(e);return o[0]}I();var kP=P("tui:bundle-flow");function wm({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();kP.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?Dm(u):Ts(n)).then(m=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:m});}).catch(m=>{l(false),a(m instanceof Error?m.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),ye.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}j();U();var $r=["local","project","user"],PP=new Set(["--transport","--scope","-s"]);function Sm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(PP.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function pt(e,a){return a?`${e}::${a}`:e}function Yd(e){return e===pe?dr:ft}function Cm(e){return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??dr,flowId:e.flowId}}function Zd(e,a){let o=Yd(e.marketplace);return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function Rm(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return $r.filter(o=>a.has(o)).map(o=>({scope:o,label:Xa[o].label,pathHint:Xa[o].pathHint,items:a.get(o)??[]}))}function Am(e){let a=o=>{if(!o)return 1/0;let t=$r.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function xm({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(g=>pt(g.name,g.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(g=>g.type==="mcp").map(g=>g.name.toLowerCase())),[a]),n=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return a.map(h=>{let v=g.get(pt(h.name,h.author?.name))??f.get(h.name),k=v?.version,T=!!k&&!!h.version&&ze(h.version,k);return {...h,updateAvailable:T,catalogItem:v}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(g=>{if(i.has(pt(g.name,g.author?.name)))return false;if(g.type==="mcp"){let f=g.installCommand?Sm(g.installCommand)?.toLowerCase():null;if(s.has(g.name.toLowerCase())||f&&s.has(f))return false}return true}).map(g=>Cm(g)):o==="updates"?n.filter(g=>g.updateAvailable).map(g=>Zd(g,g.catalogItem)):n.map(g=>Zd(g,g.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(g=>{let f=g.type??"bundle";if(!t.types.has(f))return false;let h=g.origin??"internal";return t.origins.has(h)}),[d,t]),c=useMemo(()=>{let{types:g}=t;if(g.size===1){if(g.has("skill"))return "skills";if(g.has("mcp"))return "MCPs";if(g.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),p=useMemo(()=>{let g=new Map(e.map(h=>[pt(h.name,h.author?.name),h])),f=new Map(e.map(h=>[h.name,h]));return h=>h?g.get(pt(h.name,h.authorName))??f.get(h.name)??null:null},[e]),m=useMemo(()=>n.filter(g=>g.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:p,outdatedCount:m}}function ec(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:p}=await ap();if(a(u),p.length>0){let m=p.map(g=>g.adapterName).join(", ");n(`Some catalogs failed to load: ${m}`);}d.current||(d.current=!0,C(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function Em(){return {items:ye(a=>a.installedItems)}}I();var RP=P("catalog");function Tm(){let e=y(X=>X.bundleInstallFlow),a=y(X=>X.activeTab),o=y(X=>X.notification),t=y(X=>X.loading),r=y(X=>X.loadingMessage),i=y(X=>X.downloadProgress),s=y(X=>X.downloadTotal),n=y(X=>X.catalogError),d=y(X=>X.setCatalogError),l=y(X=>X.catalogFilters),c=_e(X=>X.query),{catalog:u,isLoading:p,error:m,refetch:g}=ec(),{items:f}=Em(),h=ye(X=>X.loadFromDisk),{items:v,emptyMessage:k,getSelectedCatalogItem:T,outdatedCount:L}=xm({catalog:u,installedItems:f,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:M,selectedIndex:F,clampIndex:N,filteredItems:te}=cm({listLength:v.length}),x=te(v),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:Am(x),[a,x]),ae=useMemo(()=>a==="installed"||a==="updates"?Rm(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>T(z),[T,z]),{notify:_}=um(),{handleInstall:E,handleUninstall:B,handleToggleStatus:Q,handleUpdate:Fe,handleBatchUpdate:si,handleMcpConfigUninstall:Dh}=ym({selectedItem:z,selectedCatalogItem:W,items:v,closeMenu:M,clampIndex:N,notify:_}),{handleBundleInstallStart:wh,handleBundleDetailConfirm:Sh,handleBundleDetailBack:Ch,handleBundleInstallComplete:Rh}=wm({closeMenu:M,notify:_}),Ah=useCallback(()=>si(J),[si,J]);return useEffect(()=>{h();},[]),useEffect(()=>{N(J.length);},[J.length,N]),useEffect(()=>{m&&(RP.error(`[catalog] ${m instanceof Error?m.message:String(m)}`),d("Failed to load catalog"));},[m]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsx(mu,{outdatedCount:L}),a==="marketplaces"&&Co()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(im,{})}):jsx(Tu,{filteredItems:J,groups:ae,emptyMessage:k,onBatchUpdate:Ah}),(t||p)&&jsxs(Fragment,{children:[jsx($i,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:i,total:s})})]}),n&&!p&&a==="discover"&&jsx(es,{message:n,onRetry:()=>{d(null),g();},onBack:()=>d(null)}),o&&jsx(Mu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Hp,{bundle:e.bundle,onComplete:Rh}):jsx(qp,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>wh(z.name,z.flowId),onConfirm:Sh,onClose:e?.phase==="detail"?Ch:M}):jsx(Tp,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:M}):z.type==="mcp"?jsx(Bp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:Dh,onClose:M}):jsx(Op,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:B,onToggleStatus:X=>Q(X),onUpdate:Fe,onClose:M})),jsx(Ki,{})]})}var q=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(ye.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Re();var TP=3;function qm(){let e=q(c=>c.setStarterKits),a=q(c=>c.setIsLoadingStarterKits),o=q(c=>c.setStarterKitsError),t=q(c=>c.setPluginStatus),r=q(c=>c.setPluginDownloadProgress),i=q(c=>c.setStep),s=q(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await ns();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{ye.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=q.getState().plugins.filter(p=>p.selected&&p.status==="pending");for(let p of c){t(p.name,"installing"),d.current=0;let m="",g=false;for(let f=1;f<=TP;f++)try{await je(p.name,{onDownloadProgress:(h,v)=>{let k=Date.now();(k-d.current>100||h>=v)&&(d.current=k,r(p.name,h,v));}}),t(p.name,"success"),g=!0;break}catch(h){if(h instanceof Xe){t(p.name,"success"),g=true;break}m=h instanceof Error?h.message:"Unknown error";}g||(t(p.name,"failed",m),C(w.CLI_TOOL_INSTALL_FAILED,{tool_id:p.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:m,interface:Z().interfaceType}).catch(()=>{}));}let u=$o();Ko("summary_review"),C(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),ye.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var Yr={cursorDelta:0,confirm:false,back:false};function Lm(e,a){return a.upArrow?{...Yr,cursorDelta:-1}:a.downArrow?{...Yr,cursorDelta:1}:a.escape?{...Yr,back:true}:a.return?{...Yr,confirm:true}:Yr}var MP={cursorDelta:0,select:false};function Fm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:MP}j();var Om=Sv.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:b(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:b(a.description)})})]})});var nc=5;function Nm({onRetry:e}){let a=q(c=>c.starterKits),o=q(c=>c.selectedStarterKitIndex),t=q(c=>c.isLoadingStarterKits),r=q(c=>c.starterKitsError);if(t)return jsx($i,{message:"Loading Starter Kits..."});if(r)return jsx(es,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(Lt,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(nc/2)),s=Math.min(a.length,i+nc);s===a.length&&(i=Math.max(0,s-nc));let n=a.slice(i,s),d=i,l=a.length-s;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"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Om,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var Bm=Sv.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",b(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});j();var lc=8;function jm(){let e=q(c=>c.selectedStarterKit),a=q(c=>c.plugins),o=q(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,C(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(lc/2)),s=Math.min(a.length,i+lc);s===a.length&&(i=Math.max(0,s-lc));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:b(e.name)}),jsx(Text,{dimColor:true,children:b(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(Bm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var UP=["Retry failed","Continue anyway"];function Um({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=b(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(Zi,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function zm({onComplete:e,onRetry:a}){let o=q(l=>l.plugins),t=q(l=>l.step),r=q(l=>l.successCount),i=q(l=>l.failedCount),s=q(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="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:n.map(l=>jsx(Um,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.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:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(Um,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:UP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Wm(){let e=q(x=>x.step),a=q(x=>x.starterKits),o=q(x=>x.selectedStarterKitIndex),t=q(x=>x.setSelectedStarterKitIndex),r=q(x=>x.selectStarterKit),i=q(x=>x.plugins),s=q(x=>x.pluginCursorIndex),n=q(x=>x.setPluginCursorIndex),d=q(x=>x.setStep),l=q(x=>x.summaryActionIndex),c=q(x=>x.setSummaryActionIndex),u=q(x=>x.failedCount),p=q(x=>x.resetForRetry),m=q(x=>x.goBackToList),g=y(x=>x.setScreen),f=y(x=>x.setFocus),h=y(x=>x.focus),v=oa(x=>x.setJustAuthenticated),k=oa(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:L}=qm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),A.current||(A.current=true,Ko("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let M=useCallback(async()=>{let x=q.getState().selectedStarterKit;if(x){let ae=await Y();ae&&await ko({...ae,starterKit:x.slug});}C(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:$o()}).catch(()=>{});let{successCount:J}=q.getState();C(w.CLI_ONBOARDING_COMPLETED,{duration_ms:Do(),tools_installed_count:J}).catch(()=>{}),v(false),f("verify"),g("verify");},[v,f,g]),F=useCallback(()=>{p(),L();},[p,L]),N=useCallback(()=>{T();},[T]),te=useCallback(()=>{f("verify"),g("verify");},[f,g]);return useInput((x,J)=>{if(J.escape)qi("esc"),te();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ae=$o();r(a[o]),Ko("kit_display"),C(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ae}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,J)=>{let ae=Lm(x,J);if(ae.cursorDelta!==0){let z=s+ae.cursorDelta;z>=0&&z<i.length&&n(z);}if(ae.confirm){let z=q.getState().selectedStarterKit;z&&(async()=>(await Y())?.starterKit!==z.slug&&C(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=$o();Ko("kit_confirmation"),C(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let _=$o();Ko("tool_installation"),C(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:_}).catch(()=>{}),d("installing"),L();}if(ae.back){let z=q.getState().selectedStarterKit;z&&C(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),m();}},{isActive:h==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ae=Fm(x,J);if(ae.cursorDelta!==0){let z=l+ae.cursorDelta;z>=0&&z<=1&&c(z);}ae.select&&(l===0?F():M());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),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."}),!k&&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(Nm,{onRetry:N}),e==="starterKitDetail"&&jsx(jm,{}),(e==="installing"||e==="summary")&&jsx(zm,{onComplete:M,onRetry:F})]}),jsx(Ki,{})]})}U();var Qm=null;function Vm(){return Qm}async function Bs(){let a=ot().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=ce.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await _m(t);(r||i)&&await Pa({...o,installedVersion:r,installMethod:i});}}async function _m(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await ja(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function ar(e){let a=await Promise.all(e.map(o=>JP(o)));return Qm=a,a}async function JP(e){let a=Jm(e.versionCommand);a==="permission-denied"&&(HP(e.versionCommand[0]),a=Jm(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await ja(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await _m(e);await Pa({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function Jm(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function HP(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=se__default.realpathSync(o),{mode:r}=se__default.statSync(t);se__default.chmodSync(t,r|73);}catch{}}function _P(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function Zm(e,a){let[o,t]=useState(()=>_P(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(p=>p.map(m=>m.module.alias!==u||m.module.required?m:{...m,checked:!m.checked}));},[]),l=useCallback((u,p)=>{t(m=>m.map(g=>g.module.alias===u?{...g,selectedStrategy:p}:g));},[]);useInput((u,p)=>{let m=s.current,g=n.current,f=p.upArrow||u==="[A",h=p.downArrow||u==="[B";if(f||h)f&&m>0?i(m-1):h&&m<g.length-1&&i(m+1);else if(u===" "){let v=g[m];v&&!v.module.required&&d(v.module.alias);}else if(p.tab){let v=g[m];if(v&&v.availableStrategies.length>1){let k=v.availableStrategies.indexOf(v.selectedStrategy??v.availableStrategies[0]),T=v.availableStrategies[(k+1)%v.availableStrategies.length];t(L=>L.map(A=>A.module.alias===v.module.alias?{...A,selectedStrategy:T}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}j();function ag({probeResults:e,onConfirm:a}){let o=y(m=>m.focus),t=y(m=>m.actionMenuOpen),r=y(m=>m.setActionMenuOpen),i=y(m=>m.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=Zm(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(m=>{(m==="Install"||m==="Skip")&&a(d),l();},[d,a,l]);useInput((m,g)=>{g.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],p=d.length>0?`Install ${d.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:s.map((m,g)=>{let f=g===n,h=b(m.module.name);return m.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},m.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:f?"cyan":void 0,children:[f?"\u25B6":" ",m.checked?" [\u2713] ":" [ ] ",h]}),m.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",m.selectedStrategy??""]}),m.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",m.availableStrategies.indexOf(m.selectedStrategy??m.availableStrategies[0])+1,"/",m.availableStrategies.length," \u2194)"]})]}),m.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:b(m.module.description)})})]},m.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"})}),t&&jsx(ra,{itemName:p,actions:u,onAction:c,onClose:l})]})}var ZP=/^https?:\/\/.+/;function og({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&ZP.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(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:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="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:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&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 aD(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function ig(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,p)=>{t(m=>m.map(g=>g.alias===u?{...g,...p}:g));},[]),n=useCallback(async()=>{for(let u of e){let p=aD(u);if(!u.selectedStrategy){let m=p?`No package manager available. Install manually: ${p}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:m,manualInstallHint:p||void 0});continue}s(u.module.alias,{status:"installing"});try{let m=await xo(u.module,"onboarding",u.selectedStrategy,a);m.success?s(u.module.alias,{status:"installed",pendingSetupCommand:m.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":m.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:m.error?.message??"Installation failed",manualInstallHint:p});}catch(m){s(u.module.alias,{status:"failed",error:m instanceof Error?m.message:"Unknown error",manualInstallHint:p});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();j();function sg({module:e}){let a=b(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:b(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",b(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function lg({confirmedItems:e,customUrl:a}){let o=y(v=>v.setScreen),t=y(v=>v.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=ig(e,a),c=r.some(v=>v.pendingSetupCommand),u=useRef(false),p=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let m=useCallback(()=>{tt().catch(()=>{}),t("list");let v=le().some(k=>k.name===me);o(v?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!p.current){p.current=true;let v=setTimeout(m,1500);return ()=>clearTimeout(v)}},[s,d,c,m]),useInput((v,k)=>{k.return&&m();},{isActive:s});let g=r.filter(v=>v.pendingSetupCommand).length,f=n-g,h=[];return f>0&&h.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),g>0&&h.push(jsxs(Text,{color:"red",children:[g," needs setup"]},"p")),d>0&&h.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&h.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(v=>jsx(sg,{module:v},v.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((v,k,T)=>(T>0&&v.push(jsx(Text,{children:" | "},`sep-${T}`)),v.push(k),v),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function pg(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(m=>m.setFocus),l=y(m=>m.setScreen),c=useCallback(m=>{if(_l(m)){tt().catch(()=>{}),d("list");let f=le().some(h=>h.name===me);l(f?"main":"claudeMdSuggestion");}else t(m),a("selection");},[d,l]);useEffect(()=>{let m=Vm();if(m){c(m);return}ar(ce).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(m=>{i(m);let g=m.some(f=>f.module.alias==="metrics");a(g?"customUrl":"installation");},[]),p=useCallback(m=>{n(m),a("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(ag,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(og,{onConfirm:p}),e==="installation"&&jsx(lg,{confirmedItems:r,customUrl:s})]})}U();I();var uD=P("ClaudeMdSuggestion"),pD=[`Install ${me}`,"Skip for now"],mD=["Retry","Skip for now"];function fg(){let e=y(p=>p.setScreen),a=y(p=>p.setFocus),o=q(p=>p.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{C(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,C(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await je(me),r("installed");}catch(p){if(p instanceof Xe){r("installed");return}uD.warn(`Failed to install ${me}: ${p instanceof Error?p.message:p}`),r("error");}},[]),u=t==="error"?mD:pD;return useInput((p,m)=>{if(m.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){m.upArrow&&i>0?s(i-1):m.downArrow&&i<u.length-1?s(i+1):m.return&&(i===0?(s(0),c()):l());return}t==="installed"&&m.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(qt,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="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(gg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",me,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",me," installed!"]}),jsxs(Box,{flexDirection:"column",children:[jsx(Text,{children:"Open Claude in a new terminal or in VS Code and type:"}),jsxs(Text,{bold:true,color:"cyan",children:["/",me]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",me]}),jsx(gg,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function gg({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var bD=promisify(execFile),Js="@ciandt-flow/cli";async function hg(){let e=oe;if(Kd.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js};try{let a=await fetch(`https://registry.npmjs.org/${Js}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Js}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Js}}}async function Hs(e){try{return await bD(Ya(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function vD(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await ja(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await Pa({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function bg(e){let a=await vD(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function vg(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await ja(o.installMethod).update(e,a.currentVersion??"");return r.success?(await Pa({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function yg(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function kg(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...ce.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([hg(),ar(ce),Promise.all(ce.map(d=>bg(d)))]);if(Bs(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Hs(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=ce.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await vg(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:yg(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await tt(),a(d=>({...d,outcome:"done"}));}catch{await tt(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function SD({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jp,{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 CD({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 Pg(){let{outcome:e,items:a}=kg(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=le().some(s=>s.name===me);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),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:a.map(r=>jsx(SD,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(CD,{outcome:e})})]})}Re();xt();I();xn();var ED={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Dg=10;function wg(){let[e,a]=useState(An());useEffect(()=>ul(()=>{a([...An()]);}),[]);let o=e.slice(-Dg);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Dg,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:ED[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var qD=P("app"),LD={auth:iu,starterKitSetup:Wm,moduleSetup:pg,claudeMdSuggestion:fg,verify:Pg,main:Tm};function Rg(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Vi(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function Ag(){C(w.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Do(),interface:"tui"}).catch(()=>{});}async function Eg(){let e=await Y();if(e&&Ql()&&await Po()){e.customUrl&&La(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),Ag(),Vi(e);return}if(!e){Rg();return}try{e.customUrl&&La(e.customUrl),await Oa();}catch(t){qD.debug(`Token validation failed: ${String(t)}`),Rg();return}Ag();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Vi(e);}function Ig(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=LD[o],{pendingExit:r}=Nl(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(wg,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Re();Ti();j();U();I();mr();Re();async function Dc(e,a={}){let o=Oi({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return Ni(o),await ko(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Ta=P("auth");function Mg(){Ve.clearFallbackFile(),Ai();}var FD=3,Tg=3,qg=` \u2139 The data collected during setup is used solely to improve
|
|
122
122
|
Flow's internal tools and will not be shared externally.
|
|
123
123
|
`;function _a(e,a={}){return new Promise((o,t)=>{let{masked:r=false,defaultValue:i=""}=a;process.stdout.write(e+i);let s=i,n=c=>{if(c===""){d(),t(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
124
124
|
`){d(),process.stdout.write(`
|
|
@@ -263,7 +263,7 @@ This will run: ${s}
|
|
|
263
263
|
`);return process.stdout.write(`
|
|
264
264
|
`),D("Specify a skill name to remove: flow skills remove <name>"),1}let t=da(e),r=Ho(o),i=join(r,t);try{await stat(i);}catch{return S(`Skill "${b(e)}" is not installed.`),1}if(!a.force&&!await sS(`Remove skill "${b(t)}"?`))return D("Cancelled."),0;try{return await rm(i,{recursive:!0,force:!0}),await kf(t,o),await iS(t),K(`Skill "${b(t)}" removed.`),0}catch(s){return S(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}j();I();U();var tn=P("transfer"),Ec=1;function cS(e){return e.marketplace&&e.marketplace!==pe?`${e.name}@${e.marketplace}`:e.name}function lS(e,a){let o=e.filter(r=>a.has(r.name)),t=e.filter(r=>!a.has(r.name));o.length>0&&D(`Already installed (${o.length}): ${o.map(r=>r.name).join(", ")}`),D(`To install (${t.length}): ${t.length>0?t.map(r=>r.name).join(", "):"none"}`);}function If(e){let a=de__default.resolve(e.output);try{let o=le(),t={version:Ec,exportedAt:new Date().toISOString(),plugins:o.map(r=>({name:r.name,marketplace:r.marketplace,scope:r.scope,...r.type!==void 0?{type:r.type}:{}}))};return se__default.writeFileSync(a,JSON.stringify(t,null,2),"utf-8"),K(`Exported ${o.length} plugin(s) to ${a}`),0}catch(o){let t=$(o);return tn.error(`Export failed: ${t}`),S(`Failed to export plugins: ${t}`),1}}async function Tf(e,a={}){if(!await he())return 1;let o;try{let n=se__default.readFileSync(de__default.resolve(e),"utf-8");o=JSON.parse(n);}catch(n){return S(`Failed to read import file "${e}": ${$(n)}`),1}if(o.version!==Ec)return S(`Unsupported export format version ${o.version??"(none)"} \u2014 expected ${Ec}`),1;if(!Array.isArray(o.plugins))return S('Invalid export file format: missing or invalid "plugins" array'),1;if(o.plugins.length===0)return D("No plugins to import"),0;let t=[],r=[],i=0;for(let[n,d]of o.plugins.entries())if(!d?.name||typeof d.name!="string"){let l=`entry[${n}]`;tn.warn(`Skipping ${l}: missing or invalid name`),r.push({name:l,error:"missing or invalid name"});}else d.type==="mcp"?(tn.debug(`[${d.name}] Skipping MCP entry`),i++):t.push(d);if(i>0&&D(`Skipping ${i} MCP(s) \u2014 use 'flow mcp add' to install them manually`),a.diff||a.dryRun){let n=new Set(le().map(d=>d.name));lS(t,n);}if(a.dryRun)return D("Dry-run mode: no plugins were installed"),0;if(t.length===0){D(`
|
|
265
265
|
Import summary: 0 installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}D(`Importing ${t.length} plugin(s)...`);let s=0;for(let n of t){let d=a.scope??n.scope??"user",l=cS(n);tn.debug(`[${n.name}] Installing as "${l}" in scope "${d}"`),await ir([l],{scope:d,force:a.force})===0?s++:r.push({name:n.name,error:"installation failed"});}D(`
|
|
266
|
-
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();j();function O(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}j();I();var pS=P("moduleProxy");function mS(e){if(!process.stdin.isTTY)return Promise.resolve(false);let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(!["n","no"].includes(t.toLowerCase().trim()));});})}async function Mf(e,a){let o=Date.now(),r=spawnSync(e.binaryName,a,{stdio:"inherit",env:process.env}).status??1;await C(w.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:r,duration_ms:Date.now()-o,subcommand:a[0]??null}).catch(i=>{pS.warn(`Failed to emit proxy executed event: ${String(i)}`);}),O(r);}async function Lf(e,a){let o=ce.find(r=>r.alias===e);if(!o){S(`Unknown module alias: '${e}'`),O(1);return}if(!await Ga(o.binaryName)){S(`Module '${e}' (${o.binaryName}) is not installed.`);let r=o.platforms[process.platform];if(!r||r.status!=="supported"){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),O(1);return}let i=(await Promise.all(r.strategies.map(async n=>{try{return await ja(n.type).isAvailable()?n.type:null}catch{return null}}))).find(n=>n!==null)??null;if(!i){S(`No supported installation method available for '${e}' on this platform.`),O(1);return}if(await mS("Would you like to install it now? [Y/n] ")){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let n=await xo(o,"inline",i);if(!n.success){S(`Failed to install '${e}': ${n.error?.message??"unknown error"}`),O(1);return}await Mf(o,a);}else D(`To install manually, run: flow modules install ${e}`),await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),O(1);return}await Mf(o,a);}j();var bS=promisify(execFile);async function vS(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:t}=await bS(Ya(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(t).trim()||null}let a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{let t={"User-Agent":`flow-plugins-cli/${
|
|
266
|
+
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)S(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();j();function O(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}j();I();var pS=P("moduleProxy");function mS(e){if(!process.stdin.isTTY)return Promise.resolve(false);let a=Gd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(!["n","no"].includes(t.toLowerCase().trim()));});})}async function Mf(e,a){let o=Date.now(),r=spawnSync(e.binaryName,a,{stdio:"inherit",env:process.env}).status??1;await C(w.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:r,duration_ms:Date.now()-o,subcommand:a[0]??null}).catch(i=>{pS.warn(`Failed to emit proxy executed event: ${String(i)}`);}),O(r);}async function Lf(e,a){let o=ce.find(r=>r.alias===e);if(!o){S(`Unknown module alias: '${e}'`),O(1);return}if(!await Ga(o.binaryName)){S(`Module '${e}' (${o.binaryName}) is not installed.`);let r=o.platforms[process.platform];if(!r||r.status!=="supported"){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),O(1);return}let i=(await Promise.all(r.strategies.map(async n=>{try{return await ja(n.type).isAvailable()?n.type:null}catch{return null}}))).find(n=>n!==null)??null;if(!i){S(`No supported installation method available for '${e}' on this platform.`),O(1);return}if(await mS("Would you like to install it now? [Y/n] ")){await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let n=await xo(o,"inline",i);if(!n.success){S(`Failed to install '${e}': ${n.error?.message??"unknown error"}`),O(1);return}await Mf(o,a);}else D(`To install manually, run: flow modules install ${e}`),await C(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),O(1);return}await Mf(o,a);}j();var bS=promisify(execFile);async function vS(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:t}=await bS(Ya(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(t).trim()||null}let a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{let t={"User-Agent":`flow-plugins-cli/${oe}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(t.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let r=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:a.signal,headers:t});return r.ok?(await r.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(o);}}catch{return null}}function yS(e,a,o,t){return t?.status==="experimental"?"experimental":!t||t.status!=="supported"||!e?"not_installed":a&&o&&ze(a,o)?"outdated":"installed"}async function Ic(){let e=await Promise.all(ce.map(async a=>{let[o,t]=await Promise.all([Ga(a.binaryName),vS(a)]),i=ta(a.alias)?.installedVersion??null,s=a.platforms[process.platform],n=yS(o,i,t,s),d=i??"\u2014";return [a.name,a.alias,d,n,process.platform]}));return St(["Name","Alias","Version","Status","Platform"],e),0}async function Nf(e){let a=ce.find(s=>s.alias===e);if(!a)return S(`Unknown module alias: '${e}'`),1;let[o]=await ar([a]);if(o.alreadyInstalled){let s=ta(a.alias),n=s?.installedVersion?` (v${s.installedVersion})`:"";return D(`Module ${a.name} already installed${n}. Use: flow modules update ${e}`),0}if(o.availableStrategies.length===0){let s=a.platforms[process.platform],n=a.docs?` See: ${a.docs}`:"";return !s||s.status!=="supported"?S(`Module ${a.name} is not supported on ${process.platform}.${n}`):S(`No installation method available for ${a.name} on ${process.platform}.${n}`),1}let t=o.availableStrategies[0],r=Sc({text:`Installing ${a.name}...`}).start(),i;try{i=await xo(a,"on_demand",t);}finally{r.stop();}return i.success?(K(`${a.name} v${i.version??"unknown"} installed`),i.pendingInteractiveSetup&&spawnSync(i.pendingInteractiveSetup[0],i.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(S(i.error?.message??"Installation failed"),1)}async function Ff(e,a){let o=Sc({text:`Updating ${e.name}...`}).start(),t;try{t=await Ji(e,"command");}catch(r){return o.error(`${e.name}: ${r instanceof Error?r.message:String(r)}`),"error"}if(t.success){let r=t.version??"unknown";return r===a?(o.success(`${e.name}: already up to date (v${a})`),"up_to_date"):(o.success(`${e.name}: v${a} \u2192 v${r}`),"success")}return o.error(`${e.name}: ${t.error?.message??"Update failed"}`),"error"}async function Gf(e){if(e!==null){let t=ce.find(s=>s.alias===e);if(!t)return S(`Unknown module alias: '${e}'`),1;let r=ta(t.alias);return r?.installMethod?await Ff(t,r.installedVersion??"unknown")==="error"?1:0:(S(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let a=ot().filter(t=>t.installMethod!==null);if(a.length===0)return D("No installed modules to update."),0;let o=0;for(let t of a){let r=ce.find(s=>s.alias===t.alias);if(!r)continue;await Ff(r,t.installedVersion??"unknown")==="error"&&(o=1);}return o}var Bf="ea77652b607cf8d3dd0a1359c08565561e4f758f",ri=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
|
|
267
267
|
title: "0-current-state \u2014 Index"
|
|
268
268
|
type: index
|
|
269
269
|
domain: platform
|
|
@@ -554,7 +554,7 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
|
|
|
554
554
|
**6. Source code never in monitored folders.**
|
|
555
555
|
If you create a folder with app or script source code, keep it out of the 5 numbered folders
|
|
556
556
|
entirely (e.g. \`prototypes/\`).
|
|
557
|
-
`},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];var rn=".flow-harness-lock";function sn(e){if(!existsSync(e))return {};try{let a=readFileSync(e,"utf8"),o=JSON.parse(a);return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}catch{return {}}}function nn(e,a){return e.files?.[a]?.sha256}function jf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,strategy_context:true,strategy_context_source:`@ciandt-flow/cli@${
|
|
557
|
+
`},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];var rn=".flow-harness-lock";function sn(e){if(!existsSync(e))return {};try{let a=readFileSync(e,"utf8"),o=JSON.parse(a);return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}catch{return {}}}function nn(e,a){return e.files?.[a]?.sha256}function jf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,strategy_context:true,strategy_context_source:`@ciandt-flow/cli@${oe}`,strategy_context_harness_commit:t};"core_commit"in a||(i.core_commit=""),writeFileSync(e,JSON.stringify(i,null,2)+`
|
|
558
558
|
`,"utf8");}j();var Lc="CLAUDE.md";function CS(e){return createHash("sha256").update(e,"utf8").digest("hex")}function Fc(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function zf(e={}){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??Nc,s=e.confirmCreate??RS,n=join(a,rn),d=sn(n),l=[],c=Fc(),u={},p=ri.find(f=>f.path===Lc),m=p?existsSync(join(a,p.path)):true;if(p&&!m){let f=join(a,p.path);r?await s(p.path)?(l.push({path:p.path,status:"new"}),c.new++,o||(mkdirSync(dirname(f),{recursive:true}),writeFileSync(f,p.content,"utf8"),u[p.path]=p.sha256)):D(`declined: ${Lc} not created`):e.assistant==="claude-code"&&(l.push({path:p.path,status:"new"}),c.new++,o||(mkdirSync(dirname(f),{recursive:true}),writeFileSync(f,p.content,"utf8"),u[p.path]=p.sha256));}for(let f of ri){if(f.path===Lc&&!m)continue;let h=join(a,f.path),v=await Oc({dstPath:h,template:f,existingLockHash:nn(d,f.path),force:t,isInteractive:r,confirmOverwrite:k=>i(k)});l.push({path:f.path,status:v.status}),c[v.status]++,v.write&&!o&&(mkdirSync(dirname(h),{recursive:true}),writeFileSync(h,f.content,"utf8")),v.recordHash&&!o&&(u[f.path]=v.recordHash);}!o&&Object.keys(u).length>0&&jf(n,d,u,Bf);let g=c.divergent>0||c.declined>0;return {files:l,counts:c,hasUnresolved:g}}async function Oc(e){let{dstPath:a,template:o,existingLockHash:t,force:r,isInteractive:i,confirmOverwrite:s}=e;if(!existsSync(a))return {status:"new",write:true,recordHash:o.sha256};let n=CS(readFileSync(a,"utf8"));return n===o.sha256?{status:"unchanged",write:false,recordHash:o.sha256}:t!==void 0&&n===t?r?{status:"clean",write:true,recordHash:o.sha256}:i?await s(o.path)?{status:"clean",write:true,recordHash:o.sha256}:{status:"declined",write:false,recordHash:void 0}:{status:"declined",write:false,recordHash:void 0}:r?{status:"divergent",write:true,recordHash:o.sha256}:(D(`divergent, kept local (customized): ${o.path}`),{status:"divergent",write:false,recordHash:n})}async function Nc(e){return ee(` Overwrite ${e} with the updated template? [y/N] `)}async function RS(e){return ee(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}var Wf="64feeb4e5f6f282d4e0fae6568c0520c5ecd4d5a",Jf=[{path:"docs/catalog/TEMPLATES/agents/_TEMPLATE-LEVEL-0.md",sha256:"5f6d1ef6336d69c9fa53ec3167e4f0eb8ec212e21e771356e357e397946f3638",content:`---
|
|
559
559
|
id: <slug-do-card>
|
|
560
560
|
kind: agent | skill
|
|
@@ -84776,7 +84776,7 @@ updated: "2026-09-23"
|
|
|
84776
84776
|
flow plugin marketplace add cit-flow/flow-harness
|
|
84777
84777
|
flow plugin install runbook-tech-common
|
|
84778
84778
|
\`\`\`
|
|
84779
|
-
`}]};function Hf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,docs_content:true,docs_content_source:`@ciandt-flow/cli@${
|
|
84779
|
+
`}]};function Hf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,docs_content:true,docs_content_source:`@ciandt-flow/cli@${oe}`,docs_content_harness_commit:t};"core_commit"in a||(i.core_commit=""),writeFileSync(e,JSON.stringify(i,null,2)+`
|
|
84780
84780
|
`,"utf8");}function TS(e){let a=new Set,o=[];for(let t of e){let r=cn[t];if(r)for(let i of r)a.has(i.path)||(a.add(i.path),o.push(i));}return o}function MS(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function qS(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function LS(e,a){if(a==="all")return e;let o=new Map,t=[];for(let i of e){if(!i.path.endsWith(".md")){t.push(i);continue}let s=MS(i.path),n=qS(i.path),d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(n,i);}let r=[];for(let[i,s]of o){let n=s.get(a)??s.get("pt")??s.get("en")??s.get("es");r.push({...n,path:i});}return [...t,...r]}async function Vf(e){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??Nc,s=join(a,rn),n=sn(s),d=e.docsLang??"all",l=e.installedBundles.length===0,c=l?[]:TS(e.installedBundles),u=LS([...Jf,...c],d),p=[],m=Fc(),g={};for(let h of u){let v=join(a,h.path),k=await Oc({dstPath:v,template:h,existingLockHash:nn(n,h.path),force:t,isInteractive:r,confirmOverwrite:T=>i(T)});p.push({path:h.path,status:k.status}),m[k.status]++,k.write&&!o&&(mkdirSync(dirname(v),{recursive:true}),writeFileSync(v,h.content,"utf8")),k.recordHash&&!o&&(g[h.path]=k.recordHash);}!o&&Object.keys(g).length>0&&Hf(s,n,g,Wf);let f=m.divergent>0||m.declined>0;return {files:p,counts:m,hasUnresolved:f,skippedPlaybooks:l}}function _f(){let e=Ae().plugins,a=process.cwd(),o=new Set(Object.keys(cn)),t=new Set;for(let[r,i]of Object.entries(e)){let s=r.split("@")[0];if(!s||!o.has(s))continue;i.some(d=>d.scope==="user"||d.projectPath===a)&&t.add(s);}return [...t].sort()}j();I();Re();_o();I();var Gc=P("lib:otelMetrics"),OS="flow-plugins-cli",NS="1.0.0",GS=5e3;function BS(){return Fa("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function jS(e,a){return typeof a=="number"?{key:e,value:{intValue:String(a)}}:typeof a=="boolean"?{key:e,value:{boolValue:a}}:{key:e,value:{stringValue:a}}}function US(e,a){let o=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:OS,version:NS},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:o,timeUnixNano:o,attributes:Object.entries(a).map(([t,r])=>jS(t,r))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Bc(e,a={}){try{let[o,t]=await Promise.all([Rt(),Y()]),r=o?.email,i=t?.tenant;if(!r||!i){Gc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let s=US(e,a);await Xu.post(BS(),{json:s,timeout:GS,headers:{"Content-Type":"application/json","x-flow-user":r,flowtenant:i}}),Gc.debug(`OTel metric sent: ${e}`);}catch(o){Gc.warn(`Failed to send OTel metric "${e}": ${String(o)}`);}}var jc=P("cli:init"),JS={new:{label:"new",color:R.green},unchanged:{label:"unchanged",color:R.dim},clean:{label:"updated",color:R.cyan},divergent:{label:"kept (customized)",color:R.yellow},declined:{label:"pending (declined)",color:R.yellow}};function HS(e){process.stdout.write(`
|
|
84781
84781
|
`+R.bold(` flow setup strategy
|
|
84782
84782
|
`)),process.stdout.write(R.dim(` Target: ${e}
|
|
@@ -84824,7 +84824,7 @@ ${$f}
|
|
|
84824
84824
|
`),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
|
|
84825
84825
|
`),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
|
|
84826
84826
|
`));}async function DC(e,a,o,t){if(o||!t||a.skippedNoManifest||!a.workspaceDirs)return;let{repos_dir:r,refs_dir:i}=a.workspaceDirs,s=await ee(` Add an off-limits note to CLAUDE.md for '${r}/' and '${i}/'? [y/N] `),n=oh(e,a.workspaceDirs,s);n==="appended"?D(`CLAUDE.md updated with an off-limits note for '${r}/' and '${i}/'.`):n==="already-present"?D("CLAUDE.md already has the off-limits note \u2014 skipped."):n==="no-claude-md"&&D("No CLAUDE.md found in this repo \u2014 skipped the off-limits note.");}async function Xc(e={}){yC.debug(`Running flow setup workspace: ${JSON.stringify(e)}`);let a=e.isInteractive??!!process.stdin.isTTY;await PC(e.json);let o=await uh({targetDir:e.path,prune:e.prune});if(e.json)return ve({repos:o.repos,orphans:o.orphans,prunedCount:o.prunedCount,skippedNoManifest:o.skippedNoManifest,manifestWarnings:o.manifestWarnings}),o.repos.some(n=>n.outcome==="failed")?1:0;for(let n of o.manifestWarnings)D(`repos.yaml: ${n}`);if(o.skippedNoManifest)return D("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;for(let n of o.repos)process.stdout.write(` ${n.name}: ${kC(n.outcome)}
|
|
84827
|
-
`);let t=o.repos.filter(n=>n.outcome==="cloned").length,r=o.repos.filter(n=>n.outcome==="updated").length,i=o.repos.filter(n=>n.outcome==="skipped").length,s=o.repos.filter(n=>n.outcome==="failed").length;return K(`${t} cloned, ${r} updated, ${i} skipped`+(s>0?`, ${s} failed`:"")+(o.prunedCount>0?`, ${o.prunedCount} pruned`:"")),o.orphans.length>0&&D(`Orphan director${o.orphans.length===1?"y":"ies"} not in repos.yaml: ${o.orphans.join(", ")}. Re-run with --prune to remove.`),await DC(e.path??process.cwd(),o,e.json,a),s>0?1:0}var wC=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ln({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>_c({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>Xc({path:e})}];async function SC(e){return ee(` Run ${e}? [y/N] `)}async function hh(e={}){let a=e.isInteractive??!!process.stdin.isTTY,o=e.confirmStep??SC,t=!!e.yes||!a;!e.yes&&!a&&D("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let r=[];for(let i of wC){if(!(t||await o(i.label))){D(` \u2192 ${i.key} skipped.`);continue}r.push(await i.run(e.path));}return r.some(i=>i!==0)?1:0}function AC(){let e=fileURLToPath(import.meta.url);return e.endsWith(".js")?{runner:"node",entry:de__default.join(de__default.dirname(e),"ctxa.js")}:{runner:"tsx",entry:de__default.join(de__default.dirname(e),"module/ctxa/cli.ts")}}function bh(e){let a=new Command;a.enablePositionalOptions(),a.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${
|
|
84827
|
+
`);let t=o.repos.filter(n=>n.outcome==="cloned").length,r=o.repos.filter(n=>n.outcome==="updated").length,i=o.repos.filter(n=>n.outcome==="skipped").length,s=o.repos.filter(n=>n.outcome==="failed").length;return K(`${t} cloned, ${r} updated, ${i} skipped`+(s>0?`, ${s} failed`:"")+(o.prunedCount>0?`, ${o.prunedCount} pruned`:"")),o.orphans.length>0&&D(`Orphan director${o.orphans.length===1?"y":"ies"} not in repos.yaml: ${o.orphans.join(", ")}. Re-run with --prune to remove.`),await DC(e.path??process.cwd(),o,e.json,a),s>0?1:0}var wC=[{key:"strategy",label:"strategy (scaffold the numbered documentation structure)",run:e=>ln({path:e})},{key:"harness",label:"harness (install the fixed set of Flow runbook bundles)",run:()=>_c({})},{key:"workspace",label:"workspace (clone/update repos declared in repos.yaml)",run:e=>Xc({path:e})}];async function SC(e){return ee(` Run ${e}? [y/N] `)}async function hh(e={}){let a=e.isInteractive??!!process.stdin.isTTY,o=e.confirmStep??SC,t=!!e.yes||!a;!e.yes&&!a&&D("No interactive terminal and --yes not set \u2014 running all steps without prompting.");let r=[];for(let i of wC){if(!(t||await o(i.label))){D(` \u2192 ${i.key} skipped.`);continue}r.push(await i.run(e.path));}return r.some(i=>i!==0)?1:0}function AC(){let e=fileURLToPath(import.meta.url);return e.endsWith(".js")?{runner:"node",entry:de__default.join(de__default.dirname(e),"ctxa.js")}:{runner:"tsx",entry:de__default.join(de__default.dirname(e),"module/ctxa/cli.ts")}}function bh(e){let a=new Command;a.enablePositionalOptions(),a.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${oe}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
84828
84828
|
Without arguments, opens the interactive interface (TUI).
|
|
84829
84829
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let o=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");o.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
84830
84830
|
Examples:
|
|
@@ -84964,8 +84964,8 @@ Examples:
|
|
|
84964
84964
|
$ flow modules install dashboard`).action(async c=>{let u=await Nf(c);O(u);}),l.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
84965
84965
|
Examples:
|
|
84966
84966
|
$ flow modules update
|
|
84967
|
-
$ flow modules update metrics`).action(async c=>{let u=await Gf(c??null);O(u);}),a.addCommand(l),a.command("ctxa").description("Analyze Claude Code history/config and surface token-cost savings").helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to flow-ctxa").action(c=>{let{runner:u,entry:p}=AC(),m=spawnSync(u,[p,"ctxa",...c],{stdio:"inherit",env:process.env});O(m.status??1);});for(let c of ce)a.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await Lf(c.alias,u);});return a.hook("preAction",()=>{Bs();}),a}I();function IC(){return de__default.join(Ce__default.homedir(),".claude","settings.json")}function yh(){let e=IC();try{if(!se__default.existsSync(e))return !0;let o=JSON.parse(se__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return o===!1?!1:o==="modules-only"?"modules-only":!0}catch{return true}}I();var
|
|
84967
|
+
$ flow modules update metrics`).action(async c=>{let u=await Gf(c??null);O(u);}),a.addCommand(l),a.command("ctxa").description("Analyze Claude Code history/config and surface token-cost savings").helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to flow-ctxa").action(c=>{let{runner:u,entry:p}=AC(),m=spawnSync(u,[p,"ctxa",...c],{stdio:"inherit",env:process.env});O(m.status??1);});for(let c of ce)a.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await Lf(c.alias,u);});return a.hook("preAction",()=>{Bs();}),a}I();function IC(){return de__default.join(Ce__default.homedir(),".claude","settings.json")}function yh(){let e=IC();try{if(!se__default.existsSync(e))return !0;let o=JSON.parse(se__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return o===!1?!1:o==="modules-only"?"modules-only":!0}catch{return true}}I();var NC=P("updateChecker"),GC=promisify(execFile),BC=1440*60*1e3,kh=3e4;function jC(){let e=process.env.FLOW_HOME??de__default.join(Ce__default.homedir(),".flow");return de__default.join(e,"update.lock")}async function Ph(e){try{let{stdout:a}=await GC(Ya(),["view",e,"version"],{timeout:kh,shell:process.platform==="win32"});return String(a).trim()||null}catch{return null}}async function UC(e){let a=new AbortController,o=setTimeout(()=>a.abort(),kh);try{let t=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:a.signal});return t.ok?(await t.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(o);}}async function zC(e){return e.versionCheck.type==="npm-registry"?Ph(e.versionCheck.package):UC(e.versionCheck.repo)}async function WC(){if(Kd.prerelease(oe))return null;let e=await Ph("@ciandt-flow/cli");return e&&ze(oe,e)?(Hs({currentVersion:oe,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function JC(){let e=ot().filter(a=>a.installMethod!==null);await Promise.all(e.map(async a=>{let o=ce.find(s=>s.alias===a.alias);if(!o||o.hasOwnUpdateCheck)return;let t=Date.now(),r=a.lastChecked?new Date(a.lastChecked).getTime():0;if(t-r<BC)return;let i=await zC(o);try{await Pa({...a,lastChecked:new Date().toISOString()});}catch(s){NC.warn(`Failed to update lastChecked for ${a.alias}: ${String(s)}`);}i&&a.installedVersion&&ze(a.installedVersion,i)&&Ji(o,"background").catch(()=>{});}));}async function $c(){let e=yh();if(e===false)return;let a=jC();se__default.mkdirSync(de__default.dirname(a),{recursive:true});let o=null;try{o=await _b.lock(a,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let t=await WC().catch(()=>null);t&&process.stdout.write(`
|
|
84968
84968
|
\u26A0 @ciandt-flow/cli v${t} installing in background.
|
|
84969
84969
|
Restart flow to apply the update.
|
|
84970
84970
|
|
|
84971
|
-
`);}await
|
|
84971
|
+
`);}await JC().catch(()=>{});}finally{await o().catch(()=>{});}}var QC=P("cli"),Yc=bh(async()=>{Qe("tui"),Ml("tui"),ql(),process.on("SIGINT",()=>{let{activeTab:a,screen:o}=y.getState();fr("sigint",a,o).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:a,screen:o}=y.getState();fr("sigterm",a,o).finally(()=>process.exit(143));}),await $c().catch(()=>{}),await Zu().catch(a=>{QC.error(`Failed to init catalog registry: ${String(a)}`);}),await Eg();let{waitUntilExit:e}=render(jsx(Ig,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Yc.hook("preAction",async(e,a)=>{a!==Yc&&await $c().catch(()=>{});});Yc.parse();
|