@ciandt-flow/cli 2.3.1-beta.250 → 2.4.0-beta.251
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 +140 -141
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {execa}from'execa';import Gc,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import $g,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as Yr from'crypto';import {randomUUID,createHash}from'crypto';import*as Se from'fs';import Se__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as ye from'path';import ye__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as Ce from'os';import Ce__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as fa from'readline';import {createInterface}from'readline';import k from'chalk';import Ai from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import jf from'jsonwebtoken';import tg from'proper-lockfile';import Ig from'ink-big-text';import Ku from'ink-spinner';import*as Tt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp}from'fs/promises';import Ch from'extract-zip';import {simpleGit}from'simple-git';import Ta from'semver';import tl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var Dm=Object.defineProperty;var pi=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Om=(e,t)=>{for(var r in t)Dm(e,r,{get:t[r],enumerable:true});};function yf(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function Di(e){if(Ll.some(r=>r.test(e)))return true;let t=yf(e);return !!(t&&Ll.some(r=>r.test(t)))}function wf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function nn(e,t){let r=wf(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&Di(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Ll,Bn=pi(()=>{"use strict";Ll=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function vh(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Hc(){return Vc??=vh(),Vc}var Vc,Jc=pi(()=>{"use strict";});var Wc={};Om(Wc,{GitRepoAdapter:()=>mn});function zc(e,t){if(!Ph.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var Ph,mn,ra=pi(()=>{"use strict";Jc();Bn();Ph=/^[a-zA-Z0-9_.-]+$/;mn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if(Di(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return zc(a,"owner"),zc(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await Gc.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await Gc.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Hc();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});var $n="FLOW",Y="flow-skills",mi="flow-cli",Mn="internal",Xr="external",qr={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"}},dl={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},fi=new Set(["internal","external"]),Ln={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},se="flow-claude-md-setup",Ge=5,Er=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Rn=/^https:\/\/[a-zA-Z0-9-]+\.ciandt\.com(\/.*)?$/,_n="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)";var pl=new Set(["skill","mcp","bundle"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(pl),origins:new Set(fi)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(pl)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(fi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var Eo="aes-256-gcm",Um=16,ml=16,Dn=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=Yr.randomBytes(Um),n=Yr.createCipheriv(Eo,this.key,r,{authTagLength:ml}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:Eo}}decrypt(t){if(t.algorithm!==Eo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=Yr.createDecipheriv(Eo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:ml});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var Bm=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Fm=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,jm=/[A-Za-z0-9+/]{40,}={0,2}/g;function gi(e){return e.replace(Bm,"Bearer ***").replace(Fm,"***").replace(jm,"***").replace(/\r\n|\r|\n/g,"\\n")}var Cr=".claude",Co=".flow";function fl(e,t){return yi(Y,e,t)}function hi(e){return ye.join(Ce.homedir(),Cr,"plugins","marketplaces",Y,"plugins","native",e)}function To(){return ye.join(Ce.homedir(),Cr,"plugins","marketplaces",Y,".claude-plugin","marketplace.json")}function ko(){return ye.join(Ce.homedir(),Cr,"plugins","known_marketplaces.json")}function gl(){return ye.join(Ce.homedir(),Cr,"plugins","marketplaces",Y)}function hl(){return ye.join(Ce.homedir(),Co,"cache","install.lock")}function yl(){return ye.join(Ce.homedir(),Co,"logs","flowsetup.log")}function yi(e,t,r){return ye.join(Ce.homedir(),Cr,"plugins","cache",e,t,r)}function Tr(e){let t=e==="global"?Ce.homedir():process.cwd();return ye.join(t,".claude","skills")}function On(e){let t=e==="global"?Ce.homedir():process.cwd();return ye.join(t,".claude","skills-lock.json")}function Ao(e="user"){return e==="project"?ye.join(process.cwd(),".opencode","plugins"):ye.join(Ce.homedir(),".config","opencode","plugins")}function wl(){return ye.join(Ce.homedir(),Co,"flow-catalogs.json")}function Sl(){let e=process.env.FLOW_HOME??ye.join(Ce.homedir(),Co);return ye.join(e,"config.json")}function $o(e="user"){return e==="project"||e==="local"?ye.join(process.cwd(),Cr,"agents"):ye.join(Ce.homedir(),Cr,"agents")}var Km=5*1024*1024,Vm=3,Mo=class{filePath;constructor(){this.filePath=yl(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
-
`;try{
|
|
4
|
-
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var
|
|
5
|
-
`);}};var
|
|
6
|
-
`));}function
|
|
7
|
-
`));}function C(e){process.stdout.write(
|
|
8
|
-
`));}function
|
|
9
|
-
`),process.stdout.write(` ${
|
|
10
|
-
`),process.stdout.write(` ${
|
|
2
|
+
import {execa}from'execa';import Mc,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import cg,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as Xr from'crypto';import {randomUUID,createHash}from'crypto';import*as ge from'fs';import ge__default,{readFileSync,mkdirSync,existsSync,realpathSync}from'fs';import*as fe from'path';import fe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as be from'os';import be__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as aa from'readline';import {createInterface}from'readline';import M from'chalk';import Pi from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Vf from'jsonwebtoken';import Zf from'ink-big-text';import Cu from'ink-spinner';import*as bt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Wg from'proper-lockfile';import sh from'extract-zip';import {simpleGit}from'simple-git';import xa from'semver';import Xa from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var Nm=Object.defineProperty;var ai=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Bm=(e,t)=>{for(var r in t)Nm(e,r,{get:t[r],enumerable:true});};function Sf(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;let n=parseInt(r[1],16),o=parseInt(r[2],16);return `${n>>8&255}.${n&255}.${o>>8&255}.${o&255}`}function $i(e){if(El.some(r=>r.test(e)))return true;let t=Sf(e);return !!(t&&El.some(r=>r.test(t)))}function xf(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function or(e,t){let r=xf(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(!o&&$i(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var El,tn=ai(()=>{"use strict";El=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\.0\.0\.0$/,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function rh(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:t})=>t.trim()||void 0).catch(()=>{})}function Ac(){return kc??=rh(),kc}var kc,$c=ai(()=>{"use strict";});var Rc={};Bm(Rc,{GitRepoAdapter:()=>cn});function Lc(e,t){if(!nh.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var nh,cn,Xi=ai(()=>{"use strict";$c();tn();nh=/^[a-zA-Z0-9_.-]+$/;cn=class{id;name;source;constructor(t,r,n){this.id=t,this.name=r,this.source=n;}buildRawUrl(t,r="marketplace.json"){let n=new URL(this.source),{hostname:o,pathname:s}=n;if($i(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Lc(a,"owner"),Lc(l,"repo"),o==="github.com"?`https://raw.githubusercontent.com/${a}/${l}/${t}/${r}`:o==="bitbucket.org"?`https://bitbucket.org/${a}/${l}/raw/${t}/${r}`:o==="gitlab.com"||o.startsWith("git.")?`https://${o}/${a}/${l}/-/raw/${t}/${r}`:`https://${o}/${a}/${l}/raw/${t}/${r}`}async fetchItems(){return this._fetchFromBranch("main").catch(t=>{if(this._is404(t))return this._fetchFromBranch("master");throw t})}async _fetchFromBranch(t){let r=await this._buildHeaders();try{let s=this.buildRawUrl(t,".claude-plugin/marketplace.json"),{plugins:i}=await Mc.get(s,{headers:r}).json();return i.map(a=>({...a,catalogId:this.id,origin:a.origin??"external"}))}catch(s){if(this._is401or403(s))throw this._authError();if(!this._is404(s))throw s}let n=this.buildRawUrl(t),{plugins:o}=await Mc.get(n,{headers:r}).json();return o.map(s=>({...s,catalogId:this.id,origin:s.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let r=await Ac();return r?{Authorization:`token ${r}`}:{}}_is404(t){return t!==null&&typeof t=="object"&&"response"in t&&t.response?.status===404}_is401or403(t){return t!==null&&typeof t=="object"&&"response"in t&&[401,403].includes(t.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(t){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});var So="FLOW",z="flow-skills",li="flow-cli",kn="internal",Wr="external",zr={skill:{label:"Skill",color:"cyan"},mcp:{label:"MCP",color:"yellow"},bundle:{label:"Bundle",color:"green"},agent:{label:"Agent",color:"green"},hook:{label:"Hook",color:"blue"}},sl={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},ci=new Set(["internal","external"]),An={user:{label:"Global",pathHint:"~/.claude/",actionLabel:"Global (~/.claude)",description:"available in all projects on this machine"},project:{label:"Project",pathHint:".claude/ (shared)",actionLabel:"Project (.claude/)",description:"shared with the team via version control"},local:{label:"Local",pathHint:".claude/ (local only)",actionLabel:"Local (.claude/)",description:"only on your machine, not committed"}},re="flow-claude-md-setup",Ve=5,Dt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;var il=new Set(["skill","mcp","bundle"]),S=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(il),origins:new Set(ci)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(il)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(ci)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var xo="aes-256-gcm",Fm=16,al=16,$n=class{key;constructor(t){if(t.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${t.length}`);this.key=t;}encrypt(t){let r=Xr.randomBytes(Fm),n=Xr.createCipheriv(xo,this.key,r,{authTagLength:al}),o=Buffer.concat([n.update(t,"utf8"),n.final()]),s=n.getAuthTag();return {iv:r.toString("hex"),authTag:s.toString("hex"),ciphertext:o.toString("hex"),algorithm:xo}}decrypt(t){if(t.algorithm!==xo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=Xr.createDecipheriv(xo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:al});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var jm=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Km=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,Vm=/[A-Za-z0-9+/]{40,}={0,2}/g;function ui(e){return e.replace(jm,"Bearer ***").replace(Km,"***").replace(Vm,"***").replace(/\r\n|\r|\n/g,"\\n")}var br=".claude",Io=".flow";function ll(e,t){return pi(z,e,t)}function di(e){return fe.join(be.homedir(),br,"plugins","marketplaces",z,"plugins","native",e)}function bo(){return fe.join(be.homedir(),br,"plugins","marketplaces",z,".claude-plugin","marketplace.json")}function vo(){return fe.join(be.homedir(),br,"plugins","known_marketplaces.json")}function cl(){return fe.join(be.homedir(),br,"plugins","marketplaces",z)}function ul(){return fe.join(be.homedir(),Io,"cache","install.lock")}function dl(){return fe.join(be.homedir(),Io,"logs","flowsetup.log")}function pi(e,t,r){return fe.join(be.homedir(),br,"plugins","cache",e,t,r)}function vr(e){let t=e==="global"?be.homedir():process.cwd();return fe.join(t,".claude","skills")}function Mn(e){let t=e==="global"?be.homedir():process.cwd();return fe.join(t,".claude","skills-lock.json")}function Po(e="user"){return e==="project"?fe.join(process.cwd(),".opencode","plugins"):fe.join(be.homedir(),".config","opencode","plugins")}function pl(){return fe.join(be.homedir(),Io,"flow-catalogs.json")}function ml(){let e=process.env.FLOW_HOME??fe.join(be.homedir(),Io);return fe.join(e,"config.json")}function Eo(e="user"){return e==="project"||e==="local"?fe.join(process.cwd(),br,"agents"):fe.join(be.homedir(),br,"agents")}var Hm=5*1024*1024,Jm=3,To=class{filePath;constructor(){this.filePath=dl(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
+
`;try{ge.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=fe.dirname(this.filePath);ge.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(ge.statSync(this.filePath).size>Hm){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);ge.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=fe.dirname(this.filePath),r=fe.basename(this.filePath,".log"),n=ge.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(Jm))ge.unlinkSync(fe.join(t,o));}catch{}}};var Co=class{context;constructor(t){this.context=t;}write(t){let r=this.context==="tui"?this.formatTui(t):this.formatCli(t);process.stderr.write(r+`
|
|
4
|
+
`);}formatTui(t){return `[flow:${t.module}] ${t.message}`}formatCli(t){let r=String(t.timestamp.getHours()).padStart(2,"0"),n=String(t.timestamp.getMinutes()).padStart(2,"0"),o=String(t.timestamp.getSeconds()).padStart(2,"0");return `[${r}:${n}:${o}] [${t.level.toUpperCase()}] ${t.message}`}};var ko=class{write(t){process.stdout.write(t.message+`
|
|
5
|
+
`);}};var Ao=[],mi=new Set;function fi(){return Ao}function fl(e){return mi.add(e),()=>{mi.delete(e);}}var $o=class{write(t){Ao.push(t),Ao.length>100&&Ao.shift();for(let r of mi)r();}};var qr={debug:0,info:1,warn:2,error:3},Er={context:"cli",transports:[],minLevel:"warn",debugModules:null};function Gm(){let e=process.env.DEBUG;if(!e)return null;let t=e.split(",").map(n=>n.trim()).filter(Boolean);for(let n of t)if(n==="flow:*")return "all";let r=new Set;for(let n of t)n.startsWith("flow:")&&r.add(n.slice(5));return r.size>0?r:null}function Re(e,t){if(e==="tui"){let r=Gm();Er={context:e,transports:[new $o,new To],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Er={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Er={context:e,transports:[new Co("cli")],minLevel:"debug",debugModules:null}:Er={context:e,transports:[new ko],minLevel:"info",debugModules:null};}function gl(){return Er.transports}function hl(e,t){let{debugModules:r,minLevel:n}=Er;return Er.context==="tui"&&r&&r!=="all"?r.has(t)?qr[e]>=qr.debug:qr[e]>=qr.warn:qr[e]>=qr[n]}var yl=new Map;function Mo(e,t,r){if(!hl(e,t))return;let n={level:e,module:t,message:ui(r),timestamp:new Date};for(let o of gl())o.write(n);}function I(e){let t=yl.get(e);if(t)return t;let r={debug:n=>Mo("debug",e,n),info:n=>Mo("info",e,n),warn:n=>Mo("warn",e,n),error:n=>Mo("error",e,n)};return yl.set(e,r),r}var gi=I("encryption"),hi="__encrypted__";function Wm(e){return typeof e=="object"&&e!==null&&hi in e&&e[hi]===true}function yi(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[hi]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return gi.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(Wm(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return gi.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return gi.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var wi=promisify(execFile),qm=promisify(exec),it=I("encryption:macos-keyvault"),Yr=class{static async isAvailable(){try{let{stdout:t}=await qm("command -v security");return it.debug(`security binary found at: ${t.trim()}`),!0}catch{return it.debug("security binary not found in PATH"),false}}async getSecret(t,r){try{it.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await wi("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return it.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return it.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{it.debug(`Storing secret: service=${t}, account=${r}`),await wi("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),it.debug("security add-generic-password succeeded");}catch(o){let s=o;throw it.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return it.debug(`Deleting secret: service=${t}, account=${r}`),await wi("security",["delete-generic-password","-a",r,"-s",t]),it.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return it.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "macOS Keychain (security)"}};function y(e){return e==null?"":e.replace(/\x1b\[[0-9;:<=>?]*[ -/]*[@-~]/g,"").replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g,"").replace(/\x1b./g,"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"")}function ne(e){process.stdout.write(M.green(` \u2713 ${y(e)}
|
|
6
|
+
`));}function E(e){process.stderr.write(M.red(` \u2717 ${y(e)}
|
|
7
|
+
`));}function C(e){process.stdout.write(M.cyan(` \u2139 ${y(e)}
|
|
8
|
+
`));}function Zr(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(c=>(c[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,c)=>l.padEnd(o[c])).join(" ");process.stdout.write(`
|
|
9
|
+
`),process.stdout.write(` ${M.bold(i(e))}
|
|
10
|
+
`),process.stdout.write(` ${M.dim(s)}
|
|
11
11
|
`);for(let a of r)process.stdout.write(` ${i(a)}
|
|
12
12
|
`);process.stdout.write(`
|
|
13
|
-
`);}function
|
|
14
|
-
`);}function
|
|
15
|
-
`);}function
|
|
16
|
-
`);}function
|
|
13
|
+
`);}function er(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
|
+
`);}function _e(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
|
+
`);}function Je(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
+
`);}function H(e){return e instanceof Error?e.message:String(e)}function St(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var Si=promisify(execFile),xi=promisify(exec),ef=[{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"}],X=I("encryption:linux-keyvault");async function tf(e,t){let r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,o=setInterval(()=>{process.stderr.write(`\r${r[n++%r.length]} ${e}`);},80);try{return await t()}finally{clearInterval(o),process.stderr.write("\r\x1B[2K");}}function rf(e){let t=aa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var tr=class e{static async isAvailable(){try{let{stdout:t}=await xi("command -v secret-tool");X.debug(`secret-tool found at: ${t.trim()}`);}catch{return X.debug("secret-tool binary not found in PATH"),false}try{return await Si("secret-tool",["lookup","service","__flow_connectivity_check__"]),X.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(X.debug(`Secret Service D-Bus not available: ${n}`),false):(X.debug("secret-tool is available and D-Bus service is reachable"),true)}}static async detectPackageManager(){for(let t of ef)try{return await xi(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return true;X.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let t=await e.detectPackageManager();if(!t)return X.warn("Could not detect a supported package manager. Please install libsecret manually."),false;let r=await rf(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return false;try{return X.info(`Running: ${t.command}`),await tf("Installing secret-tool...",()=>xi(t.command)),e.isAvailable()}catch{return X.warn("Installation failed. Falling back to derived key."),false}}async getSecret(t,r){try{X.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await Si("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return X.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return X.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){X.debug(`Storing secret: service=${t}, account=${r}`),X.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),X.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),X.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((o,s)=>{let i=spawn("secret-tool",["store","--label",t,"service",t,"account",r]),a="";i.stderr.on("data",l=>{a+=l.toString();}),i.stdin.end(n,"utf8"),i.on("close",l=>{l===0?(X.debug("secret-tool store succeeded"),o()):(X.error(`secret-tool store failed: code=${l}, stderr=${a.trim()}`),s(new Error(`secret-tool exited with code ${l}${a?`: ${a.trim()}`:""}`)));}),i.on("error",l=>{X.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return X.debug(`Deleting secret: service=${t}, account=${r}`),await Si("secret-tool",["clear","service",t,"account",r]),X.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return X.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),false}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};var sf=promisify(execFile),at=I("encryption:windows-keyvault"),Ii=1,af=1,lf=2,cf=3;function bi(e,t){return `${e}:${t}`}var vi=`
|
|
17
17
|
using System;
|
|
18
18
|
using System.Runtime.InteropServices;
|
|
19
19
|
using System.Text;
|
|
@@ -49,7 +49,7 @@ public class FlowCredManager {
|
|
|
49
49
|
|
|
50
50
|
public static string Read(string target) {
|
|
51
51
|
IntPtr credPtr;
|
|
52
|
-
if (!CredRead(target, ${
|
|
52
|
+
if (!CredRead(target, ${Ii}, 0, out credPtr)) return "";
|
|
53
53
|
try {
|
|
54
54
|
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
|
55
55
|
if (cred.CredentialBlobSize <= 0) return "";
|
|
@@ -63,7 +63,7 @@ public class FlowCredManager {
|
|
|
63
63
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
64
64
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
65
65
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
66
|
-
int[] persistLevels = new int[] { ${
|
|
66
|
+
int[] persistLevels = new int[] { ${lf}, ${cf}, ${af} };
|
|
67
67
|
int lastErr = 0;
|
|
68
68
|
try {
|
|
69
69
|
foreach (int persist in persistLevels) {
|
|
@@ -71,7 +71,7 @@ public class FlowCredManager {
|
|
|
71
71
|
try {
|
|
72
72
|
Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
|
|
73
73
|
var cred = new CREDENTIAL();
|
|
74
|
-
cred.Type = ${
|
|
74
|
+
cred.Type = ${Ii};
|
|
75
75
|
cred.TargetName = targetPtr;
|
|
76
76
|
cred.CredentialBlobSize = bytes.Length;
|
|
77
77
|
cred.CredentialBlob = blobPtr;
|
|
@@ -89,155 +89,152 @@ public class FlowCredManager {
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
public static bool Delete(string target) {
|
|
92
|
-
return CredDelete(target, ${
|
|
92
|
+
return CredDelete(target, ${Ii}, 0);
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
|
-
`;function
|
|
96
|
-
${
|
|
95
|
+
`;function Rn(e){return e.replace(/'/g,"''")}function Lo(e){return ["-NoProfile","-NonInteractive","-Command",e]}function uf(e){return `Add-Type -TypeDefinition @'
|
|
96
|
+
${vi}
|
|
97
97
|
'@
|
|
98
|
-
[FlowCredManager]::Read('${
|
|
99
|
-
${
|
|
98
|
+
[FlowCredManager]::Read('${Rn(e)}')`}function df(e,t,r){return `Add-Type -TypeDefinition @'
|
|
99
|
+
${vi}
|
|
100
100
|
'@
|
|
101
|
-
[FlowCredManager]::Write('${
|
|
102
|
-
${
|
|
101
|
+
[FlowCredManager]::Write('${Rn(e)}', '${Rn(t)}', '${Rn(r)}')`}function pf(e){return `Add-Type -TypeDefinition @'
|
|
102
|
+
${vi}
|
|
103
103
|
'@
|
|
104
|
-
[FlowCredManager]::Delete('${
|
|
105
|
-
`)[0]:"unknown error";return
|
|
106
|
-
`)[0]:"unknown error";return
|
|
107
|
-
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw
|
|
108
|
-
`)[0]:"unknown error";return
|
|
104
|
+
[FlowCredManager]::Delete('${Rn(e)}')`}async function Ro(e){return sf("powershell.exe",e)}var Qr=class{static async isAvailable(){try{let{stdout:t}=await Ro(Lo('Write-Output "ok"')),r=t.trim()==="ok";return at.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return at.debug(`PowerShell not available: ${r}`),false}}async getSecret(t,r){try{let n=bi(t,r);at.debug(`Looking up secret: target=${n}`);let o=uf(n),{stdout:s}=await Ro(Lo(o)),i=s.trim();return at.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return at.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=bi(t,r);at.debug(`Storing secret: target=${o}`);let s=df(o,n,r),{stdout:i}=await Ro(Lo(s)),a=i.trim();if(a.startsWith("OK:")){let c=a.split(":")[1];at.debug(`CredWrite succeeded (persist=${c})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
+
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw at.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=bi(t,r);at.debug(`Deleting secret: target=${n}`);let o=pf(n),{stdout:s}=await Ro(Lo(o)),i=s.trim()==="True";return at.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return at.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),false}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};var mf=32,ff="flow-plugins-cli-fallback",Ei="flow-plugins-cli-fallback",gf={linux:"install secret-tool (e.g. sudo apt install libsecret-tools)",darwin:"ensure the Keychain is accessible (security binary must be available)",win32:"ensure Credential Manager is available (cmdkey must be in PATH)"};function hf(){let e=`${be.hostname()}${be.userInfo().username}`;return Xr.scryptSync(e,ff,mf)}function yf(){let e=hf(),t=new $n(e),r=yi(t);return new Pi({projectName:Ei,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var Do=null;function _o(){return Do||(Do=yf()),Do}var De=class{warned=false;async getSecret(t,r){return _o().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=gf[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
109
109
|
using a machine-derived key. For stronger security, ${o}.
|
|
110
|
-
`),this.warned=true;}Bo().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=Bo(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return Bo().path}static hasExistingData(){try{let t=new Ai({projectName:$i});return Se.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Ai({projectName:$i});Se.rmSync(t.path,{force:!0});}catch{}Fo=null;}};async function Mi(){if(Be.hasExistingData())return new Be;switch(process.platform){case "darwin":return await Qr.isAvailable()?new Qr:new Be;case "linux":return await or.isAvailable()?new or:await or.ensureInstalled()?new or:new Be;case "win32":return await rn.isAvailable()?new rn:new Be;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var hf=x("config:credentials"),Ut="flow-plugins-cli",Li="credentials",Ri="token-cache",_i="user-info",Vo=null;async function sr(){return Vo||(Vo=Mi()),Vo}function Ho(){Vo=null;}async function ae(){let t=await(await sr()).getSecret(Ut,Li);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Bt(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw hf.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await sr()).setSecret(Ut,Li,JSON.stringify(e));}async function kl(){let e=await sr();await e.deleteSecret(Ut,Li),await e.deleteSecret(Ut,Ri),await e.deleteSecret(Ut,_i);}async function Al(){return (await sr()).getStoragePath()}async function $l(e){await(await sr()).setSecret(Ut,Ri,JSON.stringify(e));}async function Jo(){let t=await(await sr()).getSecret(Ut,Ri);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Go(e){await(await sr()).setSecret(Ut,_i,JSON.stringify(e));}async function Ml(){let t=await(await sr()).getSecret(Ut,_i);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ir(){let e=await Jo();return e?new Date(e.expiresAt)>new Date:false}function zo(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}Bn();var Oi=x("api:auth");function If(e){if(!Er.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Rl={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 bf(e){if(e instanceof HTTPError){let t=e.response.status;Oi.debug(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Rl[r]?new Error(Rl[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Oi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Oi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function $r(e){let t=nn("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");If(e.tenant);let r;try{r=await Gc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await bf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Bt(e),await $l({accessToken:r.access_token,expiresAt:n});let o=zo(r.access_token);await Go({sub:o.sub,name:o.name,email:o.email});}var _l=x("lib:tokenProvider");async function ar(){if(await ir()){let n=await Jo();if(n)return n.accessToken}_l.debug("Token expired or missing, re-authenticating...");let t=await ae();if(!t)throw new Error("Not authenticated. Run: flow auth login");Be.clearFallbackFile(),Ho(),await $r(t);let r=await Jo();if(!r)throw new Error("Authentication succeeded but token was not persisted");return _l.debug("Token refreshed successfully"),r.accessToken}Bn();var Wo=x("api:metrics");function Dl(){return nn("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Ol(e,t,r){return Gc.post(e,{json:t,headers:r})}async function Pf(e){let t=await Ml();if(t)return t;let r=zo(e),n={sub:r.sub,name:r.name,email:r.email};return await Go(n),n}async function b(e,t){let r=await ar(),n=await Pf(r),o=await ae();if(!Er.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:mi,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Ol(Dl(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Wo.debug(`Metrics event sent: ${e}`);}catch(i){throw Wo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Nl(e,t,r){try{let n=r&&Er.test(r)?r:"unknown",o={action:e,booster:mi,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Ol(Dl(),o,{FlowTenant:n}),Wo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Wo.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var I={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var Ef={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ut={...Ef};function Ul(e){let t=Date.now();ut={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Mr(e){ut.currentStep=e,ut.stepStart=Date.now();}function X(){return {...ut}}function Ft(){return ut.sessionStart===0?0:Date.now()-ut.sessionStart}function Lr(){return ut.stepStart===0?0:Date.now()-ut.stepStart}function Bl(){ut.tuiSessionStart=Date.now();}function Fl(){return ut.tuiSessionStart===0?0:Date.now()-ut.tuiSessionStart}var Cf=3e3,Tf=x("abandonment");async function Xo(e){let{currentStep:t,sessionStart:r}=X();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Ft()};try{await Promise.race([b(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Cf))]);}catch(o){Tf.warn(`Abandonment event failed: ${String(o)}`);}}function jl(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var kf=3e3,Af=x("session-end");async function jn(e,t,r){let n=Fl(),s=[b(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Xo(e));try{await jl(Promise.all(s).then(()=>{}),kf);}catch(i){Af.warn(`Session end event failed: ${String(i)}`);}}var Rf=2e3;function Vl(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),jn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Rf);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Nf=16;function Hl({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,c)=>{if(c.backspace){let u=i.current.slice(0,-1);i.current=u,r(u);}else if(l&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let u=i.current+l;i.current=u,r(u);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Nf)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}var Xe=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Rr(){return ye__default.join(Ce__default.homedir(),".claude","settings.json")}function Jn(){let e=Rr();if(!Se__default.existsSync(e))return {status:"missing"};let t=Se__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function qo(e){let t=Rr();Se__default.mkdirSync(ye__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function Gl(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function Bi(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var Kf=3600,_r=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Vf(e){return jf.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Kf})}function Yo(e,t={}){let r=Jn();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new _r;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Bi(r.settings):null,s=Vf(e),i=Gl(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function Zo(e){qo(e.merged);}function zl(){let e=Jn();return e.status!=="ok"?false:Bi(e.settings)!==null}var Wl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Wl=e.version);}catch{}var le=Wl;function Gf(){let e=Sl();if(!Se__default.existsSync(e))return {};try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return {}}}var Fi=null;function zf(){return Fi===null&&(Fi=Gf()),Fi}function lr(){return !!zf().ENABLE_EXPERIMENTAL_BETAS}function Yf(){return re.filter(e=>e.platforms[process.platform]?.status==="supported")}function ql(e){let t=Yf();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Qo={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=ye__default.join(Ce__default.homedir(),".claude","settings.json"),r=Se__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=[];if(t.push(e.customUrl?["flow-ai-obs","init","--no-interactive","--custom-url",e.customUrl]:["flow-ai-obs","init","--no-interactive"]),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push(["flow-ai-obs","auth","login","--client-id",r,"--client-secret",n,"--tenant",o]);}return t},onDemand:null,mode:"non-interactive"}},Zf={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},re=lr()?[Qo,Zf]:[Qo];var rg=x("moduleState");function ts(){let e=process.env.FLOW_HOME??ye__default.join(Ce__default.homedir(),".flow");return ye__default.join(e,"modules.json")}var ng={retries:5,minTimeout:50};async function Yl(e,t){Se__default.mkdirSync(ye__default.dirname(e),{recursive:true});let r=await tg.lock(e+".lock",{realpath:false,retries:ng});try{return await t()}finally{await r();}}function Zl(){let e=ts();if(!Se__default.existsSync(e))return [];try{let t=JSON.parse(Se__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(rg.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),Se__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return Se__default.rmSync(e,{force:true}),[]}}function Dr(){return Zl()}function Ql(e){let t=ts();Se__default.mkdirSync(ye__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Se__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function qe(e){return Dr().find(t=>t.alias===e)??null}async function dt(e){let t=ts();await Yl(t,async()=>{let r=Zl(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Ql(r);});}async function Or(){let e=ts();Se__default.existsSync(e)||await Yl(e,async()=>{Se__default.existsSync(e)||Ql([]);});}var ig=promisify(execFile);function cr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function vt(e){let t=process.platform==="win32"?"where":"which";try{return await ig(t,[e]),!0}catch{return false}}function jt(){return process.platform==="win32"?"npm.cmd":"npm"}var ec=promisify(execFile),on=class{type="npm";async isAvailable(){return vt("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=cr(t,"npm");if(!r)return null;try{let{stdout:n}=await ec(jt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=cr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await ec(jt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var rs=promisify(execFile),dg=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,ns=class{type="homebrew";async isAvailable(){return vt("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=cr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=cr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await rs("brew",["tap",o.tap]),await rs("brew",["trust",o.tap])),await rs("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await rs("brew",["list","--versions",t]),n=r.trim().match(dg);return n?n[2]:null}catch{return null}}};var sn=promisify(execFile),rc=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function nc(){let e=process.env.FLOW_HOME??ye__default.join(Ce__default.homedir(),".flow");return ye__default.join(e,"bin")}var os=class{type="curl";async isAvailable(){return vt("curl")}async install(t){let r=Date.now(),n=cr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=ye__default.join(nc(),ye__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await sn(n,["--version"]),s=o.match(rc);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=ye__default.join(Ce__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await sn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{Se__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return Se__default.chmodSync(s,448),await sn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{Se__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=nc(),i=ye__default.join(s,ye__default.basename(n.binaryName)),a=false;try{if(Se__default.mkdirSync(s,{recursive:!0}),a=!0,await sn("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return Se__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}Se__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await sn(i,["--version"]),u=c.match(rc);l=u?u[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{Se__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=ye__default.join(Ce__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await sn("curl",["-L","--fail","-o",n,r]);let o=Se__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=Se__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{Se__default.unlinkSync(n);}catch{}}}};var ve=x("moduleInstaller");function Et(e){switch(e){case "npm":return new on;case "homebrew":return new ns;case "curl":return new os}}async function Gn(e,t,r){try{await b(I.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){ve.warn(`Failed to emit install failed event: ${String(n)}`);}}async function dr(e,t,r,n){let o=Date.now(),s=e.platforms[process.platform];if(!s)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-o};if(s.status==="experimental"){ve.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let c={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Gn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(s.status!=="supported"){let c={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Gn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(!s.strategies.some(c=>c.type===r)){let c={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await Gn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}let i=Et(r),a=false;try{a=await i.isAvailable();}catch(c){ve.warn(`${r} availability check failed: ${String(c)}`);}if(!a){let c={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await Gn(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}try{await b(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,trigger:t});}catch(c){ve.warn(`Failed to emit install started event: ${String(c)}`);}let l;try{l=await i.install(e);}catch(c){let u=c instanceof Error?c.message:String(c);ve.warn(`${r} install threw: ${u}`),l={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-o};}if(l.success){await dt({alias:e.alias,name:e.name,installedVersion:l.version??null,installMethod:l.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await b(I.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:l.version??"unknown",duration_ms:l.durationMs,os:process.platform,trigger:t});}catch(d){ve.warn(`Failed to emit install completed event: ${String(d)}`);}let{pendingCmd:c,failed:u}=await hg(e,t,n);return c?{...l,pendingInteractiveSetup:c}:u?{...l,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...l,configCheckFailed:true}:l}return await Gn(e,t,l.error??{code:"UNKNOWN",message:"unknown error"}),l}async function hg(e,t,r){if(!e.postInstall)return {pendingCmd:null,failed:false};let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return {pendingCmd:null,failed:false};let o;if(typeof n=="function"){let i=await ae(),a={credentials:i?{clientId:i.clientId,clientSecret:i.clientSecret,tenant:i.tenant}:null,customUrl:r??null};try{o=n(a);}catch(l){return ve.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else o=n;if(o.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:o[0]??null,failed:false};let s=false;for(let i=0;i<o.length;i++){let a=o[i];if(a.length===0)continue;let l=spawnSync(a[0],a.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,ve.debug(`postInstall "${a.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&ve.debug(l.stderr);let c=o.slice(i+1).filter(u=>u.length>0);c.length>0&&ve.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function ss(e,t){let r=Date.now(),n=qe(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Et(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await b(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,trigger:"command"});}catch(a){ve.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);ve.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await dt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await b(I.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){ve.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await b(I.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){ve.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await b(I.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){ve.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var is=x("flowAiObsSetup");async function zn(e){try{if(!await new on().isAvailable().catch(()=>!1))return is.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let n=await dr(Qo,"onboarding","npm",e);return n.success?n.postInstallFailed||n.configCheckFailed?(is.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(is.warn(`flow-ai-obs install failed: ${n.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(t){return is.warn(`installFlowAiObs threw: ${String(t)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}var oc=x("AuthSetup");function wg(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var Ct=["clientId","clientSecret","tenant"],Sg={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function sc(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,c]=useState(false),[u,d]=useState("fields"),[m,p]=useState(null),[f,h]=useState(null),[g,w]=useState("confirm"),[v,O]=useState(""),_=useRef(""),[E,M]=useState(false),K=useRef(0),H=useRef(false),{setCredentials:ue,setJustAuthenticated:T}=Xe(),U=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),G=()=>{d("fields"),p(null),t(A=>({...A,clientSecret:""})),n("clientSecret");},B=async()=>{H.current=true;let A=U();try{await Bt(A);}catch(at){a(at instanceof Error?at.message:"Failed to persist credentials"),G(),H.current=false;return}let{clientSecret:R,...V}=A;ue(V),T(true),b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Ft(),interface:"tui"}).catch(()=>{}),await zn(f).catch(at=>oc.warn(`installFlowAiObs threw unexpectedly: ${String(at)}`)),Wn({starterKit:V.starterKit});},be=async A=>{H.current=true;let R=U();try{Zo(A),await Bt(R);}catch(Wr){a(Wr instanceof Error?Wr.message:"Failed to persist credentials"),G(),H.current=false;return}let{clientSecret:V,...at}=R;ue(at),T(true),b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Ft(),interface:"tui"}).catch(()=>{}),await zn(f).catch(Wr=>oc.warn(`installFlowAiObs threw unexpectedly: ${String(Wr)}`)),Wn({starterKit:at.starterKit});},Nt=A=>{try{return Yo(U(),{allowOverwriteMalformed:A})}catch(R){return R instanceof _r?(d("malformedConfirm"),null):(a(R instanceof Error?R.message:"Failed to read settings.json"),d("fields"),null)}};useInput((A,R)=>{if(!(l||H.current)){if(u==="preview"){R.return&&m?be(m):R.escape?B():A==="q"&&G();return}if(u==="malformedConfirm"){if(R.return){let V=Nt(true);V&&(p(V),be(V));}else R.escape&&G();return}if(u==="customUrl"){if(g==="confirm")A==="y"||A==="Y"?w("input"):(A==="n"||A==="N"||R.return)&&N(null);else if(R.escape)_.current="",O(""),w("confirm");else if(R.return){let V=_.current.trim();V.length>0&&Rn.test(V)?(M(false),N(V)):V.length>0&&M(true);}else R.backspace||R.delete?(_.current=_.current.slice(0,-1),O(_.current)):A&&!R.ctrl&&!R.meta&&(_.current=_.current+A,O(_.current),M(false));return}if(R.shift&&R.tab){let V=Ct.indexOf(r);V>0&&n(Ct[V-1]);}else if(R.tab){let V=Ct.indexOf(r);V<Ct.length-1&&n(Ct[V+1]);}else if(R.return)if(r==="tenant")$();else {let V=Ct.indexOf(r);n(Ct[V+1]);}}},{isActive:true});let $=()=>{let A={};for(let R of Ct)e[R].trim()||(A[R]="This field is required");if(Object.keys(A).length>0){s(A);let R=Ct.find(V=>A[V]);R&&n(R);return}w("confirm"),_.current="",O(""),M(false),d("customUrl");},N=async(A=f)=>{h(A),c(true),a(null),K.current+=1;try{await $r(U());let R=Nt(!1);R&&(p(R),d("preview"));}catch(R){let V=R instanceof Error?R.message:"Authentication failed";a(V),Nl(I.CLI_AUTH_FAILED,{error_code:wg(R),attempt:K.current},e.tenant.trim()).catch(()=>{}),t(at=>({...at,clientSecret:""})),d("fields");}finally{c(false);}},z=A=>R=>{t(V=>({...V,[A]:R})),o[A]&&s(V=>({...V,[A]:void 0}));};return u==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[$n," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!l&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!l&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:v}),jsx(Text,{color:"cyan",children:"\u2588"})]}),E&&jsx(Text,{color:"red",children:_n}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[$n," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:m.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),m.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[$n," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[$n," \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:Ct.map(A=>jsx(Box,{marginBottom:1,children:jsx(Hl,{label:Sg[A],value:e[A],onChange:z(A),masked:A==="clientSecret",isActive:r===A&&!l,error:o[A]})},A))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function an(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Ig,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",le]})})]})}var cc=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],Q=lr()?cc:cc.slice(0,3);function bg(e){return Q.findIndex(t=>t.id===e)}function Vi(e,t,r){let n=bg(r.activeTab);if(t.rightArrow||t.tab){let o=Q[(n+1)%Q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=Q[(n-1+Q.length)%Q.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:Q[n]?.focus??"list"}]:[]}var pc={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function mc({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Q.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${pc[r]} (${e})`:pc[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Fe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function gc(){let e=S(i=>i.focus),t=Fe(i=>i.query),r=Fe(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var Cg=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...qr[e]})),Tg=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...dl[e]}));function hc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),Cg.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),Tg.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function yc({type:e}){let{label:t,color:r}=qr[e];return jsx(Text,{color:r,children:t})}function xc({origin:e}){return e===Mn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var ls=$g.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(yc,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(xc,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",nr(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function ln({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function vc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(ln,{message:t});let n=Math.max(0,r-Math.floor(Ge/2)),o=Math.min(e.length,n+Ge);o===e.length&&(n=Math.max(0,o-Ge));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,c)=>jsx(ls,{item:l,isSelected:n+c===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Cc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function kc({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(ln,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Ge/2)),c=Math.min(n.length,l+Ge);c===n.length&&(l=Math.max(0,c-Ge));let u=n.slice(l,c),d=l,m=n.length-c;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),u.map(p=>p.kind==="header"?jsx(Cc,{label:p.label,pathHint:p.pathHint},p.key):jsx(ls,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var Ug={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Bg({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(gc,{}),jsx(hc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Ug[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(kc,{groups:n,emptyMessage:r}):jsx(vc,{items:e,emptyMessage:r})]})}function Ac({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Bg,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Kg={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 cs(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Kg[e],t?" | Ctrl+D: debug log":""]})})}function $c({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function us({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function qi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var _c=20;function ds(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*_c),s="\u2588".repeat(o)+"\u2591".repeat(_c-o),i=`${qi(e)} / ${qi(t)}`;return {bar:s,percent:n,label:i}}function ps({received:e,total:t}){let{bar:r,percent:n,label:o}=ds(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function ms({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Ye({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,c)=>{c.upArrow?a(u=>u>0?u-1:u):c.downArrow?a(u=>u<t.length-1?u+1:u):c.return?n(t[i]):c.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,c)=>jsxs(Box,{children:[jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},c))})]})}var ea=Object.entries(Ln),Uc=[...ea.map(([,e])=>e.actionLabel),"Cancel"],Bc=Object.fromEntries(ea.map(([,e])=>[e.actionLabel,e.description]));function Fc(e){let t=ea.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var nh=x("provider.registry"),oh=3e4,gs=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+oh}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&nh.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var sh={user:"global",project:"project",local:"local"};function hs(e){return e?sh[e]:"global"}var je=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},mr=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};Bn();function gt(){return Gc.create({prefix:nn("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await ar();e.headers.set("Authorization",`Bearer ${t}`);let r=await ae();r?.tenant&&Er.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var ah=x("catalog.registry"),ys=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);ah.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var gh={retries:5,minTimeout:50};async function ta(e,t){mkdirSync(dirname(e),{recursive:true});let r=await tg.lock(e+".lock",{realpath:false,retries:gh});try{return await t()}finally{await r();}}var ws=class{filePath;constructor(t){this.filePath=t??wl();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await ta(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await ta(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await ta(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var hh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Yn(e){if(!e||!hh.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var yh=/^[^@]+@[^@]+$/;function un(e){return yh.test(e)}function dn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var wh=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Sh(e){if(!wh.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 pn(e,t){let r=dn(e);Sh(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var xh=/^[\w./:@?&=+#%-]+$/;function Ss(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!xh.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var Ih=x("catalog.flow-api"),xs=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await gt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){Yn(t);try{return await gt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await gt().head("v1/plugins/catalog"),Ih.debug("ping ok"),!0}catch{return false}}};var de=new ys,Vt=new ws;de.register(new xs);var Xc=false;async function qc(){if(Xc)return;Xc=true;let e=await Vt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(ra(),Wc));for(let r of e)de.register(new t(r.id,r.name,r.source));}var Yc=2;async function fr(){return de.fetchAll()}async function Zc(){return de.fetchAllWithErrors()}async function fn(e){Yn(e);try{return await gt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function Qc(e,t){Yn(e);try{let r=await gt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),c=[],u=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(u+=m.byteLength,i&&u>s*Yc)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*Yc}`);c.push(m),i&&t?.(u,s);}return Buffer.concat(c)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function Is(){try{let{profiles:e}=await gt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function eu(e,t){let r=ye.resolve(t);await Tt.mkdir(r,{recursive:true});let n=ye.join(ye.dirname(r),`${randomUUID()}.zip`);try{await Tt.writeFile(n,e),await Ch(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=ye.resolve(r,o.fileName);if(process.platform==="win32"&&i.length>=260)throw new Error(`Path too long: "${i}" (${i.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);let a=ye.normalize(r+ye.sep);if(!i.startsWith(a)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(ye.resolve(ye.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await Tt.unlink(n);}catch{}}}async function na(e){await Tt.rm(e,{recursive:true,force:true});}async function gr(){let e=hl();await Tt.mkdir(ye.dirname(e),{recursive:true});try{await Tt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await tg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function Ah(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:Y,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function nu(){let e=To();if(!Se__default.existsSync(e))return null;try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return null}}function $h(){let e=nu();if(e)return e;let t=Ah(),r=To();return Se__default.mkdirSync(ye__default.dirname(r),{recursive:true}),oa(t),t}function oa(e){let t=To(),r=`${t}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,t);}function Mh(){let e=ko(),t={};try{Se__default.existsSync(e)&&(t=JSON.parse(Se__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[Y])return;t[Y]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:gl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,e);}function ou(e,t){ht(e.name),Mh();let r=hi(e.name);Se__default.mkdirSync(ye__default.dirname(r),{recursive:true});try{Se__default.lstatSync(r),Se__default.rmSync(r,{recursive:!0,force:!0});}catch{}Se__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=$h();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),oa(n));}function sa(e){ht(e);let t=hi(e);try{Se__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=nu();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&oa(r);}var Rh=x("mcpConfigReader"),_h=500,Dh=512;function Oh(){return ye__default.join(Ce__default.homedir(),".claude.json")}function Nh(){return ye__default.join(process.cwd(),".mcp.json")}function iu(e){if(!Se__default.existsSync(e))return null;try{return JSON.parse(Se__default.readFileSync(e,"utf-8"))}catch{return Rh.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Zn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ia(e){if(!Zn(e))return {};let t=e.mcpServers;return Zn(t)?t:{}}function aa(e,t){return Object.keys(e).slice(0,_h).map(n=>({name:y(n.slice(0,Dh)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function lu(){let e=[],t=Oh(),r=iu(t);if(Zn(r)){let a=r,l=ia(a);e.push(...aa(l,"user"));let c=process.cwd();if(Zn(a.projects)){let u=a.projects[c];if(Zn(u)){let d=ia(u);e.push(...aa(d,"local"));}}}let n=Nh(),o=iu(n),s=ia(o);e.push(...aa(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var Ze=x("storage");async function Bh(e,t,r){try{await b(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:X().interfaceType});}catch(n){Ze.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Fh(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;b(n,{tool_id:e,source:r,interface:X().interfaceType}).catch(o=>Ze.warn(`Failed to send ${t} metrics: ${String(o)}`));}function da(){return ye__default.join(Ce__default.homedir(),".claude","plugins","installed_plugins.json")}function jh(){return ye__default.join(Ce__default.homedir(),".claude","plugins")}function cu(e){let t=ye__default.resolve(e),r=ye__default.resolve(jh()),n=ye__default.resolve(ye__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+ye__default.sep)||t===r,s=t.startsWith(n+ye__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function uu(e="user"){return e==="local"?ye__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?ye__default.join(process.cwd(),".claude","settings.json"):ye__default.join(Ce__default.homedir(),".claude","settings.json")}function et(){let e=da();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 pa(){let e=da();try{let t=await Se__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Kh(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function du(e,t){try{Se__default.mkdirSync(ye__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;Se__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Se__default.renameSync(r,e);}catch(r){throw Kh(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Qe(e){du(da(),e);}function Qn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Vh(e,t){let r=ye__default.join(e,".claude-plugin"),n=ye__default.join(r,"plugin.json");if(Se__default.existsSync(n))try{return JSON.parse(Se__default.readFileSync(n,"utf-8"))}catch{return null}let o=ye__default.join(r,"marketplace.json");if(Se__default.existsSync(o))try{let s=JSON.parse(Se__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ma(e="user"){let t=uu(e);if(!Se__default.existsSync(t))return {};try{return JSON.parse(Se__default.readFileSync(t,"utf-8"))}catch{return {}}}function pu(e,t="user"){du(uu(t),e);}function Hh(e,t){let{name:r,marketplace:n}=Qn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Qn(i).name===r)[0],!o)throw Ze.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Jh(e,t){let{name:r,marketplace:n}=Qn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Qn(i).name===r)[0],o?{key:o,name:r}:null}function la(e="user"){return ma(e).enabledPlugins??{}}function ca(e,t="user"){let r=ma(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,pu(r,t);}function eo(e,t,r="user"){let n=ma(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},pu(n,r);}function Gh(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function ne(){let e=et(),t=la(),r=la("project"),n=la("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=Qn(c),p=u.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return Gh(p).map(h=>{let g=Vh(h.installPath,d),v=(o[h.scope]??t)[c];return {name:d,marketplace:m,version:h.version&&h.version!=="unknown"?h.version:void 0,installedAt:h.installedAt,installPath:h.installPath,scope:h.scope,providerId:h.providerId,type:h.type,description:g?.description,author:g?.author,status:v===false?"disabled":"enabled"}})}),i=lu(),a=new Set(s.map(c=>`${c.name}@${c.scope}`)),l=i.filter(c=>!a.has(`${c.name}@${c.scope}`));return [...s,...l]}async function to(e,t){Ze.debug(`[${e}] Acquiring lock to uninstall`);let r=await gr();try{let n=et(),o=Jh(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);Ze.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),cu(l.installPath);let c=ye__default.dirname(l.installPath);Ze.debug(`[${i}] Removing directory: ${c}`),Se__default.rmSync(c,{recursive:!0,force:!0});let u=a.filter(d=>d.scope!==t);if(u.length===0){let{[s]:d,...m}=n.plugins;Qe({...n,plugins:m}),ca(s,t),sa(i);}else n.plugins[s]=u,Qe(n),ca(s,t);}else {Ze.debug(`[${i}] Resolved key: ${s}`);for(let u of a){cu(u.installPath);let d=ye__default.dirname(u.installPath);Ze.debug(`[${i}] Removing directory: ${d}`),Se__default.rmSync(d,{recursive:!0,force:!0}),ca(s,u.scope);}sa(i);let{[s]:l,...c}=n.plugins;Qe({...n,plugins:c});}await Bh(i,a[0].origin??"internal",a[0].type??"skill"),Ze.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function ro(e,t,r){Ze.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await gr();try{let o=et(),{key:s,name:i}=Hh(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";Ze.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),eo(s,t==="enabled",l),Fh(i,t,c),Ze.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var zh=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Wh=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ht(e){if(!zh.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Xh(e){if(!Wh.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var hr=x("installer");function qh(e,t){let r=`${e}@${Y}`,o=et().plugins[r];if(o&&!t)throw new je(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Yh(e,t,r){r&&await na(t);try{hr.debug(`[${t}] Extracting archive...`),await eu(e,t);}catch(n){throw await na(t),n}}function Zh(e,t,r,n,o,s="claude-code",i){let a=et(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},c=a.plugins[e]??[];a.plugins[e]=[...c.filter(u=>u.scope!==n),l],Qe(a),eo(e,true,n);}async function Qh(e,t,r,n,o,s){try{await b(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:X().interfaceType});}catch(i){hr.warn(`Failed to send install metrics: ${String(i)}`);}}async function ey(e,t,r,n){try{await b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:X().interfaceType});}catch(o){hr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function $e(e,t={}){let r=Date.now(),n=null;try{hr.debug(`[${e}] Acquiring lock...`),n=await gr();let{pluginKey:o,alreadyInstalled:s}=qh(e,t.force);hr.debug(`[${e}] Fetching manifest...`);let i=await fn(e);ht(i.name),Xh(i.version),hr.debug(`[${e}] Downloading archive...`);let a=await Qc(e,t.onDownloadProgress),l=t.scope??"user",c=t.type??"skill",u=fl(i.name,i.version);await Yh(a,u,!!s&&!!t.force),Zh(o,u,i.version,l,"internal",t.providerId,c),ou(i,u);let d=Date.now()-r;hr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:u,duration_ms:d};return t.skipMetrics||await Qh(i.name,i.version,d,hs(l),"internal",c),m}catch(o){throw await ey(e,o,"internal",t.type??"skill"),hr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var ty=x("commands:helpers");async function we(){if(!await ae())return P("Not authenticated. Run: flow auth login"),false;try{await ar();}catch(t){return ty.debug(`Token validation failed: ${String(t)}`),P("Session expired. Run: flow auth login"),false}return true}async function kt(e){let t=fa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function mu(e){let t=fa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var gn=x("claudeProxy"),Sa="claude ",fu="flow ",ga=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ha=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},ry=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,ny=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,oy=/^(flow|claude)\s+auth\s+login(\s|$)/,gu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function hu(e){return gu.test(e.trim())}function sy(e){return gu.exec(e.trim())?.[2]??""}async function yu(e){let t=sy(e),r=Date.now();gn.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw xa(n)?new ya:n}}function iy(e){wu(e);let t=e.slice(Sa.length);if(!ry.test(t))throw new ha(e)}var bs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},ya=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function wu(e){if(!e||!/^claude /.test(e))throw new ga(e)}async function Pe(e){wu(e);let t=e.slice(Sa.length).split(/\s+/).filter(Boolean),r=ay(t);gn.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return gn.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw xa(o)?new bs:o}}function ay(e){return e.length>=3?e[2]:e.join(" ")}function xa(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function ly(e){return e.startsWith(fu)?Sa+e.slice(fu.length):e}function cy(e){return ny.test(e)||oy.test(e)}function uy(e){let t=0;for(;t<e.length&&cy(e[t]);)t++;return e.slice(t)}var dy=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function py(e,t){return !t||e.includes("--scope")||!dy.test(e)?e:`${e} --scope ${t}`}async function no(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=uy(r).map(i=>ly(i)).map(i=>py(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)iy(i);gn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Pe(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Pe(o[i]),s.exitCode!==0)return s;return s}async function vs(e,t,r){let n=dn(e),o=t?.trim();if(!o&&(o=(await mu(`Plugin "${n}" could not be installed.
|
|
111
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=Ss(o),r?.(),gn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);gn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw xa(s)?new bs:s}}var yy=6e4,yr=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function At(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:yy}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm$1(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new yr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new yr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new yr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function $t(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function Kr(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function Sy(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function xy(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Iy(e){return typeof e=="object"&&e!==null&&e.source==="github"}function hn(e,t){let r=e.source;if(Sy(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(xy(r))return {cloneUrl:r.url,subPath:"."};if(Iy(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function tt(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Mt=x("claude-code.adapter");function Py(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=ko();if(!Se__default.existsSync(s))return r;try{let i=JSON.parse(Se__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Eu(e,t){let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=hn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=Py(e.catalogId,r?.source),i=t.scope??"user",a;o?a=yi(s,e.name,"external"):a=join(Tr(i==="user"?"global":"project"),e.name);let l=null;try{ht(e.name),l=await At(n.cloneUrl,n.ref);let c=n.subPath==="."?l:join(l,n.subPath);if(Se__default.existsSync(a)&&Se__default.rmSync(a,{recursive:!0,force:!0}),Se__default.mkdirSync(dirname(a),{recursive:!0}),Se__default.cpSync(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await pa(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[u]??[];d.plugins[u]=[...p.filter(f=>f.scope!==i),m],Qe(d),eo(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return Mt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await $t(l).catch(()=>{});}}async function Ia(e,t,r,n){try{await b(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:hs(n),version:"unknown",duration_ms:t,interface:X().interfaceType});}catch(o){Mt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function vu(e,t,r){try{await b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:X().interfaceType});}catch(n){Mt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Ey={async install(e,t){if(e.origin===Xr&&!e.installCommand&&!un(e.name))return Eu(e,t);if(e.origin===Xr&&e.installCommand){let r=e.type??"skill",n=await no(e.installCommand,t.scope);return n.exitCode===0?(await Ia(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await vu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(un(e.name)){let r=e.type??"skill",n=pn(e.name,t.scope);Mt.debug(`[${e.name}] Attempting install: ${n}`);let o=await Pe(n);if(o.exitCode===0)return await Ia(e.name,o.duration_ms,r,t.scope),{success:true};Mt.debug(`[${e.name}] First attempt failed, adding marketplace`),await vs(e.name,t.marketplaceSource,()=>{});let s=await Pe(n);return s.exitCode===0?(await Ia(e.name,s.duration_ms,r,t.scope),{success:true}):(await vu(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await $e(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Mt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await to(e,t);},getInstallPath(e,t){return ""}};function Pu(e){return {async install(t,r){if(t.origin===Xr&&!t.installCommand&&!un(t.name))return Eu(t,r);if(!t.installCommand)try{let o=await $e(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Mt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Mt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await no(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=et(),o=`${t}@${Y}`;if(n.plugins[o]){await to(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function Cy(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!Se__default.existsSync(t))continue;let r=Se__default.readdirSync(t).filter(n=>n.endsWith(".md")&&Se__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function ba(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ba(r)]))}function Cu(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(ba(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(ba(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Cu(s,o):r[n]=o;}return r}async function Tu(e,t,r,n){let o=await pa(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],Qe(o);}var Ty={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=hn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ht(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=Cy(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=$o(r);Se__default.mkdirSync(l,{recursive:!0});let c=tt(e.name);if(a.length===1)Se__default.copyFileSync(a[0],join(l,`${c}.md`));else for(let d of a){let m=tt(basename(d,".md"));Se__default.copyFileSync(d,join(l,`${c}--${m}.md`));}let u=a.length===1?join(l,`${c}.md`):l;return await Tu(e.name,r,u,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Mt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await $t(s).catch(()=>{});}},async uninstall(e,t){let r=$o(t),n=tt(e);if(Se__default.existsSync(r))for(let a of Se__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))Se__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=et(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Qe({...s,plugins:l});}else Qe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join($o(t),`${tt(e)}.md`)}},ky={async install(e,t){let r=t.scope??"user",n=e.catalogId?de.getAdapter(e.catalogId):void 0,o=hn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ht(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!Se__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(Se__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let c=l.hooks;if(!c||typeof c!="object"||Array.isArray(c))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let u=Jn();if(u.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=u.status==="ok"?u.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Cu(m,c);return qo({...d,hooks:p}),await Tu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Mt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await $t(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Ps=class{id="claude-code";name="Claude Code";async isAvailable(){return Kr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Ey,skill:Pu("skill"),mcp:Pu("mcp"),agent:Ty,hook:ky}};function Es(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var $y=new Set(["gh"]),My=Es($y,"use: gh copilot mcp remove <name>"),Cs=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Kr("gh",["--version"])?Kr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:My}};var Ly=new Set(["opencode"]),Ry=Es(Ly,"use: opencode config remove mcp <name>");function _y(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
-
`)}function ku(){return {async install(e,t){try{ht(e.name);}catch{return {success:false,message:`Invalid plugin name: "${e.name}".`}}let r=e.catalogId?de.getAdapter(e.catalogId):void 0,n=hn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await At(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Ao(t.scope??"user"),a=join(s,".opencode","plugins");if(Se__default.existsSync(a)){let l=Se__default.readdirSync(a).filter(c=>c.endsWith(".js")||c.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};Se__default.mkdirSync(i,{recursive:!0}),Se__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);Se__default.existsSync(l)&&Se__default.rmSync(l,{recursive:!0,force:!0}),Se__default.mkdirSync(l,{recursive:!0}),Se__default.cpSync(s,l,{recursive:!0}),Se__default.mkdirSync(i,{recursive:!0}),Se__default.writeFileSync(join(i,`${e.name}.js`),_y(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await $t(o).catch(()=>{});}},async uninstall(e,t){ht(e);let r=Ao(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);Se__default.existsSync(n)&&Se__default.rmSync(n,{force:true}),Se__default.existsSync(o)&&Se__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Ao(t),`${e}.js`)}}}var Ts=class{id="opencode";name="OpenCode";async isAvailable(){return Kr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:Ry,skill:ku(),bundle:ku()}};var Lt=new gs;Lt.register(new Ps);lr()&&(Lt.register(new Cs),Lt.register(new Ts));function Au({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,c]=useState([]),[u,d]=useState(void 0);useEffect(()=>{Lt.getAvailableProviders(t??"bundle").then(c).catch(()=>{});},[t]);let m=useCallback(g=>{g==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(g=>{if(g==="Cancel"){a(false);return}let w=l.find(v=>v.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Fc(g);w?r(w,u):s(false);},[r,u]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(Ye,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(Ye,{itemName:`${e} \u2014 Choose scope`,actions:Uc,descriptions:Bc,onAction:f,onClose:h},"scope"):jsx(Ye,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function Mu({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),c=(t?.artifact.artifacts??[]).filter(f=>f.available),u=t!==void 0&&c.length===0,d=useMemo(()=>u?["Cancel"]:["Confirm Install","Cancel"],[u]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,h)=>{h.upArrow?a(g=>Math.max(0,g-1)):h.downArrow?a(g=>Math.min(d.length-1,g+1)):h.return?d[i]==="Confirm Install"?n():o():h.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[c.length," artifact",c.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:c.map(f=>{let h=y(f.name??f.flowId),g=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:h}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,h)=>jsx(Box,{children:jsxs(Text,{bold:h===i,color:h===i?"cyan":void 0,children:[h===i?"\u203A ":" ",f]})},f))})]}):jsx(Ye,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function $s({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function _u({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=$s({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(c)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(Ye,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?u():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function Nu({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=$s({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(Ye,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var Sn=x("bundle:installer"),Uu=/already exists/i;async function Ky(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(hu(t)){let r=await yu(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Uu.test(n))return;throw new Error(n)}}else {let r=await no(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Uu.test(n))return;throw new Error(n)}}}async function Vy(e,t){try{await b(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Sn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Hy(e,t,r){try{await b(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Sn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Bu(e,t,r,n){try{await b(I.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Sn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function Jy(e,t,r,n,o){try{await b(I.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Sn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function Rs(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await Vy(i,o.length);let l=[],c=0,u=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){Sn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await Bu(i,h,g,"unknown artifact type"),r?.({index:p+1,total:u,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Ky(f),c++,await Hy(i,h,g),r?.({index:p+1,total:u,artifact:f,success:!0});}catch(w){let v=w instanceof Error?w.message:String(w);Sn.error(`Failed to install artifact "${h}": ${v}`),l.push({name:h,type:g,reason:v}),await Bu(i,h,g,v),r?.({index:p+1,total:u,artifact:f,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await Jy(i,c,m,s,d),{bundleTitle:e.title,total:n.length,installed:c,skipped:s,failed:m,failures:l}}function Vu({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,Rs(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",c=e.artifact.artifacts,u=c.filter(d=>d.available);s({bundleTitle:e.title,total:c.length,installed:0,skipped:c.length-u.length,failed:u.length,failures:u.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var pe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ne()})}));function Hu({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,c=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),c&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",nr(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function Ju({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:c,stored:u}=e,d=c.removable!==false,m=u?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",u?.lastUpdated?` \xB7 Updated ${nr(u.lastUpdated)}`:""]})}),u&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((h,g)=>{let w=g===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:h.danger?"yellow":void 0,dimColor:!w,children:h.label})]},h.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Gu(e){return e.adapter.removable!==false?4:2}function zu({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((c,u)=>{if(u.escape){n();return}if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(i.length-1,d+1));return}u.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((c,u)=>jsxs(Box,{children:[jsx(Text,{color:u===a?"cyan":void 0,children:u===a?"\u203A ":" "}),jsx(Text,{bold:u===a,color:c.danger?"yellow":void 0,dimColor:u!==a,children:c.label})]},c.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Xu({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function qu({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(E=>r.has(`${E.name}@${o}`)),i=t.filter(E=>!r.has(`${E.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((E,M)=>{if(M.escape){n();return}if(M.return){d(a[l]??null);return}if(M.upArrow){c(K=>Math.max(0,K-1));return}M.downArrow&&c(K=>Math.min(a.length-1,K+1));},{isActive:u===null}),u!==null)return jsx(zu,{item:u,adapterName:e.adapter.name,isInstalled:r.has(`${u.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Ge/2)),p=Math.min(a.length,m+Ge);p===a.length&&(m=Math.max(0,p-Ge));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,v=p>s.length,O=f.filter(E=>r.has(`${E.name}@${o}`)),_=f.filter(E=>!r.has(`${E.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:h>0?`\u2191 ${h} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),O.map(E=>jsx(Xu,{item:E,isSelected:a.indexOf(E)===l,isInstalled:true},E.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),_.map(E=>jsx(Xu,{item:E,isSelected:a.indexOf(E)===l,isInstalled:false},E.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2193 ${g} more below`:" "})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: details \xB7 Esc: back"})})]})}ra();var Zy=/^https?:\/\/.+/;function Qy(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function ew(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function ed(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[c,u]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),u(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!Zy.test(g)){u("URL must start with http:// or https://");return}u(null),o("adding");let v=randomUUID(),O=new mn(v,w,g);try{await O.fetchItems(),await Vt.add({id:v,name:w,source:g}),de.register(new mn(v,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(_){let E=Qy(_)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":ew(_)?_.message:_ instanceof Error?`Could not reach catalog URL: ${_.message}`:"Failed to validate catalog URL";t(E,"error"),o("add-url");}},[e,t,r]);return useInput((g,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}g&&!w.ctrl&&!w.meta&&(d.current=d.current+g,i(d.current));},{isActive:n==="add-name"}),useInput((g,w)=>{if(w.escape){o("add-name");return}if(w.return){h();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function td(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Vt.remove(o),de.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function nd(){let e=S($=>$.focus),t=S($=>$.setFocus),r=S($=>$.showNotification),n=pe($=>$.installedItems),[o,s]=useState(()=>de.listAdapters().map($=>({adapter:$,stored:null}))),[i,a]=useState(0),[l,c]=useState("list"),[u,d]=useState(0),[m,p]=useState(null),[f,h]=useState("main"),g=useRef(o);useEffect(()=>{g.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&h("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let $=de.listAdapters(),N=await Vt.read(),z=new Map(N.map(A=>[A.id,A]));s($.map(A=>({adapter:A,stored:z.get(A.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let $=g.current[i-1];if(!$)return;let N=false;return p({items:[],loading:true,error:null}),$.adapter.fetchItems().then(z=>{N||p({items:z,loading:false,error:null});}).catch(z=>{N||p({items:[],loading:false,error:z instanceof Error?z.message:"Failed to load catalog"});}),()=>{N=true;}},[i]);let v=ed(w),O=useCallback(()=>{w(),a(0),c("list"),p(null),h("main");},[w]),{handleRemove:_}=td(O),E=useCallback(async $=>{h("removing"),await _($);},[_]),M=useCallback(async $=>{try{let N=await $.adapter.fetchItems();if(p({items:N,loading:!1,error:null}),$.stored){let z=new Date().toISOString();await Vt.updateField($.stored.id,{lastUpdated:z}),w();}r("Marketplace updated","success");}catch(N){r(N instanceof Error?N.message:"Update failed","error");}},[w,r]),K=useCallback(async $=>{if(!$.stored)return;let N=$.stored.autoUpdate!==false;await Vt.updateField($.stored.id,{autoUpdate:!N}),w();},[w]),H=useCallback(()=>h("browse"),[]),ue=useCallback($=>{let N=o[i-1];if(!N)return;let z=N.adapter.removable!==false;[H,()=>{M(N);},...z?[()=>{K(N);},()=>{E(N.adapter.id);}]:[]][$]?.();},[o,i,H,M,K,E]),T=useCallback(()=>h("main"),[]),U=useCallback(()=>{let $=o[i-1];$&&M($);},[o,i,M]),G=useCallback(()=>{let $=o[i-1];$&&K($);},[o,i,K]),B=useCallback(()=>{let $=o[i-1];$&&E($.adapter.id);},[o,i,E]);if(useInput(($,N)=>{if(N.upArrow){a(z=>Math.max(0,z-1));return}if(N.downArrow){a(z=>Math.min(o.length,z+1));return}(N.return||N.tab)&&(i===0?v.startAdd():(c("detail"),d(0)));},{isActive:f==="main"&&v.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput(($,N)=>{if(N.escape||N.tab){c("list");return}if(N.upArrow){d(z=>Math.max(0,z-1));return}if(N.downArrow){let z=o[i-1],A=z?Gu(z)-1:0;d(R=>Math.min(R+1,A));return}N.return&&ue(u);},{isActive:f==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(v.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let $=o[i-1];if(!$)return jsx(Box,{});let N=$.adapter.id??"default",z=new Set(n.filter(A=>A.marketplace===$.adapter.name).map(A=>`${A.name}@${N}`));return jsx(qu,{entry:$,items:m?.items??[],installedKeys:z,onBack:T})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let be=o[i-1]??null,Nt=be?n.filter($=>$.marketplace===be.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Hu,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&be?jsx(Ju,{entry:be,detailData:m,installedCount:Nt,focusPanel:l,actionIndex:u,onBrowse:H,onUpdate:U,onToggleAutoUpdate:G,onRemove:B}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:be?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function od(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=Q.findIndex(i=>i.id===r.activeTab),s=Q[(o-1+Q.length)%Q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=Q.findIndex(i=>i.id===r.activeTab),s=Q[(o+1)%Q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=Q.findIndex(i=>i.id===r.activeTab),s=Q[(o+1)%Q.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function sd(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function id(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var sw=new Set(Q.filter(e=>e.focus!=="list").map(e=>e.focus));function fo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:c}=Fe.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function ad({listLength:e}){let t=S(h=>h.focus),r=S(h=>h.selectedIndex),n=S(h=>h.actionMenuOpen),o=S(h=>h.setFocus),s=S(h=>h.setActionMenuOpen),i=Fe(h=>h.query),a=Fe(h=>h.setQuery),l=Fe(h=>h.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Fe.getState();g(h.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();fo(Vi(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();fo(Vi("",g,{activeTab:w}));},{isActive:sw.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:O}=S.getState();fo(od(h,g,{activeTab:w,selectedIndex:v},c.current));},{isActive:t==="list"}),useInput((h,g)=>{fo(sd(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=id(h,g,Fe.getState().query),v=w.queryUpdate;if(fo(w.actions),v==="reset")l(),d("");else if(v!==null){let{query:O,cursorPosition:_,setCursorPosition:E}=Fe.getState();if("backspace"in v)_>0&&(a(O.slice(0,_-1)+O.slice(_)),E(_-1));else if("append"in v)a(O.slice(0,_)+v.append+O.slice(_)),E(_+v.append.length);else if("cursorMove"in v){let M=_+v.cursorMove;M>=0&&M<=O.length&&E(M);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(h=>{let{setSelectedIndex:g,selectedIndex:w}=S.getState();h===0?g(0):w>=h&&g(h-1);},[]),f=useCallback(h=>{if(!u)return c.current=h.length,h;let g=u.toLowerCase(),w=h.filter(v=>v.name.toLowerCase().includes(g)||v.description?.toLowerCase().includes(g));return c.current=w.length,w},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function cd(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Xe(a=>a.justAuthenticated),o=Xe(a=>a.credentials),s=Xe(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Re(e,t,r=false){return r?true:!Ta.valid(e)||!Ta.valid(t)?false:Ta.gt(t,e)}var Gt=x("updater");async function iw(e,t,r,n,o,s){try{await b(I.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:X().interfaceType});}catch(i){Gt.warn(`Failed to send update metrics: ${String(i)}`);}}function aw(e){let t=et(),r=`${e}@${Y}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ns(e,t={}){let r=Date.now(),n=null;try{Gt.debug(`[${e}] Acquiring lock...`),n=await gr();let o=aw(e);if(!o)throw Gt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Gt.debug(`[${e}] Fetching manifest...`);let c=(await fn(e)).version;if(!i||!Re(i,c,t.force))throw Gt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new mr(e,i??"unknown");Gt.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await $e(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await iw(u.name,i,u.version,d,s.origin??"internal",s.type??"skill"),Gt.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){Gt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await gr();let d=et(),m=`${e}@${Y}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Qe(d),Gt.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var Us=x("dispatcher");async function lw(e,t,r,n,o){let s=dn(e);return Us.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await vs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Us.debug(`[${e}] Retrying install after marketplace add`),Pe(t)}async function ud(e,t,r,n){let o=pn(e,n),s=dn(e);r?.onStatus?.(`Installing ${s}...`),Us.debug(`[${e}] Attempting install: ${o}`);let i=await Pe(o);if(i.exitCode===0)return i;Us.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return lw(e,o,a,t,r)}async function dd(e,t,r){let n=e.type??"bundle",o=await Lt.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function pd(){let e=pe(i=>i.installedItems),t=pe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await dd(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=ne().find(p=>p.name===i),c=l?.providerId??"claude-code",u=Lt.getAdapter(c);if(!u)throw new Error(`Provider "${c}" not found`);let d=l?.type??"bundle",m=u.installers[d];if(!m)throw new Error(`Provider "${c}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let c=e.find(u=>u.name===i)?.status==="enabled"?"disabled":"enabled";await ro(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Ns(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var Fs=x("mcp");function go(e,t){e.silent?We({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):P(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function fd(e,t){e.silent?Ue({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ie(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function cw(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function ka(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function gd(e,t,r){if(!await we())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return go(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Fs.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=cw(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await kt(`Install external MCP "${s}"?
|
|
110
|
+
`),this.warned=true;}_o().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=_o(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return _o().path}static hasExistingData(){try{let t=new Pi({projectName:Ei});return ge.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Pi({projectName:Ei});ge.rmSync(t.path,{force:!0});}catch{}Do=null;}};async function Ti(){if(De.hasExistingData())return new De;switch(process.platform){case "darwin":return await Yr.isAvailable()?new Yr:new De;case "linux":return await tr.isAvailable()?new tr:await tr.ensureInstalled()?new tr:new De;case "win32":return await Qr.isAvailable()?new Qr:new De;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var wf=I("config:credentials"),Ot="flow-plugins-cli",Ci="credentials",ki="token-cache",Ai="user-info",Bo=null;async function rr(){return Bo||(Bo=Ti()),Bo}function Uo(){Bo=null;}async function q(){let t=await(await rr()).getSecret(Ot,Ci);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function Nt(e){let{clientId:t,clientSecret:r,tenant:n}=e,o=[!t?.trim()&&"clientId",!r?.trim()&&"clientSecret",!n?.trim()&&"tenant"].filter(Boolean);if(o.length>0)throw wf.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await rr()).setSecret(Ot,Ci,JSON.stringify(e));}async function bl(){let e=await rr();await e.deleteSecret(Ot,Ci),await e.deleteSecret(Ot,ki),await e.deleteSecret(Ot,Ai);}async function vl(){return (await rr()).getStoragePath()}async function Pl(e){await(await rr()).setSecret(Ot,ki,JSON.stringify(e));}async function Fo(){let t=await(await rr()).getSecret(Ot,ki);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function jo(e){await(await rr()).setSecret(Ot,Ai,JSON.stringify(e));}async function Ko(){let t=await(await rr()).getSecret(Ot,Ai);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function nr(){let e=await Fo();return e?new Date(e.expiresAt)>new Date:false}function en(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}tn();var Mi=I("api:auth");function vf(e){if(!Dt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Tl={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 Pf(e){if(e instanceof HTTPError){let t=e.response.status;Mi.error(`HTTP error during authentication [status=${t}]`);let r="";try{let n=await e.response.text(),o=JSON.parse(n);typeof o.error=="string"&&(r=o.error);}catch{}return r&&Tl[r]?new Error(Tl[r]):t===StatusCodes.UNAUTHORIZED||t===StatusCodes.FORBIDDEN||t===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):t>=StatusCodes.BAD_REQUEST&&t<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Mi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Mi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Tr(e){let t=or("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");vf(e.tenant);let r;try{r=await Mc.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Pf(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await Nt(e),await Pl({accessToken:r.access_token,expiresAt:n});let o=en(r.access_token);await jo({sub:o.sub,name:o.name,email:o.email});}var Cl=I("lib:tokenProvider");async function xt(){if(await nr()){let n=await Fo();if(n)return n.accessToken}Cl.debug("Token expired or missing, re-authenticating...");let t=await q();if(!t)throw new Error("Not authenticated. Run: flow auth login");De.clearFallbackFile(),Uo(),await Tr(t);let r=await Fo();if(!r)throw new Error("Authentication succeeded but token was not persisted");return Cl.debug("Token refreshed successfully"),r.accessToken}tn();var Vo=I("api:metrics");function kl(){return or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Al(e,t,r){return Mc.post(e,{json:t,headers:r})}async function Tf(e){let t=await Ko();if(t)return t;let r=en(e),n={sub:r.sub,name:r.name,email:r.email};return await jo(n),n}async function P(e,t){let r=await xt(),n=await Tf(r),o=await q();if(!Dt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:li,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Al(kl(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),Vo.debug(`Metrics event sent: ${e}`);}catch(i){throw Vo.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function $l(e,t,r){try{let n=r&&Dt.test(r)?r:"unknown",o={action:e,booster:li,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Al(kl(),o,{FlowTenant:n}),Vo.debug(`Anonymous metrics event sent: ${e}`);}catch(n){Vo.warn(`Failed to send anonymous metrics event "${e}": ${String(n)}`);}}var b={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED"};var Cf={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},lt={...Cf};function Ml(e){let t=Date.now();lt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Cr(e){lt.currentStep=e,lt.stepStart=Date.now();}function J(){return {...lt}}function Bt(){return lt.sessionStart===0?0:Date.now()-lt.sessionStart}function kr(){return lt.stepStart===0?0:Date.now()-lt.stepStart}function Ll(){lt.tuiSessionStart=Date.now();}function Rl(){return lt.tuiSessionStart===0?0:Date.now()-lt.tuiSessionStart}var kf=3e3,Af=I("abandonment");async function Ho(e){let{currentStep:t,sessionStart:r}=J();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:Bt()};try{await Promise.race([P(b.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),kf))]);}catch(o){Af.warn(`Abandonment event failed: ${String(o)}`);}}function _l(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var $f=3e3,Mf=I("session-end");async function Dn(e,t,r){let n=Rl(),s=[P(b.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Ho(e));try{await _l(Promise.all(s).then(()=>{}),$f);}catch(i){Mf.warn(`Session end event failed: ${String(i)}`);}}var Df=2e3;function Ol(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),Dn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Df);},[e,o,s,i]);return useInput((l,c)=>{c.ctrl&&l==="c"&&a();}),{pendingExit:n}}var Uf=16;function Nl({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,c)=>{if(c.backspace){let u=i.current.slice(0,-1);i.current=u,r(u);}else if(l&&!c.ctrl&&!c.meta&&!c.escape&&!c.return&&!c.tab&&!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow){let u=i.current+l;i.current=u,r(u);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(Uf)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}var Ge=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Ar(){return fe__default.join(be__default.homedir(),".claude","settings.json")}function Un(){let e=Ar();if(!ge__default.existsSync(e))return {status:"missing"};let t=ge__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function Jo(e){let t=Ar();ge__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ge__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ge__default.renameSync(r,t);}function Ul(e,t){let r=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...r,ANTHROPIC_AUTH_TOKEN:t}}}function _i(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}var Hf=3600,$r=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function Jf(e){return Vf.sign({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Hf})}function Go(e,t={}){let r=Un();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new $r;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?_i(r.settings):null,s=Jf(e),i=Ul(n,s);return {jwt:s,merged:i,previousToken:o,hadExistingFile:r.status!=="missing"}}function Wo(e){Jo(e.merged);}function Fl(){let e=Un();return e.status!=="ok"?false:_i(e.settings)!==null}var jl="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(jl=e.version);}catch{}var oe=jl;function Xf(e){if(!(e instanceof Error))return "unknown";let t=e.message.toLowerCase();return t.includes("401")||t.includes("unauthorized")?"invalid_credentials":t.includes("403")||t.includes("forbidden")?"forbidden":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("network")||t.includes("econnrefused")||t.includes("fetch")?"network_error":"unknown"}var It=["clientId","clientSecret","tenant"],qf={clientId:"Client ID",clientSecret:"Client Secret",tenant:"Tenant"};function Vl(){let[e,t]=useState({clientId:"",clientSecret:"",tenant:""}),[r,n]=useState("clientId"),[o,s]=useState({}),[i,a]=useState(null),[l,c]=useState(false),[u,d]=useState("fields"),[m,p]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:h,setJustAuthenticated:w}=Ge(),v=()=>({clientId:e.clientId.trim(),clientSecret:e.clientSecret.trim(),tenant:e.tenant.trim()}),D=()=>{d("fields"),p(null),t(R=>({...R,clientSecret:""})),n("clientSecret");},U=async()=>{g.current=true;let R=v();try{await Nt(R);}catch(j){a(j instanceof Error?j.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:x,...k}=R;h(k),w(true),P(b.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Bt(),interface:"tui"}).catch(()=>{}),Fn({starterKit:k.starterKit});},T=async R=>{g.current=true;let x=v();try{Wo(R),await Nt(x);}catch(O){a(O instanceof Error?O.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:k,...j}=x;h(j),w(true),P(b.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Bt(),interface:"tui"}).catch(()=>{}),Fn({starterKit:j.starterKit});},L=R=>{try{return Go(v(),{allowOverwriteMalformed:R})}catch(x){return x instanceof $r?(d("malformedConfirm"),null):(a(x instanceof Error?x.message:"Failed to read settings.json"),d("fields"),null)}};useInput((R,x)=>{if(!(l||g.current)){if(u==="preview"){x.return&&m?T(m):x.escape?U():R==="q"&&D();return}if(u==="malformedConfirm"){if(x.return){let k=L(true);k&&(p(k),T(k));}else x.escape&&D();return}if(x.shift&&x.tab){let k=It.indexOf(r);k>0&&n(It[k-1]);}else if(x.tab){let k=It.indexOf(r);k<It.length-1&&n(It[k+1]);}else if(x.return)if(r==="tenant")F();else {let k=It.indexOf(r);n(It[k+1]);}}},{isActive:true});let F=async()=>{let R={};for(let x of It)e[x].trim()||(R[x]="This field is required");if(Object.keys(R).length>0){s(R);let x=It.find(k=>R[k]);x&&n(x);return}c(true),a(null),f.current+=1;try{await Tr(v());let x=L(!1);x&&(p(x),d("preview"));}catch(x){let k=x instanceof Error?x.message:"Authentication failed";a(k),$l(b.CLI_AUTH_FAILED,{error_code:Xf(x),attempt:f.current},e.tenant.trim()).catch(()=>{}),t(j=>({...j,clientSecret:""}));}finally{c(false);}},V=R=>x=>{t(k=>({...k,[R]:x})),o[R]&&s(k=>({...k,[R]:void 0}));};return u==="preview"&&m?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[So," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:m.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),m.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]}):u==="malformedConfirm"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[So," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[So," \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:It.map(R=>jsx(Box,{marginBottom:1,children:jsx(Nl,{label:qf[R],value:e[R],onChange:V(R),masked:R==="clientSecret",isActive:r===R&&!l,error:o[R]})},R))}),l&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),i&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(i)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Tab next field \xB7 Enter confirm"})})]})}function rn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Zf,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",oe]})})]})}function Qf(){let e=ml();if(!ge__default.existsSync(e))return {};try{return JSON.parse(ge__default.readFileSync(e,"utf-8"))}catch{return {}}}var Di=null;function eg(){return Di===null&&(Di=Qf()),Di}function sr(){return !!eg().ENABLE_EXPERIMENTAL_BETAS}var zl=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],Y=sr()?zl:zl.slice(0,3);function tg(e){return Y.findIndex(t=>t.id===e)}function Oi(e,t,r){let n=tg(r.activeTab);if(t.rightArrow||t.tab){let o=Y[(n+1)%Y.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=Y[(n-1+Y.length)%Y.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:Y[n]?.focus??"list"}]:[]}var Yl={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Zl({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:Y.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${Yl[r]} (${e})`:Yl[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Oe=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function ec(){let e=S(i=>i.focus),t=Oe(i=>i.query),r=Oe(i=>i.cursorPosition),n=e==="search",o=t.slice(0,r),s=t.slice(r);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:n?"cyan":"gray",children:"\u{1F50D} "}),n?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:o}),jsx(Text,{inverse:true,children:s[0]??" "}),jsx(Text,{color:"white",children:s.slice(1)})]}):jsx(Text,{dimColor:true,children:t||"Search..."})]})}var sg=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...zr[e]})),ig=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...sl[e]}));function tc(){let e=S(n=>n.catalogFilters),t=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),r=e.origins.has("internal")&&e.origins.has("external");return jsxs(Box,{paddingX:1,paddingBottom:1,gap:1,children:[jsx(Text,{bold:true,children:"Type:"}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[1] "}),jsxs(Text,{color:t?"green":void 0,dimColor:!t,children:[t?"\u25C9":"\u25CB"," All"]})]}),sg.map(n=>{let o=!t&&e.types.has(n.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:r?"green":void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," All"]})]}),ig.map(n=>{let o=!r&&e.origins.has(n.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",n.key,"] "]}),jsxs(Text,{color:o?n.color:void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," ",n.label]})]},n.key)})]})}function rc({type:e}){let{label:t,color:r}=zr[e];return jsx(Text,{color:r,children:t})}function sc({origin:e}){return e===kn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var Xo=cg.memo(function({item:t,isSelected:r}){let n=t.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:t.name}),t.type&&jsxs(Text,{children:[" ",jsx(rc,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(sc,{origin:t.origin})]}),jsxs(Text,{dimColor:true,children:[t.authorName?` \xB7 ${t.authorName}`:"",t.version?` \xB7 v${t.version}`:" \xB7 n/a"]}),t.status&&jsxs(Text,{color:n,children:[" [",t.status,"]"]}),t.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),t.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",St(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function nn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function lc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(nn,{message:t});let n=Math.max(0,r-Math.floor(Ve/2)),o=Math.min(e.length,n+Ve);o===e.length&&(n=Math.max(0,o-Ve));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,c)=>jsx(Xo,{item:l,isSelected:n+c===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function dc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function mc({groups:e,emptyMessage:t}){let r=S(p=>p.selectedIndex),n=[],o=0;for(let p of e){n.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let f of p.items)n.push({kind:"item",item:f,itemIndex:o,key:`i-${p.scope}-${f.name}-${f.marketplace??""}`}),o++;}if(o===0)return jsx(nn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Ve/2)),c=Math.min(n.length,l+Ve);c===n.length&&(l=Math.max(0,c-Ve));let u=n.slice(l,c),d=l,m=n.length-c;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),u.map(p=>p.kind==="header"?jsx(dc,{label:p.label,pathHint:p.pathHint},p.key):jsx(Xo,{item:p.item,isSelected:p.itemIndex===r},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var yg={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function wg({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(ec,{}),jsx(tc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:yg[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(mc,{groups:n,emptyMessage:r}):jsx(lc,{items:e,emptyMessage:r})]})}function fc({filteredItems:e,emptyMessage:t,groups:r,onBatchUpdate:n}){let o=S(l=>l.activeTab),s=S(l=>l.focus);return useInput(l=>{l==="a"&&e.length>0&&n?.();},{isActive:o==="updates"&&s==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(wg,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var Ig={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 qo(){let e=S(r=>r.focus),t=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[Ig[e],t?" | Ctrl+D: debug log":""]})})}function gc({message:e,type:t}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:t==="success"?"green":t==="info"?"cyan":"red",children:[t==="success"?"\u2713":t==="info"?"(i)":"\u2717"," ",y(e)]})}):null}function Yo({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Vi(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Sc=20;function Zo(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Sc),s="\u2588".repeat(o)+"\u2591".repeat(Sc-o),i=`${Vi(e)} / ${Vi(t)}`;return {bar:s,percent:n,label:i}}function Qo({received:e,total:t}){let{bar:r,percent:n,label:o}=Zo(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function es({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ze({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,c)=>{c.upArrow?a(u=>u>0?u-1:u):c.downArrow?a(u=>u<t.length-1?u+1:u):c.return?n(t[i]):c.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,c)=>jsxs(Box,{children:[jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},c))})]})}var Wi=Object.entries(An),vc=[...Wi.map(([,e])=>e.actionLabel),"Cancel"],Pc=Object.fromEntries(Wi.map(([,e])=>[e.actionLabel,e.description]));function Ec(e){let t=Wi.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var Og=I("provider.registry"),Ng=3e4,rs=class{adapters=new Map;availabilityCache=new Map;register(t){this.adapters.set(t.id,t);}async checkAvailability(t){let r=this.availabilityCache.get(t.id);if(r&&Date.now()<r.expiresAt)return r.result;let n=await t.isAvailable();return this.availabilityCache.set(t.id,{result:n,expiresAt:Date.now()+Ng}),n}async getAvailableProviders(t){let r=[...this.adapters.values()].filter(o=>t in o.installers),n=await Promise.allSettled(r.map(o=>this.checkAvailability(o)));return n.forEach((o,s)=>{o.status==="rejected"&&Og.warn(`Provider "${r[s].id}" isAvailable() threw: ${String(o.reason)}`);}),r.filter((o,s)=>{let i=n[s];return i.status==="fulfilled"&&i.value===true})}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var Bg={user:"global",project:"project",local:"local"};function ns(e){return e?Bg[e]:"global"}var Ne=class extends Error{constructor(r,n){super(`${r} v${n} is already installed. Use --force to reinstall.`);this.pluginName=r;this.version=n;this.name="AlreadyInstalledError";}pluginName;version},ar=class extends Error{constructor(r,n){super(`${r} is already up to date (v${n})`);this.pluginName=r;this.version=n;this.name="AlreadyUpToDateError";}pluginName;version};tn();function dt(){return Mc.create({prefix:or("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),hooks:{beforeRequest:[async({request:e})=>{let t=await xt();e.headers.set("Authorization",`Bearer ${t}`);let r=await q();r?.tenant&&Dt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Fg=I("catalog.registry"),os=class{adapters=new Map;register(t){this.adapters.set(t.id,t);}unregister(t){this.adapters.delete(t);}async fetchAllWithErrors(){let t=this.listAdapters(),r=await Promise.allSettled(t.map(s=>s.fetchItems())),n=[],o=[];for(let s=0;s<r.length;s++){let i=r[s],a=t[s];if(i.status==="fulfilled")n.push(...i.value);else {let l=String(i.reason);Fg.warn(`Catalog adapter failed: ${l}`),o.push({adapterId:a.id,adapterName:a.name,reason:l});}}return {items:n,failures:o}}async fetchAll(){let{items:t}=await this.fetchAllWithErrors();return t}getAdapter(t){return this.adapters.get(t)}listAdapters(){return [...this.adapters.values()]}};var zg={retries:5,minTimeout:50};async function zi(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Wg.lock(e+".lock",{realpath:false,retries:zg});try{return await t()}finally{await r();}}var ss=class{filePath;constructor(t){this.filePath=t??pl();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await zi(this.filePath,async()=>{let r=await this.read();if(r.some(o=>o.id===t.id))return;let n={...t,lastUpdated:t.lastUpdated??new Date().toISOString()};await this.write([...r,n]);});}async remove(t){if(t==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await zi(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await zi(this.filePath,async()=>{let n=await this.read();n.some(o=>o.id===t)&&await this.write(n.map(o=>o.id===t?{...o,...r}:o));});}};var Xg=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function Vn(e){if(!e||!Xg.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var qg=/^[^@]+@[^@]+$/;function sn(e){return qg.test(e)}function an(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var Yg=/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/;function Zg(e){if(!Yg.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 ln(e,t){let r=an(e);Zg(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var Qg=/^[\w./:@?&=+#%-]+$/;function is(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Qg.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or a URL (no spaces or special characters).`);return t}var eh=I("catalog.flow-api"),as=class{id="flow-api";name="Flow Marketplace";source;removable=false;constructor(){this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await dt().get("v1/plugins/catalog").json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle"}))}catch(t){if(t instanceof HTTPError){let{status:r}=t.response;throw r===401||r===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${r}`)}throw t instanceof Error?t.name==="TimeoutError"||t.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${t.message}`):t}}async fetchManifest(t){Vn(t);try{return await dt().get(`v1/plugins/${t}/manifest`).json()}catch(r){if(r instanceof HTTPError){let{status:n}=r.response;throw n===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${n}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await dt().head("v1/plugins/catalog"),eh.debug("ping ok"),!0}catch{return false}}};var le=new os,Ft=new ss;le.register(new as);var _c=false;async function Dc(){if(_c)return;_c=true;let e=await Ft.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Xi(),Rc));for(let r of e)le.register(new t(r.id,r.name,r.source));}var Oc=2;async function lr(){return le.fetchAll()}async function Nc(){return le.fetchAllWithErrors()}async function un(e){Vn(e);try{return await dt().get(`v1/plugins/${e}/manifest`).json()}catch(t){throw t instanceof Error?t.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):t.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${t.message}`):t}}async function Bc(e,t){Vn(e);try{let r=await dt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),c=[],u=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(u+=m.byteLength,i&&u>s*Oc)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*Oc}`);c.push(m),i&&t?.(u,s);}return Buffer.concat(c)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function ls(){try{let{profiles:e}=await dt().get("v1/plugins/profiles").json();return e}catch(e){throw e instanceof Error?e.message.includes("401")||e.message.includes("403")?new Error("Authentication failed. Run: flow auth login"):e.message.includes("timeout")?new Error("Request timed out while fetching starter kits"):new Error(`Failed to fetch starter kits: ${e.message}`):e}}async function Uc(e,t){let r=fe.resolve(t);await bt.mkdir(r,{recursive:true});let n=fe.join(fe.dirname(r),`${randomUUID()}.zip`);try{await bt.writeFile(n,e),await sh(n,{dir:r,onEntry(o){if((o.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${o.fileName}" is a symbolic link and was rejected`);let i=fe.resolve(r,o.fileName);if(process.platform==="win32"&&i.length>=260)throw new Error(`Path too long: "${i}" (${i.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);let a=fe.normalize(r+fe.sep);if(!i.startsWith(a)&&i!==r)throw new Error(`Zip Slip detected: entry "${o.fileName}" would escape target directory`)}});try{let o=realpathSync(r);if(!o.startsWith(fe.resolve(fe.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${o}" is outside expected parent`)}catch(o){if(o.code!=="ENOENT")throw o}}finally{try{await bt.unlink(n);}catch{}}}async function qi(e){await bt.rm(e,{recursive:true,force:true});}async function cr(){let e=ul();await bt.mkdir(fe.dirname(e),{recursive:true});try{await bt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Wg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function lh(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:z,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Kc(){let e=bo();if(!ge__default.existsSync(e))return null;try{return JSON.parse(ge__default.readFileSync(e,"utf-8"))}catch{return null}}function ch(){let e=Kc();if(e)return e;let t=lh(),r=bo();return ge__default.mkdirSync(fe__default.dirname(r),{recursive:true}),Yi(t),t}function Yi(e){let t=bo(),r=`${t}.${randomUUID()}.tmp`;ge__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ge__default.renameSync(r,t);}function uh(){let e=vo(),t={};try{ge__default.existsSync(e)&&(t=JSON.parse(ge__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[z])return;t[z]={source:{source:"github",repo:"CI-T-HyperX/flow-skills"},installLocation:cl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;ge__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ge__default.renameSync(r,e);}function Vc(e,t){ur(e.name),uh();let r=di(e.name);ge__default.mkdirSync(fe__default.dirname(r),{recursive:true});try{ge__default.lstatSync(r),ge__default.rmSync(r,{recursive:!0,force:!0});}catch{}ge__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=ch();n.plugins.some(s=>s.name===e.name)||(n.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),Yi(n));}function Zi(e){ur(e);let t=di(e);try{ge__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Kc();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Yi(r);}var ph=I("mcpConfigReader"),mh=500,fh=512;function gh(){return fe__default.join(be__default.homedir(),".claude.json")}function hh(){return fe__default.join(process.cwd(),".mcp.json")}function Jc(e){if(!ge__default.existsSync(e))return null;try{return JSON.parse(ge__default.readFileSync(e,"utf-8"))}catch{return ph.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qi(e){if(!Hn(e))return {};let t=e.mcpServers;return Hn(t)?t:{}}function ea(e,t){return Object.keys(e).slice(0,mh).map(n=>({name:y(n.slice(0,fh)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Wc(){let e=[],t=gh(),r=Jc(t);if(Hn(r)){let a=r,l=Qi(a);e.push(...ea(l,"user"));let c=process.cwd();if(Hn(a.projects)){let u=a.projects[c];if(Hn(u)){let d=Qi(u);e.push(...ea(d,"local"));}}}let n=hh(),o=Jc(n),s=Qi(o);e.push(...ea(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var Xe=I("storage");async function wh(e,t,r){try{await P(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:J().interfaceType});}catch(n){Xe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Sh(e,t,r){let n=t==="enabled"?b.CLI_TOOL_ENABLED:b.CLI_TOOL_DISABLED;P(n,{tool_id:e,source:r,interface:J().interfaceType}).catch(o=>Xe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function oa(){return fe__default.join(be__default.homedir(),".claude","plugins","installed_plugins.json")}function xh(){return fe__default.join(be__default.homedir(),".claude","plugins")}function zc(e){let t=fe__default.resolve(e),r=fe__default.resolve(xh()),n=fe__default.resolve(fe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+fe__default.sep)||t===r,s=t.startsWith(n+fe__default.sep)||t===n;if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Xc(e="user"){return e==="local"?fe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?fe__default.join(process.cwd(),".claude","settings.json"):fe__default.join(be__default.homedir(),".claude","settings.json")}function Ye(){let e=oa();if(!ge__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ge__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function sa(){let e=oa();try{let t=await ge__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function Ih(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function qc(e,t){try{ge__default.mkdirSync(fe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ge__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ge__default.renameSync(r,e);}catch(r){throw Ih(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function qe(e){qc(oa(),e);}function Jn(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function bh(e,t){let r=fe__default.join(e,".claude-plugin"),n=fe__default.join(r,"plugin.json");if(ge__default.existsSync(n))try{return JSON.parse(ge__default.readFileSync(n,"utf-8"))}catch{return null}let o=fe__default.join(r,"marketplace.json");if(ge__default.existsSync(o))try{let s=JSON.parse(ge__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function ia(e="user"){let t=Xc(e);if(!ge__default.existsSync(t))return {};try{return JSON.parse(ge__default.readFileSync(t,"utf-8"))}catch{return {}}}function Yc(e,t="user"){qc(Xc(t),e);}function vh(e,t){let{name:r,marketplace:n}=Jn(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Jn(i).name===r)[0],!o)throw Xe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Ph(e,t){let{name:r,marketplace:n}=Jn(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>Jn(i).name===r)[0],o?{key:o,name:r}:null}function ta(e="user"){return ia(e).enabledPlugins??{}}function ra(e,t="user"){let r=ia(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Yc(r,t);}function Gn(e,t,r="user"){let n=ia(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Yc(n,r);}function Eh(e){let t=new Map;for(let r of e){let n=t.get(r.scope);(!n||r.installedAt>n.installedAt)&&t.set(r.scope,r);}return [...t.values()]}function Q(){let e=Ye(),t=ta(),r=ta("project"),n=ta("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([c,u])=>{let{name:d,marketplace:m}=Jn(c),p=u.map(g=>g.scope==="managed"?{...g,scope:"user"}:g);return Eh(p).map(g=>{let h=bh(g.installPath,d),v=(o[g.scope]??t)[c];return {name:d,marketplace:m,version:g.version&&g.version!=="unknown"?g.version:void 0,installedAt:g.installedAt,installPath:g.installPath,scope:g.scope,providerId:g.providerId,type:g.type,description:h?.description,author:h?.author,status:v===false?"disabled":"enabled"}})}),i=Wc(),a=new Set(s.map(c=>`${c.name}@${c.scope}`)),l=i.filter(c=>!a.has(`${c.name}@${c.scope}`));return [...s,...l]}async function Wn(e,t){Xe.debug(`[${e}] Acquiring lock to uninstall`);let r=await cr();try{let n=Ye(),o=Ph(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);Xe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),zc(l.installPath);let c=fe__default.dirname(l.installPath);Xe.debug(`[${i}] Removing directory: ${c}`),ge__default.rmSync(c,{recursive:!0,force:!0});let u=a.filter(d=>d.scope!==t);if(u.length===0){let{[s]:d,...m}=n.plugins;qe({...n,plugins:m}),ra(s,t),Zi(i);}else n.plugins[s]=u,qe(n),ra(s,t);}else {Xe.debug(`[${i}] Resolved key: ${s}`);for(let u of a){zc(u.installPath);let d=fe__default.dirname(u.installPath);Xe.debug(`[${i}] Removing directory: ${d}`),ge__default.rmSync(d,{recursive:!0,force:!0}),ra(s,u.scope);}Zi(i);let{[s]:l,...c}=n.plugins;qe({...n,plugins:c});}await wh(i,a[0].origin??"internal",a[0].type??"skill"),Xe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function zn(e,t,r){Xe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await cr();try{let o=Ye(),{key:s,name:i}=vh(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,c=a[0].origin??"internal";Xe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),Gn(s,t==="enabled",l),Sh(i,t,c),Xe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Th=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Ch=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ur(e){if(!Th.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function kh(e){if(!Ch.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var dr=I("installer");function Ah(e,t){let r=`${e}@${z}`,o=Ye().plugins[r];if(o&&!t)throw new Ne(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function $h(e,t,r){r&&await qi(t);try{dr.debug(`[${t}] Extracting archive...`),await Uc(e,t);}catch(n){throw await qi(t),n}}function Mh(e,t,r,n,o,s="claude-code",i){let a=Ye(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},c=a.plugins[e]??[];a.plugins[e]=[...c.filter(u=>u.scope!==n),l],qe(a),Gn(e,true,n);}async function Lh(e,t,r,n,o,s){try{await P(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:J().interfaceType});}catch(i){dr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Rh(e,t,r,n){try{await P(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:n,source:r,error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(o){dr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Te(e,t={}){let r=Date.now(),n=null;try{dr.debug(`[${e}] Acquiring lock...`),n=await cr();let{pluginKey:o,alreadyInstalled:s}=Ah(e,t.force);dr.debug(`[${e}] Fetching manifest...`);let i=await un(e);ur(i.name),kh(i.version),dr.debug(`[${e}] Downloading archive...`);let a=await Bc(e,t.onDownloadProgress),l=t.scope??"user",c=t.type??"skill",u=ll(i.name,i.version);await $h(a,u,!!s&&!!t.force),Mh(o,u,i.version,l,"internal",t.providerId,c),Vc(i,u);let d=Date.now()-r;dr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:u,duration_ms:d};return t.skipMetrics||await Lh(i.name,i.version,d,ns(l),"internal",c),m}catch(o){throw await Rh(e,o,"internal",t.type??"skill"),dr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var _h=I("commands:helpers");async function se(){if(!await q())return E("Not authenticated. Run: flow auth login"),false;try{await xt();}catch(t){return _h.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function vt(e){let t=aa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(["y","yes"].includes(n.toLowerCase().trim()));});})}async function Zc(e){let t=aa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var dn=I("claudeProxy"),pa="claude ",Qc="flow ",la=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},ca=class extends Error{constructor(t){super(`Disallowed subcommand: "${t}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Dh=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Oh=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Nh=/^(flow|claude)\s+auth\s+login(\s|$)/,eu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function tu(e){return eu.test(e.trim())}function Bh(e){return eu.exec(e.trim())?.[2]??""}async function ru(e){let t=Bh(e),r=Date.now();dn.debug(`[${t}] Executing: flow plugin install ${t}`);try{let n=await execa("flow",["plugin","install",t],{reject:!1});return {name:t,command:`flow plugin install ${t}`,exitCode:n.exitCode??1,stdout:n.stdout,stderr:n.stderr,duration_ms:Date.now()-r}}catch(n){throw ma(n)?new ua:n}}function Uh(e){nu(e);let t=e.slice(pa.length);if(!Dh.test(t))throw new ca(e)}var cs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},ua=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function nu(e){if(!e||!/^claude /.test(e))throw new la(e)}async function we(e){nu(e);let t=e.slice(pa.length).split(/\s+/).filter(Boolean),r=Fh(t);dn.debug(`[${r}] Executing proxy command: claude ${t.join(" ")}`);let n=Date.now();try{let o=await execa("claude",t,{reject:!1}),s=Date.now()-n;return dn.debug(`[${r}] Proxy command finished with exit code ${o.exitCode} in ${s}ms`),{name:r,command:e,exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr,duration_ms:s}}catch(o){throw ma(o)?new cs:o}}function Fh(e){return e.length>=3?e[2]:e.join(" ")}function ma(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function jh(e){return e.startsWith(Qc)?pa+e.slice(Qc.length):e}function Kh(e){return Oh.test(e)||Nh.test(e)}function Vh(e){let t=0;for(;t<e.length&&Kh(e[t]);)t++;return e.slice(t)}var Hh=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Jh(e,t){return !t||e.includes("--scope")||!Hh.test(e)?e:`${e} --scope ${t}`}async function Xn(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Vh(r).map(i=>jh(i)).map(i=>Jh(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Uh(i);dn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await we(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await we(o[i]),s.exitCode!==0)return s;return s}async function us(e,t,r){let n=an(e),o=t?.trim();if(!o&&(o=(await Zc(`Plugin "${n}" could not be installed.
|
|
111
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!o))throw new Error("No marketplace source provided. Cannot retry install.");o=is(o),r?.(),dn.debug(`[${n}] Adding marketplace via: claude plugin marketplace add ${o}`);try{let s=await execa("claude",["plugin","marketplace","add",o],{reject:!1});if(s.exitCode!==0)throw new Error(`Failed to add marketplace: ${s.stderr||"unknown error"}`);dn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw ma(s)?new cs:s}}var qh=6e4,pr=class extends Error{url;isTimeout;isAuthError;constructor(t,r,n=false,o=false){super(t),this.name="GitCloneError",this.url=r,this.isTimeout=n,this.isAuthError=o;}};async function Pt(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:qh}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),o=t?["--depth","1","--branch",t]:["--depth","1"];try{return await n.clone(e,r,o),r}catch(s){await rm(r,{recursive:true,force:true}).catch(()=>{});let i=s instanceof Error?s.message:String(s),a=i.includes("block timeout")||i.includes("timed out"),l=i.includes("Authentication failed")||i.includes("could not read Username")||i.includes("Permission denied")||i.includes("Repository not found");throw a?new pr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new pr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new pr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Et(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm(e,{recursive:true,force:true});}async function Nr(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function Zh(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Qh(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ey(e){return typeof e=="object"&&e!==null&&e.source==="github"}function pn(e,t){let r=e.source;if(Zh(r)){let n=r.path?r.path.replace(/^\.\//,""):".",o=r.ref&&!/^[0-9a-f]{40}$/i.test(r.ref)?r.ref:void 0;return {cloneUrl:r.url,subPath:n||".",ref:o}}if(Qh(r))return {cloneUrl:r.url,subPath:"."};if(ey(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function Ze(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Tt=I("claude-code.adapter");function ny(e,t){let r=e??"external";if(!t)return r;let n=t.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!n)return r;let o=n[1],s=vo();if(!ge__default.existsSync(s))return r;try{let i=JSON.parse(ge__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function uu(e,t){let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=pn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=e.type==="bundle"||e.type==null,s=ny(e.catalogId,r?.source),i=t.scope??"user",a;o?a=pi(s,e.name,"external"):a=join(vr(i==="user"?"global":"project"),e.name);let l=null;try{ur(e.name),l=await Pt(n.cloneUrl,n.ref);let c=n.subPath==="."?l:join(l,n.subPath);if(ge__default.existsSync(a)&&ge__default.rmSync(a,{recursive:!0,force:!0}),ge__default.mkdirSync(dirname(a),{recursive:!0}),ge__default.cpSync(c,a,{recursive:!0}),o){let u=`${e.name}@${s}`,d=await sa(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[u]??[];d.plugins[u]=[...p.filter(f=>f.scope!==i),m],qe(d),Gn(u,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(c){return Tt.debug(`[${e.name}] External catalog install failed: ${String(c)}`),{success:false,message:c instanceof Error?c.message:String(c)}}finally{l&&await Et(l).catch(()=>{});}}async function fa(e,t,r,n){try{await P(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:ns(n),version:"unknown",duration_ms:t,interface:J().interfaceType});}catch(o){Tt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function lu(e,t,r){try{await P(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:r,source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(n){Tt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var oy={async install(e,t){if(e.origin===Wr&&!e.installCommand&&!sn(e.name))return uu(e,t);if(e.origin===Wr&&e.installCommand){let r=e.type??"skill",n=await Xn(e.installCommand,t.scope);return n.exitCode===0?(await fa(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await lu(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(sn(e.name)){let r=e.type??"skill",n=ln(e.name,t.scope);Tt.debug(`[${e.name}] Attempting install: ${n}`);let o=await we(n);if(o.exitCode===0)return await fa(e.name,o.duration_ms,r,t.scope),{success:true};Tt.debug(`[${e.name}] First attempt failed, adding marketplace`),await us(e.name,t.marketplaceSource,()=>{});let s=await we(n);return s.exitCode===0?(await fa(e.name,s.duration_ms,r,t.scope),{success:true}):(await lu(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await Te(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Tt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Wn(e,t);},getInstallPath(e,t){return ""}};function cu(e){return {async install(t,r){if(t.origin===Wr&&!t.installCommand&&!sn(t.name))return uu(t,r);if(!t.installCommand)try{let o=await Te(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Tt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Tt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await Xn(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Ye(),o=`${t}@${z}`;if(n.plugins[o]){await Wn(t,r);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${t}`)},getInstallPath(t,r){return ""}}}function sy(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ge__default.existsSync(t))continue;let r=ge__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ge__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function ga(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ga(r)]))}function du(e,t){let r={...e};for(let[n,o]of Object.entries(t)){let s=r[n];if(Array.isArray(o)&&Array.isArray(s)){let i=new Set(s.map(a=>JSON.stringify(ga(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(ga(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=du(s,o):r[n]=o;}return r}async function pu(e,t,r,n){let o=await sa(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],qe(o);}var iy={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=pn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ur(e.name),s=await Pt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=sy(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=Eo(r);ge__default.mkdirSync(l,{recursive:!0});let c=Ze(e.name);if(a.length===1)ge__default.copyFileSync(a[0],join(l,`${c}.md`));else for(let d of a){let m=Ze(basename(d,".md"));ge__default.copyFileSync(d,join(l,`${c}--${m}.md`));}let u=a.length===1?join(l,`${c}.md`):l;return await pu(e.name,r,u,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Et(s).catch(()=>{});}},async uninstall(e,t){let r=Eo(t),n=Ze(e);if(ge__default.existsSync(r))for(let a of ge__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ge__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ye(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;qe({...s,plugins:l});}else qe({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(Eo(t),`${Ze(e)}.md`)}},ay={async install(e,t){let r=t.scope??"user",n=e.catalogId?le.getAdapter(e.catalogId):void 0,o=pn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ur(e.name),s=await Pt(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!ge__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ge__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let c=l.hooks;if(!c||typeof c!="object"||Array.isArray(c))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let u=Un();if(u.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=u.status==="ok"?u.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=du(m,c);return Jo({...d,hooks:p}),await pu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Tt.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Et(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},ds=class{id="claude-code";name="Claude Code";async isAvailable(){return Nr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:oy,skill:cu("skill"),mcp:cu("mcp"),agent:iy,hook:ay}};function ps(e,t){return {async install(r,n){if(!r.installCommand)return {success:false,message:"No install command provided"};let[o,...s]=r.installCommand.split(/\s+/).filter(Boolean);if(!o||!e.has(o))return {success:false,message:`Disallowed command: "${o??""}"`};let i=await execa(o,s,{reject:false});return i.exitCode===0?{success:true}:{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`}},async uninstall(r,n){throw new Error(`MCP uninstall not supported \u2014 ${t.replace("<name>",r)}`)},getInstallPath(r,n){return ""}}}var cy=new Set(["gh"]),uy=ps(cy,"use: gh copilot mcp remove <name>"),ms=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Nr("gh",["--version"])?Nr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:uy}};var dy=new Set(["opencode"]),py=ps(dy,"use: opencode config remove mcp <name>");function my(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
+
`)}function mu(){return {async install(e,t){let r=e.catalogId?le.getAdapter(e.catalogId):void 0,n=pn(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await Pt(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Po(t.scope??"user"),a=join(s,".opencode","plugins");if(ge__default.existsSync(a)){let l=ge__default.readdirSync(a).filter(c=>c.endsWith(".js")||c.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ge__default.mkdirSync(i,{recursive:!0}),ge__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ge__default.existsSync(l)&&ge__default.rmSync(l,{recursive:!0,force:!0}),ge__default.mkdirSync(l,{recursive:!0}),ge__default.cpSync(s,l,{recursive:!0}),ge__default.mkdirSync(i,{recursive:!0}),ge__default.writeFileSync(join(i,`${e.name}.js`),my(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(s){return {success:false,message:s instanceof Error?s.message:String(s)}}finally{o&&await Et(o).catch(()=>{});}},async uninstall(e,t){let r=Po(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ge__default.existsSync(n)&&ge__default.rmSync(n,{force:true}),ge__default.existsSync(o)&&ge__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Po(t),`${e}.js`)}}}var fs=class{id="opencode";name="OpenCode";async isAvailable(){return Nr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:py,skill:mu(),bundle:mu()}};var Ct=new rs;Ct.register(new ds);sr()&&(Ct.register(new ms),Ct.register(new fs));function fu({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,c]=useState([]),[u,d]=useState(void 0);useEffect(()=>{Ct.getAvailableProviders(t??"bundle").then(c).catch(()=>{});},[t]);let m=useCallback(h=>{h==="Install"?l.length>1?a(true):s(true):n();},[n,l.length]),p=useCallback(h=>{if(h==="Cancel"){a(false);return}let w=l.find(v=>v.name===h);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(h=>{let w=Ec(h);w?r(w,u):s(false);},[r,u]),g=useCallback(()=>{s(false);},[]);if(i){let h=[...l.map(w=>w.name),"Cancel"];return jsx(ze,{itemName:`${e} \u2014 Choose provider`,actions:h,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(ze,{itemName:`${e} \u2014 Choose scope`,actions:vc,descriptions:Pc,onAction:f,onClose:g},"scope"):jsx(ze,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function hu({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),c=(t?.artifact.artifacts??[]).filter(f=>f.available),u=t!==void 0&&c.length===0,d=useMemo(()=>u?["Cancel"]:["Confirm Install","Cancel"],[u]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,g)=>{g.upArrow?a(h=>Math.max(0,h-1)):g.downArrow?a(h=>Math.min(d.length-1,h+1)):g.return?d[i]==="Confirm Install"?n():o():g.escape&&o();},[d,i,n,o]);useInput(m,{isActive:s==="actionMenu"&&t!==void 0});let p=useCallback(f=>{f==="Install Bundle"?r():o();},[r,o]);return t?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:t.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[c.length," artifact",c.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:c.map(f=>{let g=y(f.name??f.flowId),h=f.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:g}),jsxs(Text,{dimColor:true,children:["(",h,")"]})]},f.flowId)})}),jsx(Box,{flexDirection:"column",children:d.map((f,g)=>jsx(Box,{children:jsxs(Text,{bold:g===i,color:g===i?"cyan":void 0,children:[g===i?"\u203A ":" ",f]})},f))})]}):jsx(ze,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function ys({activeFocus:e,onConfirm:t}){let[r,n]=useState("idle"),o=S(s=>s.focus);return useInput((s,i)=>{i.escape||s==="n"?n("idle"):s==="y"&&t();},{isActive:r==="confirming"&&o===e}),{isConfirming:r==="confirming",requestConfirm:()=>n("confirming"),cancelConfirm:()=>n("idle")}}function Su({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:c,requestConfirm:u}=ys({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(c)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(ze,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:h=>{h==="Uninstall"?u():h===d?i(t):h.startsWith("Update")?a?.():l();},onClose:l})}function bu({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=ys({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ze,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var gn=I("bundle:installer"),vu=/already exists/i;async function Iy(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(tu(t)){let r=await ru(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(vu.test(n))return;throw new Error(n)}}else {let r=await Xn(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(vu.test(n))return;throw new Error(n)}}}async function by(e,t){try{await P(b.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){gn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function vy(e,t,r){try{await P(b.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){gn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function Pu(e,t,r,n){try{await P(b.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){gn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function Py(e,t,r,n,o){try{await P(b.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){gn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function xs(e,t={}){let{onProgress:r}=t,n=e.artifact.artifacts,o=n.filter(p=>p.available),s=n.length-o.length,i=e.artifact.name,a=Date.now();await by(i,o.length);let l=[],c=0,u=o.length;for(let[p,f]of o.entries()){let g=f.name??f.flowId,h=f.type??"unknown";if(!f.type){gn.warn(`Artifact "${g}" has no type \u2014 treated as failed`),l.push({name:g,type:h,reason:"unknown artifact type"}),await Pu(i,g,h,"unknown artifact type"),r?.({index:p+1,total:u,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Iy(f),c++,await vy(i,g,h),r?.({index:p+1,total:u,artifact:f,success:!0});}catch(w){let v=w instanceof Error?w.message:String(w);gn.error(`Failed to install artifact "${g}": ${v}`),l.push({name:g,type:h,reason:v}),await Pu(i,g,h,v),r?.({index:p+1,total:u,artifact:f,success:false,error:v});}}let d=Date.now()-a,m=l.length;return await Py(i,c,m,s,d),{bundleTitle:e.title,total:n.length,installed:c,skipped:s,failed:m,failures:l}}function ku({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,xs(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",c=e.artifact.artifacts,u=c.filter(d=>d.available);s({bundleTitle:e.title,total:c.length,installed:0,skipped:c.length-u.length,failed:u.length,failures:u.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",r.index,"/",r.total,"] Installing"," ",y(r.artifact.name??r.artifact.flowId)," (",r.artifact.type??"unknown",")"]})]}),!r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ce=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:Q()})}));function Au({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,c=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),c&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",St(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function $u({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:c,stored:u}=e,d=c.removable!==false,m=u?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",u?.lastUpdated?` \xB7 Updated ${St(u.lastUpdated)}`:""]})}),u&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((g,h)=>{let w=h===o;return jsxs(Box,{children:[jsx(Text,{color:w?"cyan":void 0,children:w?"\u203A ":" "}),jsx(Text,{bold:w,color:g.danger?"yellow":void 0,dimColor:!w,children:g.label})]},g.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:c.name}),jsx(Text,{dimColor:true,children:c.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Mu(e){return e.adapter.removable!==false?4:2}function Lu({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((c,u)=>{if(u.escape){n();return}if(u.upArrow){l(d=>Math.max(0,d-1));return}if(u.downArrow){l(d=>Math.min(i.length-1,d+1));return}u.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((c,u)=>jsxs(Box,{children:[jsx(Text,{color:u===a?"cyan":void 0,children:u===a?"\u203A ":" "}),jsx(Text,{bold:u===a,color:c.danger?"yellow":void 0,dimColor:u!==a,children:c.label})]},c.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function _u({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Du({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(T=>r.has(`${T.name}@${o}`)),i=t.filter(T=>!r.has(`${T.name}@${o}`)),a=[...s,...i],[l,c]=useState(0),[u,d]=useState(null);if(useInput((T,L)=>{if(L.escape){n();return}if(L.return){d(a[l]??null);return}if(L.upArrow){c(F=>Math.max(0,F-1));return}L.downArrow&&c(F=>Math.min(a.length-1,F+1));},{isActive:u===null}),u!==null)return jsx(Lu,{item:u,adapterName:e.adapter.name,isInstalled:r.has(`${u.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Ve/2)),p=Math.min(a.length,m+Ve);p===a.length&&(m=Math.max(0,p-Ve));let f=a.slice(m,p),g=m,h=a.length-p,w=s.length>0&&m<s.length,v=p>s.length,D=f.filter(T=>r.has(`${T.name}@${o}`)),U=f.filter(T=>!r.has(`${T.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:g>0?`\u2191 ${g} more above`:" "})}),w&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),D.map(T=>jsx(_u,{item:T,isSelected:a.indexOf(T)===l,isInstalled:true},T.name))]}),v&&jsxs(Box,{flexDirection:"column",marginTop:w?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),U.map(T=>jsx(_u,{item:T,isSelected:a.indexOf(T)===l,isInstalled:false},T.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"})})]})}Xi();var My=/^https?:\/\/.+/;function Ly(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Ry(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Uu(e){let t=S(h=>h.showNotification),r=S(h=>h.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[c,u]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),u(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),g=useCallback(async()=>{let h=m.current,w=d.current;if(!My.test(h)){u("URL must start with http:// or https://");return}u(null),o("adding");let v=randomUUID(),D=new cn(v,w,h);try{await D.fetchItems(),await Ft.add({id:v,name:w,source:h}),le.register(new cn(v,w,h)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(U){let T=Ly(U)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Ry(U)?U.message:U instanceof Error?`Could not reach catalog URL: ${U.message}`:"Failed to validate catalog URL";t(T,"error"),o("add-url");}},[e,t,r]);return useInput((h,w)=>{if(w.escape){o("idle");return}if(w.return){d.current.trim().length>0&&o("add-url");return}if(w.backspace||w.delete){d.current=d.current.slice(0,-1),i(d.current);return}h&&!w.ctrl&&!w.meta&&(d.current=d.current+h,i(d.current));},{isActive:n==="add-name"}),useInput((h,w)=>{if(w.escape){o("add-name");return}if(w.return){g();return}if(w.backspace||w.delete){m.current=m.current.slice(0,-1),l(m.current),u(null);return}h&&!w.ctrl&&!w.meta&&(m.current=m.current+h,l(m.current),u(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:c,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Fu(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Ft.remove(o),le.unregister(o),r(),e(),t("Catalog removed","success");}catch(s){t(s instanceof Error?s.message:"Failed to remove catalog","error");}},[e,t,r])}}function Ku(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=ce(A=>A.installedItems),[o,s]=useState(()=>le.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,c]=useState("list"),[u,d]=useState(0),[m,p]=useState(null),[f,g]=useState("main"),h=useRef(o);useEffect(()=>{h.current=o;},[o]),useEffect(()=>{f==="browse"&&!o[i-1]&&g("main");},[f,o,i]);let w=useCallback(()=>{(async()=>{let A=le.listAdapters(),B=await Ft.read(),W=new Map(B.map(Ie=>[Ie.id,Ie]));s(A.map(Ie=>({adapter:Ie,stored:W.get(Ie.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=h.current[i-1];if(!A)return;let B=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(W=>{B||p({items:W,loading:false,error:null});}).catch(W=>{B||p({items:[],loading:false,error:W instanceof Error?W.message:"Failed to load catalog"});}),()=>{B=true;}},[i]);let v=Uu(w),D=useCallback(()=>{w(),a(0),c("list"),p(null),g("main");},[w]),{handleRemove:U}=Fu(D),T=useCallback(async A=>{g("removing"),await U(A);},[U]),L=useCallback(async A=>{try{let B=await A.adapter.fetchItems();if(p({items:B,loading:!1,error:null}),A.stored){let W=new Date().toISOString();await Ft.updateField(A.stored.id,{lastUpdated:W}),w();}r("Marketplace updated","success");}catch(B){r(B instanceof Error?B.message:"Update failed","error");}},[w,r]),F=useCallback(async A=>{if(!A.stored)return;let B=A.stored.autoUpdate!==false;await Ft.updateField(A.stored.id,{autoUpdate:!B}),w();},[w]),V=useCallback(()=>g("browse"),[]),R=useCallback(A=>{let B=o[i-1];if(!B)return;let W=B.adapter.removable!==false;[V,()=>{L(B);},...W?[()=>{F(B);},()=>{T(B.adapter.id);}]:[]][A]?.();},[o,i,V,L,F,T]),x=useCallback(()=>g("main"),[]),k=useCallback(()=>{let A=o[i-1];A&&L(A);},[o,i,L]),j=useCallback(()=>{let A=o[i-1];A&&F(A);},[o,i,F]),O=useCallback(()=>{let A=o[i-1];A&&T(A.adapter.id);},[o,i,T]);if(useInput((A,B)=>{if(B.upArrow){a(W=>Math.max(0,W-1));return}if(B.downArrow){a(W=>Math.min(o.length,W+1));return}(B.return||B.tab)&&(i===0?v.startAdd():(c("detail"),d(0)));},{isActive:f==="main"&&v.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,B)=>{if(B.escape||B.tab){c("list");return}if(B.upArrow){d(W=>Math.max(0,W-1));return}if(B.downArrow){let W=o[i-1],Ie=W?Mu(W)-1:0;d(wo=>Math.min(wo+1,Ie));return}B.return&&R(u);},{isActive:f==="main"&&v.phase==="idle"&&l==="detail"&&e==="marketplaces"}),v.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:v.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(v.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:v.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:v.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),v.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:v.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(v.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(f==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(f==="browse"){let A=o[i-1];if(!A)return jsx(Box,{});let B=A.adapter.id??"default",W=new Set(n.filter(Ie=>Ie.marketplace===A.adapter.name).map(Ie=>`${Ie.name}@${B}`));return jsx(Du,{entry:A,items:m?.items??[],installedKeys:W,onBack:x})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let Ke=o[i-1]??null,Gr=Ke?n.filter(A=>A.marketplace===Ke.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Au,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&Ke?jsx($u,{entry:Ke,detailData:m,installedCount:Gr,focusPanel:l,actionIndex:u,onBrowse:V,onUpdate:k,onToggleAutoUpdate:j,onRemove:O}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:Ke?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:l==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function Vu(e,t,r,n){if(t.upArrow)return r.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:r.selectedIndex-1}];if(t.downArrow&&r.selectedIndex<n-1)return [{type:"setSelectedIndex",index:r.selectedIndex+1}];if(t.leftArrow){let o=Y.findIndex(i=>i.id===r.activeTab),s=Y[(o-1+Y.length)%Y.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=Y.findIndex(i=>i.id===r.activeTab),s=Y[(o+1)%Y.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=Y.findIndex(i=>i.id===r.activeTab),s=Y[(o+1)%Y.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}return t.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&r.activeTab==="updates"?[]:e&&e!==" "&&!t.ctrl&&!t.meta&&!t.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function Hu(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Ju(e,t,r){return t.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:t.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:t.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:t.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:t.backspace?r.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!t.ctrl&&!t.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var By=new Set(Y.filter(e=>e.focus!=="list").map(e=>e.focus));function so(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:c}=Oe.getState();i(a.slice(0,c)+s.char+a.slice(c)),l(c+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function Gu({listLength:e}){let t=S(g=>g.focus),r=S(g=>g.selectedIndex),n=S(g=>g.actionMenuOpen),o=S(g=>g.setFocus),s=S(g=>g.setActionMenuOpen),i=Oe(g=>g.query),a=Oe(g=>g.setQuery),l=Oe(g=>g.resetQuery),c=useRef(e);useEffect(()=>{c.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:g,setCursorPosition:h}=Oe.getState();h(g.length);}},[t]);let[u,d]=useState("");useEffect(()=>{let g=setTimeout(()=>d(i),300);return ()=>clearTimeout(g)},[i]),useInput((g,h)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();so(Oi(g,h,{activeTab:w}));},{isActive:t==="tabs"}),useInput((g,h)=>{if(!h.leftArrow&&!h.rightArrow)return;let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();so(Oi("",h,{activeTab:w}));},{isActive:By.has(t)}),useInput((g,h)=>{let{activeTab:w,selectedIndex:v,actionMenuOpen:D}=S.getState();so(Vu(g,h,{activeTab:w,selectedIndex:v},c.current));},{isActive:t==="list"}),useInput((g,h)=>{so(Hu(g,h));},{isActive:t==="actionMenu"}),useInput((g,h)=>{let w=Ju(g,h,Oe.getState().query),v=w.queryUpdate;if(so(w.actions),v==="reset")l(),d("");else if(v!==null){let{query:D,cursorPosition:U,setCursorPosition:T}=Oe.getState();if("backspace"in v)U>0&&(a(D.slice(0,U-1)+D.slice(U)),T(U-1));else if("append"in v)a(D.slice(0,U)+v.append+D.slice(U)),T(U+v.append.length);else if("cursorMove"in v){let L=U+v.cursorMove;L>=0&&L<=D.length&&T(L);}}},{isActive:t==="search"});let m=useCallback(()=>{s(false),o("list");},[s,o]),p=useCallback(g=>{let{setSelectedIndex:h,selectedIndex:w}=S.getState();g===0?h(0):w>=g&&h(g-1);},[]),f=useCallback(g=>{if(!u)return c.current=g.length,g;let h=u.toLowerCase(),w=g.filter(v=>v.name.toLowerCase().includes(h)||v.description?.toLowerCase().includes(h));return c.current=w.length,w},[u]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function zu(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Ge(a=>a.justAuthenticated),o=Ge(a=>a.credentials),s=Ge(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Ae(e,t,r=false){return r?true:!xa.valid(e)||!xa.valid(t)?false:xa.gt(t,e)}var Vt=I("updater");async function Uy(e,t,r,n,o,s){try{await P(b.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:J().interfaceType});}catch(i){Vt.warn(`Failed to send update metrics: ${String(i)}`);}}function Fy(e){let t=Ye(),r=`${e}@${z}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Ps(e,t={}){let r=Date.now(),n=null;try{Vt.debug(`[${e}] Acquiring lock...`),n=await cr();let o=Fy(e);if(!o)throw Vt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Vt.debug(`[${e}] Fetching manifest...`);let c=(await un(e)).version;if(!i||!Ae(i,c,t.force))throw Vt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new ar(e,i??"unknown");Vt.info(`[${e}] Updating v${i} \u2192 v${c}...`),await n(),n=null;try{let u=await Te(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Uy(u.name,i,u.version,d,s.origin??"internal",s.type??"skill"),Vt.debug(`[${e}] Updated successfully in ${d}ms`),{name:u.name,previousVersion:i,newVersion:u.version,path:u.path,duration_ms:d}}catch(u){Vt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await cr();let d=Ye(),m=`${e}@${z}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,qe(d),Vt.info(`[${e}] Rollback completed, restored to v${i}`)),u}}finally{n&&await n();}}var Es=I("dispatcher");async function jy(e,t,r,n,o){let s=an(e);return Es.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await us(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Es.debug(`[${e}] Retrying install after marketplace add`),we(t)}async function Xu(e,t,r,n){let o=ln(e,n),s=an(e);r?.onStatus?.(`Installing ${s}...`),Es.debug(`[${e}] Attempting install: ${o}`);let i=await we(o);if(i.exitCode===0)return i;Es.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return jy(e,o,a,t,r)}async function qu(e,t,r){let n=e.type??"bundle",o=await Ct.getAvailableProviders(n),s=o[0];if(!s)throw new Error(`No available provider for artifact type "${n}"`);let i=s.installers[n];if(!i)throw new Error(`Provider "${s.id}" does not support type "${n}"`);let a=t??{},l=a;return i.install(e,l)}function Yu(){let e=ce(i=>i.installedItems),t=ce(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await qu(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=Q().find(p=>p.name===i),c=l?.providerId??"claude-code",u=Ct.getAdapter(c);if(!u)throw new Error(`Provider "${c}" not found`);let d=l?.type??"bundle",m=u.installers[d];if(!m)throw new Error(`Provider "${c}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let c=e.find(u=>u.name===i)?.status==="enabled"?"disabled":"enabled";await zn(i,c,a),t();},[e,t]),s=useCallback(async i=>{await Ps(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var Cs=I("mcp");function io(e,t){e.silent?Je({status:"error",mcp:t.name,...t.exitCode!==void 0&&{exitCode:t.exitCode},message:t.message}):E(`Failed to ${t.action} MCP "${t.name}": ${t.message}`);}function Qu(e,t){e.silent?_e({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ne(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function Ky(e,t,r,n){let o=["claude","mcp","add","--transport",r,e];return t.length>0&&o.push(...t),n&&o.push("--scope",n),o.join(" ")}function Ia(e,t){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let r=["claude","mcp","remove",e];return t&&r.push("--scope",t),r.join(" ")}async function ed(e,t,r){if(!await se())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return io(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}Cs.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Ky(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await vt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|
|
114
|
-
[y/N] `))return
|
|
114
|
+
[y/N] `))return Cs.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:Xa({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await we(n);return o?.stop(),s.exitCode!==0?(io(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&C(`stdout: ${s.stdout}`),1):(Qu(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),io(r,{name:e,action:"add",message:H(s)}),1}}async function td(e,t){if(!await se())return 1;Cs.debug(`[${e}] Starting MCP remove`);let r=Ia(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await vt(`Remove MCP "${o}"?
|
|
115
115
|
This will run: ${s}
|
|
116
|
-
[y/N] `))return Fs.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:tl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await Pe(r);return n?.stop(),o.exitCode!==0?(go(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(fd(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),go(t,{name:e,action:"remove",message:te(o)}),1}}function yd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(E=>E.setLoading),c=S(E=>E.setDownloadProgress),{install:u,uninstall:d,toggle:m,update:p}=pd(),f=async(E,M,K)=>{l(true,E),n();try{await M(),o(r.length),s(K,"success");}catch(H){let ue=H instanceof Error?H.message:"Something went wrong";i.error(`[withLoading] ${E} failed: ${ue}`),s(ue,"error");}finally{l(false);}};return {handleInstall:(E,M)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>u(t,{scope:E,...M!==void 0?{providerId:M}:{},onDownloadProgress:(K,H)=>{let ue=Date.now();(ue-a.current>100||K>=H)&&(a.current=ue,c(K,H));}}),"\u2713 Installed successfully"));},handleUninstall:E=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,E),"\u2713 Uninstalled");},handleToggleStatus:E=>{if(!e)return;let M=e.status==="enabled";f(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,E),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let E=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${E}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${E}`,"success");}catch(K){if(K instanceof mr)s(K.message,"info");else {let H=K instanceof Error?K.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${H}`),s(H,"error");}}finally{l(false);}})();},handleBatchUpdate:E=>{if(E.length===0)return;let M=E.length;(async()=>{l(true,`Updating ${M} plugin${M>1?"s":""}...`),n();try{let H=[];for(let U of E)H.push(await p(U.name).then(()=>({status:"fulfilled",value:void 0}),G=>({status:"rejected",reason:G})));let ue=H.filter(U=>U.status==="fulfilled").length,T=H.map((U,G)=>U.status==="rejected"?E[G].name:null).filter(U=>U!==null);o(r.length),T.length===0?s(`\u2713 Updated ${ue}/${M} plugin${M>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${T.join(", ")}`),s(`Updated ${ue}/${M}; failed: ${T.join(", ")}`,ue>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:E=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let M=ka(e.name,E),K=await Pe(M);if(K.exitCode!==0)throw new Error(K.stderr||"MCP removal failed");pe.getState().loadFromDisk();},"\u2713 MCP removed");}}}var ho=x("api:bundle"),Pn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},yo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},pw=/^[a-zA-Z0-9_-]{1,128}$/;async function Sd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw ho.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new Pn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new yo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw ho.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function xd(e){if(!pw.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);ho.debug(`Fetching bundle by flowId "${e}"`);try{return await gt().get(`v1/use-cases/${t}`).json()}catch(r){return Sd(r,e)}}async function js(e){let t=encodeURIComponent(e);ho.debug(`Fetching bundle by name "${e}"`);let r;try{r=await gt().get(`v1/use-cases/by-name/${t}`).json(),ho.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Sd(n,e)}if(r.length===0)throw new Pn(e);return r[0]}var mw=x("tui:bundle-flow");function Id({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:c,setBundleInstallFlow:u}=S.getState(),d=l?.trim();mw.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),c(true,"Loading bundle..."),(d?xd(d):js(a)).then(p=>{c(false),S.getState().actionMenuOpen&&u({phase:"detail",bundle:p});}).catch(p=>{c(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),pe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var wo=["local","project","user"],fw=new Set(["--transport","--scope","-s"]);function bd(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(fw.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Hr(e,t){return t?`${e}::${t}`:e}function Aa(e){return e===Y?Mn:Xr}function vd(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??Mn,flowId:e.flowId}}function $a(e,t){let r=Aa(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function Pd(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return wo.filter(r=>t.has(r)).map(r=>({scope:r,label:Ln[r].label,pathHint:Ln[r].pathHint,items:t.get(r)??[]}))}function Ed(e){let t=r=>{if(!r)return 1/0;let n=wo.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function Cd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Hr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[Hr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(Hr(g.name,g.author?.name))??h.get(g.name),v=w?.version,O=!!v&&!!g.version&&Re(g.version,v);return {...g,updateAvailable:O,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Hr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?bd(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>vd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>$a(f,f.catalogItem)):a.map(f=>$a(f,f.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(f=>{let h=f.type??"bundle";if(!n.types.has(h))return false;let g=f.origin??"internal";return n.origins.has(g)}),[l,n]),u=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${u} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>{let f=new Map(e.map(g=>[Hr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(Hr(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Ma(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=S(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Zc();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,b(I.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{u();},[u,c]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:u}}function Td(){return {items:pe(t=>t.installedItems)}}var Sw=x("catalog");function Ad(){let e=S(W=>W.bundleInstallFlow),t=S(W=>W.activeTab),r=S(W=>W.notification),n=S(W=>W.loading),o=S(W=>W.loadingMessage),s=S(W=>W.downloadProgress),i=S(W=>W.downloadTotal),a=S(W=>W.catalogError),l=S(W=>W.setCatalogError),c=S(W=>W.catalogFilters),u=Fe(W=>W.query),{catalog:d,isLoading:m,error:p,refetch:f}=Ma(),{items:h}=Td(),g=pe(W=>W.loadFromDisk),{items:w,emptyMessage:v,getSelectedCatalogItem:O,outdatedCount:_}=Cd({catalog:d,installedItems:h,activeTab:t,catalogFilters:c,searchQuery:u}),{actionMenuOpen:E,closeMenu:M,selectedIndex:K,clampIndex:H,filteredItems:ue}=ad({listLength:w.length}),T=ue(w),U=useMemo(()=>t!=="installed"&&t!=="updates"?T:Ed(T),[t,T]),G=useMemo(()=>t==="installed"||t==="updates"?Pd(U):[],[t,U]),B=U[K]??null,be=useMemo(()=>O(B),[O,B]),{notify:Nt}=cd(),{handleInstall:$,handleUninstall:N,handleToggleStatus:z,handleUpdate:A,handleBatchUpdate:R,handleMcpConfigUninstall:V}=yd({selectedItem:B,selectedCatalogItem:be,items:w,closeMenu:M,clampIndex:H,notify:Nt}),{handleBundleInstallStart:at,handleBundleDetailConfirm:Wr,handleBundleDetailBack:Lm,handleBundleInstallComplete:Rm}=Id({closeMenu:M,notify:Nt}),_m=useCallback(()=>R(U),[R,U]);return useEffect(()=>{g();},[]),useEffect(()=>{H(U.length);},[U.length,H]),useEffect(()=>{p&&(Sw.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(an,{}),jsx(mc,{outdatedCount:_}),t==="marketplaces"&&lr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(nd,{})}):jsx(Ac,{filteredItems:U,groups:G,emptyMessage:v,onBatchUpdate:_m}),(n||m)&&jsxs(Fragment,{children:[jsx(us,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(ps,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(ms,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx($c,{message:r.message,type:r.type}),E&&B&&(t==="discover"?be?.type==="bundle"?e?.phase==="installing"?jsx(Vu,{bundle:e.bundle,onComplete:Rm}):jsx(Mu,{itemName:B.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>at(B.name,B.flowId),onConfirm:Wr,onClose:e?.phase==="detail"?Lm:M}):jsx(Au,{itemName:B.name,itemType:be?.type,onInstall:$,onClose:M}):B.type==="mcp"?jsx(Nu,{itemName:B.name,itemScope:B.scope??"user",onUninstall:V,onClose:M}):jsx(_u,{itemName:B.name,itemScope:B.scope??"user",itemStatus:B.status??"enabled",updateAvailable:B.updateAvailable??false,catalogVersion:be?.version,onUninstall:N,onToggleStatus:W=>z(W),onUpdate:A,onClose:M})),jsx(cs,{})]})}var L=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(pe.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));var Pw=3;function Md(){let e=L(u=>u.setStarterKits),t=L(u=>u.setIsLoadingStarterKits),r=L(u=>u.setStarterKitsError),n=L(u=>u.setPluginStatus),o=L(u=>u.setPluginDownloadProgress),s=L(u=>u.setStep),i=L(u=>u.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let u=await Is();e(u);}catch(u){r(u instanceof Error?u.message:String(u));}finally{t(false);}},[t,r,e]);useEffect(()=>{pe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),c=useCallback(async()=>{let u=L.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of u){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=Pw;h++)try{await $e(m.name,{onDownloadProgress:(g,w)=>{let v=Date.now();(v-l.current>100||g>=w)&&(l.current=v,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof je){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),b(I.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:X().interfaceType}).catch(()=>{}));}let d=Lr();Mr("summary_review"),b(I.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),pe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:c}}var So={cursorDelta:0,confirm:false,back:false};function Ld(e,t){return t.upArrow?{...So,cursorDelta:-1}:t.downArrow?{...So,cursorDelta:1}:t.escape?{...So,back:true}:t.return?{...So,confirm:true}:So}var Ew={cursorDelta:0,select:false};function Rd(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:Ew}var _d=$g.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var Ua=5;function Dd({onRetry:e}){let t=L(u=>u.starterKits),r=L(u=>u.selectedStarterKitIndex),n=L(u=>u.isLoadingStarterKits),o=L(u=>u.starterKitsError);if(n)return jsx(us,{message:"Loading Starter Kits..."});if(o)return jsx(ms,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(ln,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Ua/2)),i=Math.min(t.length,s+Ua);i===t.length&&(s=Math.max(0,i-Ua));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(_d,{starterKit:u,isSelected:s+d===r},u.slug)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var Nd=$g.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var ja=8;function Ud(){let e=L(u=>u.selectedStarterKit),t=L(u=>u.plugins),r=L(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,b(I.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,s=Math.max(0,r-Math.floor(ja/2)),i=Math.min(t.length,s+ja);i===t.length&&(s=Math.max(0,i-ja));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(Nd,{plugin:u,isCursor:s+d===r},u.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var _w=["Retry failed","Continue anyway"];function Bd({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(ps,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Fd({onComplete:e,onRetry:t}){let r=L(c=>c.plugins),n=L(c=>c.step),o=L(c=>c.successCount),s=L(c=>c.failedCount),i=L(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(Bd,{name:c.name,status:c.status,error:c.error,downloadProgress:c.downloadProgress,downloadTotal:c.downloadTotal},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(Bd,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:_w.map((c,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",c]})},c))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function jd(){let e=L(T=>T.step),t=L(T=>T.starterKits),r=L(T=>T.selectedStarterKitIndex),n=L(T=>T.setSelectedStarterKitIndex),o=L(T=>T.selectStarterKit),s=L(T=>T.plugins),i=L(T=>T.pluginCursorIndex),a=L(T=>T.setPluginCursorIndex),l=L(T=>T.setStep),c=L(T=>T.summaryActionIndex),u=L(T=>T.setSummaryActionIndex),d=L(T=>T.failedCount),m=L(T=>T.resetForRetry),p=L(T=>T.goBackToList),f=S(T=>T.setScreen),h=S(T=>T.setFocus),g=S(T=>T.focus),w=Xe(T=>T.setJustAuthenticated),v=Xe(T=>T.justAuthenticated),{loadStarterKits:O,installSelected:_}=Md(),E=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),E.current||(E.current=true,Mr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let M=useCallback(async()=>{let T=L.getState().selectedStarterKit;if(T){let G=await ae();G&&await Bt({...G,starterKit:T.slug});}b(I.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:Lr()}).catch(()=>{});let{successCount:U}=L.getState();b(I.CLI_ONBOARDING_COMPLETED,{duration_ms:Ft(),tools_installed_count:U}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),K=useCallback(()=>{m(),_();},[m,_]),H=useCallback(()=>{O();},[O]),ue=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((T,U)=>{if(U.escape)Xo("esc"),ue();else if(U.upArrow&&r>0)n(r-1);else if(U.downArrow&&r<t.length-1)n(r+1);else if(U.return&&t.length>0){let G=Lr();o(t[r]),Mr("kit_display"),b(I.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:G}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((T,U)=>{let G=Ld(T,U);if(G.cursorDelta!==0){let B=i+G.cursorDelta;B>=0&&B<s.length&&a(B);}if(G.confirm){let B=L.getState().selectedStarterKit;B&&(async()=>(await ae())?.starterKit!==B.slug&&b(I.CLI_KIT_ACCEPTED,{bundle_slug:B.slug}).catch(()=>{}))();let be=Lr();Mr("kit_confirmation"),b(I.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:be}).catch(()=>{});let Nt=Lr();Mr("tool_installation"),b(I.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Nt}).catch(()=>{}),l("installing"),_();}if(G.back){let B=L.getState().selectedStarterKit;B&&b(I.CLI_KIT_REJECTED,{bundle_slug:B.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((T,U)=>{if(d===0)return;let G=Rd(T,U);if(G.cursorDelta!==0){let B=c+G.cursorDelta;B>=0&&B<=1&&u(B);}G.select&&(c===0?K():M());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(an,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!v&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(Dd,{onRetry:H}),e==="starterKitDetail"&&jsx(Ud,{}),(e==="installing"||e==="summary")&&jsx(Fd,{onComplete:M,onRetry:K})]}),jsx(cs,{})]})}var Hd=null;function Jd(){return Hd}async function Xs(){let t=Dr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=re.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Gd(n);(o||s)&&await dt({...r,installedVersion:o,installMethod:s});}}async function Gd(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Et(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Cn(e){let t=await Promise.all(e.map(r=>Nw(r)));return Hd=t,t}async function Nw(e){let t=Kd(e.versionCommand);t==="permission-denied"&&(Uw(e.versionCommand[0]),t=Kd(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Et(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!qe(e.alias)){let{installedVersion:l,installMethod:c}=await Gd(e);await dt({alias:e.alias,name:e.name,installedVersion:l,installMethod:c,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Kd(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function Uw(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=Se__default.realpathSync(r),{mode:o}=Se__default.statSync(n);Se__default.chmodSync(n,o|73);}catch{}}function jw(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function Yd(e,t){let[r,n]=useState(()=>jw(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),c=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,h=m.upArrow||d==="[A",g=m.downArrow||d==="[B";if(h||g)h&&p>0?s(p-1):g&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let v=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),O=w.availableStrategies[(v+1)%w.availableStrategies.length];n(_=>_.map(E=>E.module.alias===w.module.alias?{...E,selectedStrategy:O}:E));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Qd({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Yd(e,r==="moduleSetup"),c=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),u=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),c();},[l,t,c]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let h=f===a,g=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",g," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:h?"cyan":void 0,children:[h?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",g]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(Ye,{itemName:m,actions:d,onAction:u,onClose:c})]})}var Gw=/^https?:\/\/.+/;function ep({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,c)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||c.return){e(null);return}}if(t==="input"){if(c.escape){a.current="",o(""),r("confirm");return}if(c.return){let u=a.current.trim();u.length>0&&Gw.test(u)?(i(false),e(u)):u.length>0&&i(true);return}if(c.backspace||c.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!c.ctrl&&!c.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function Ww(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function np(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=Ww(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await dr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:c,skippedCount:u}}function op({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function lp({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:c}=np(e,t),u=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Or().catch(()=>{}),n("list");let w=ne().some(v=>v.name===se);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!u&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,u,p]),useInput((w,v)=>{v.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,h=a-f,g=[];return h>0&&g.push(jsxs(Text,{color:"green",children:[h," installed"]},"i")),f>0&&g.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&g.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),c>0&&g.push(jsxs(Text,{dimColor:true,children:[c," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(op,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,v,O)=>(O>0&&w.push(jsx(Text,{children:" | "},`sep-${O}`)),w.push(v),w),[])}),jsx(Box,{paddingX:1,children:l>0||u?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function up(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),c=S(p=>p.setScreen),u=useCallback(p=>{if(ql(p)){Or().catch(()=>{}),l("list");let h=ne().some(g=>g.name===se);c(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,c]);useEffect(()=>{let p=Jd();if(p){u(p);return}Cn(re).then(u).catch(()=>{n([]),t("selection");});},[u]);let d=useCallback(p=>{s(p);let f=p.some(h=>h.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Qd,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(ep,{onConfirm:m}),e==="installation"&&jsx(lp,{confirmedItems:o,customUrl:i})]})}var oS=x("ClaudeMdSuggestion"),sS=[`Install ${se}`,"Skip for now"],iS=["Retry","Skip for now"];function mp(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{b(I.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,b(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await $e(se),o("installed");}catch(m){if(m instanceof je){o("installed");return}oS.warn(`Failed to install ${se}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?iS:sS;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?c():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),u()):c());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(an,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(pp,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ku,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",se,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",se," 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:["/",se]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",se]}),jsx(pp,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function pp({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var uS=promisify(execFile),ei="@ciandt-flow/cli";async function fp(){let e=le;if(Ta.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ei};try{let t=await fetch(`https://registry.npmjs.org/${ei}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:ei}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:ei}}}async function ti(e){try{return await uS(jt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function dS(e){let t=qe(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Et(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await dt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function gp(e){let t=await dS(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function hp(e,t){let r=qe(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Et(r.installMethod).update(e,t.currentVersion??"");return o.success?(await dt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function yp(e){let r=qe(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function wp(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...re.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([fp(),Cn(re),Promise.all(re.map(l=>gp(l)))]);if(Xs(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await ti(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=re.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await hp(c,l);u.success?r(l.moduleAlias,{status:"updated",detail:`v${u.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:yp(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await Or(),t(l=>({...l,outcome:"done"}));}catch{await Or(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function yS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Ku,{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 wS({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 Sp(){let{outcome:e,items:t}=wp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=ne().some(i=>i.name===se);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(yS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(wS,{outcome:e})})]})}var bS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},xp=10;function Ip(){let[e,t]=useState(Si());useEffect(()=>xl(()=>{t([...Si()]);}),[]);let r=e.slice(-xp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",xp,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:bS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var CS=x("app"),TS={auth:sc,starterKitSetup:jd,moduleSetup:up,claudeMdSuggestion:mp,verify:Sp,main:Ad};function Pp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Wn(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Ep(){b(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:Ft(),interface:"tui"}).catch(()=>{});}async function Tp(){let e=await ae();if(e&&zl()&&await ir()){let{clientSecret:n,...o}=e;Xe.getState().setCredentials(o),Ep(),Wn(e);return}if(!e){Pp();return}try{await ar();}catch(n){CS.debug(`Token validation failed: ${String(n)}`),Pp();return}Ep();let{clientSecret:t,...r}=e;Xe.getState().setCredentials(r),Wn(e);}function kp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=TS[r],{pendingExit:o}=Vl(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(Ip,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function Qa(e,t={}){let r=Yo({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Zo(r),await Bt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var xt=x("auth");function $p(){Be.clearFallbackFile(),Ho();}var kS=3,Ap=3,Mp=` \u2139 The data collected during setup is used solely to improve
|
|
116
|
+
[y/N] `))return Cs.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:Xa({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await we(r);return n?.stop(),o.exitCode!==0?(io(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(Qu(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),io(t,{name:e,action:"remove",message:H(o)}),1}}function rd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=I("pluginHandlers"),a=useRef(0),l=S(T=>T.setLoading),c=S(T=>T.setDownloadProgress),{install:u,uninstall:d,toggle:m,update:p}=Yu(),f=async(T,L,F)=>{l(true,T),n();try{await L(),o(r.length),s(F,"success");}catch(V){let R=V instanceof Error?V.message:"Something went wrong";i.error(`[withLoading] ${T} failed: ${R}`),s(R,"error");}finally{l(false);}};return {handleInstall:(T,L)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>u(t,{scope:T,...L!==void 0?{providerId:L}:{},onDownloadProgress:(F,V)=>{let R=Date.now();(R-a.current>100||F>=V)&&(a.current=R,c(F,V));}}),"\u2713 Installed successfully"));},handleUninstall:T=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,T),"\u2713 Uninstalled");},handleToggleStatus:T=>{if(!e)return;let L=e.status==="enabled";f(L?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,T),L?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let T=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${T}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${T}`,"success");}catch(F){if(F instanceof ar)s(F.message,"info");else {let V=F instanceof Error?F.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${V}`),s(V,"error");}}finally{l(false);}})();},handleBatchUpdate:T=>{if(T.length===0)return;let L=T.length;(async()=>{l(true,`Updating ${L} plugin${L>1?"s":""}...`),n();try{let V=[];for(let k of T)V.push(await p(k.name).then(()=>({status:"fulfilled",value:void 0}),j=>({status:"rejected",reason:j})));let R=V.filter(k=>k.status==="fulfilled").length,x=V.map((k,j)=>k.status==="rejected"?T[j].name:null).filter(k=>k!==null);o(r.length),x.length===0?s(`\u2713 Updated ${R}/${L} plugin${L>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),s(`Updated ${R}/${L}; failed: ${x.join(", ")}`,R>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:T=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let L=Ia(e.name,T),F=await we(L);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");ce.getState().loadFromDisk();},"\u2713 MCP removed");}}}var ao=I("api:bundle"),xn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},lo=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Jy=/^[a-zA-Z0-9_-]{1,128}$/;async function od(e,t){if(e instanceof HTTPError){let r=e.response.status;throw ao.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new xn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new lo:new Error(`Server error (${r}) \u2014 please try again later.`)}throw ao.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function sd(e){if(!Jy.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);ao.debug(`Fetching bundle by flowId "${e}"`);try{return await dt().get(`v1/use-cases/${t}`).json()}catch(r){return od(r,e)}}async function ks(e){let t=encodeURIComponent(e);ao.debug(`Fetching bundle by name "${e}"`);let r;try{r=await dt().get(`v1/use-cases/by-name/${t}`).json(),ao.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return od(n,e)}if(r.length===0)throw new xn(e);return r[0]}var Gy=I("tui:bundle-flow");function id({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:c,setBundleInstallFlow:u}=S.getState(),d=l?.trim();Gy.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),c(true,"Loading bundle..."),(d?sd(d):ks(a)).then(p=>{c(false),S.getState().actionMenuOpen&&u({phase:"detail",bundle:p});}).catch(p=>{c(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),ce.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var co=["local","project","user"],Wy=new Set(["--transport","--scope","-s"]);function ad(e){let t=e.split(/\s+/).filter(Boolean),r=t.indexOf("add");if(r===-1)return null;let n=r+1;for(;n<t.length;){let o=t[n];if(Wy.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function Ur(e,t){return t?`${e}::${t}`:e}function ba(e){return e===z?kn:Wr}function ld(e){return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??kn,flowId:e.flowId}}function va(e,t){let r=ba(e.marketplace);return {name:y(e.name),version:e.version?y(e.version):e.version,description:e.description?y(e.description):e.description,authorName:e.author?.name?y(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:t?.type??e.type??"bundle",origin:t?.origin??r}}function cd(e){let t=new Map;for(let r of e){if(!r.scope)continue;let n=t.get(r.scope)??[];n.push(r),t.set(r.scope,n);}return co.filter(r=>t.has(r)).map(r=>({scope:r,label:An[r].label,pathHint:An[r].pathHint,items:t.get(r)??[]}))}function ud(e){let t=r=>{if(!r)return 1/0;let n=co.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function dd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>Ur(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(h=>[Ur(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return t.map(h=>{let w=f.get(Ur(h.name,h.author?.name))??g.get(h.name),v=w?.version,D=!!v&&!!h.version&&Ae(h.version,v);return {...h,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(Ur(f.name,f.author?.name)))return false;if(f.type==="mcp"){let g=f.installCommand?ad(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||g&&i.has(g))return false}return true}).map(f=>ld(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>va(f,f.catalogItem)):a.map(f=>va(f,f.catalogItem)),[r,e,s,i,a]),c=useMemo(()=>l.filter(f=>{let g=f.type??"bundle";if(!n.types.has(g))return false;let h=f.origin??"internal";return n.origins.has(h)}),[l,n]),u=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${u} found for '${o}' \u2014 explore the Discover tab!`:`No ${u} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${u} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${u} found for '${o}'`:`No ${u} available in the catalog`,[r,o,u]),m=useMemo(()=>{let f=new Map(e.map(h=>[Ur(h.name,h.author?.name),h])),g=new Map(e.map(h=>[h.name,h]));return h=>h?f.get(Ur(h.name,h.authorName))??g.get(h.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:c,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Pa(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),c=S(d=>d.catalogVersion),u=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Nc();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,P(b.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:d.length}).catch(()=>{}));}catch(d){s(d instanceof Error?d:new Error(String(d))),t([]);}finally{n(false);}},[]);return useEffect(()=>{u();},[u,c]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:u}}function pd(){return {items:ce(t=>t.installedItems)}}var Zy=I("catalog");function fd(){let e=S(K=>K.bundleInstallFlow),t=S(K=>K.activeTab),r=S(K=>K.notification),n=S(K=>K.loading),o=S(K=>K.loadingMessage),s=S(K=>K.downloadProgress),i=S(K=>K.downloadTotal),a=S(K=>K.catalogError),l=S(K=>K.setCatalogError),c=S(K=>K.catalogFilters),u=Oe(K=>K.query),{catalog:d,isLoading:m,error:p,refetch:f}=Pa(),{items:g}=pd(),h=ce(K=>K.loadFromDisk),{items:w,emptyMessage:v,getSelectedCatalogItem:D,outdatedCount:U}=dd({catalog:d,installedItems:g,activeTab:t,catalogFilters:c,searchQuery:u}),{actionMenuOpen:T,closeMenu:L,selectedIndex:F,clampIndex:V,filteredItems:R}=Gu({listLength:w.length}),x=R(w),k=useMemo(()=>t!=="installed"&&t!=="updates"?x:ud(x),[t,x]),j=useMemo(()=>t==="installed"||t==="updates"?cd(k):[],[t,k]),O=k[F]??null,Ke=useMemo(()=>D(O),[D,O]),{notify:Gr}=zu(),{handleInstall:A,handleUninstall:B,handleToggleStatus:W,handleUpdate:Ie,handleBatchUpdate:wo,handleMcpConfigUninstall:Mm}=rd({selectedItem:O,selectedCatalogItem:Ke,items:w,closeMenu:L,clampIndex:V,notify:Gr}),{handleBundleInstallStart:Lm,handleBundleDetailConfirm:Rm,handleBundleDetailBack:_m,handleBundleInstallComplete:Dm}=id({closeMenu:L,notify:Gr}),Om=useCallback(()=>wo(k),[wo,k]);return useEffect(()=>{h();},[]),useEffect(()=>{V(k.length);},[k.length,V]),useEffect(()=>{p&&(Zy.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),l("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(rn,{}),jsx(Zl,{outdatedCount:U}),t==="marketplaces"&&sr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Ku,{})}):jsx(fc,{filteredItems:k,groups:j,emptyMessage:v,onBatchUpdate:Om}),(n||m)&&jsxs(Fragment,{children:[jsx(Yo,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Qo,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(es,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(gc,{message:r.message,type:r.type}),T&&O&&(t==="discover"?Ke?.type==="bundle"?e?.phase==="installing"?jsx(ku,{bundle:e.bundle,onComplete:Dm}):jsx(hu,{itemName:O.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Lm(O.name,O.flowId),onConfirm:Rm,onClose:e?.phase==="detail"?_m:L}):jsx(fu,{itemName:O.name,itemType:Ke?.type,onInstall:A,onClose:L}):O.type==="mcp"?jsx(bu,{itemName:O.name,itemScope:O.scope??"user",onUninstall:Mm,onClose:L}):jsx(Su,{itemName:O.name,itemScope:O.scope??"user",itemStatus:O.status??"enabled",updateAvailable:O.updateAvailable??false,catalogVersion:Ke?.version,onUninstall:B,onToggleStatus:K=>W(K),onUpdate:Ie,onClose:L})),jsx(qo,{})]})}var $=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(ce.getState().installedItems.map(o=>o.name));e({selectedStarterKit:r,plugins:r.plugins.map(o=>({name:o,selected:true,status:n.has(o)?"success":"pending",installed:n.has(o)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:r=>e({pluginCursorIndex:r}),setStep:r=>e({step:r}),setPluginStatus:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,status:n,error:o}:i);e({plugins:s});},setPluginDownloadProgress:(r,n,o)=>{let s=t().plugins.map(i=>i.name===r?{...i,downloadProgress:n,downloadTotal:o}:i);e({plugins:s});},setIsLoadingStarterKits:r=>e({isLoadingStarterKits:r}),setStarterKitsError:r=>e({starterKitsError:r}),setSummaryActionIndex:r=>e({summaryActionIndex:r}),computeSummary:()=>{let n=t().plugins.filter(o=>o.selected);e({successCount:n.filter(o=>o.status==="success").length,failedCount:n.filter(o=>o.status==="failed").length});},resetForRetry:()=>{let r=t().plugins.map(n=>n.status==="failed"?{...n,status:"pending",error:void 0}:n);e({plugins:r,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));var nw=3;function hd(){let e=$(u=>u.setStarterKits),t=$(u=>u.setIsLoadingStarterKits),r=$(u=>u.setStarterKitsError),n=$(u=>u.setPluginStatus),o=$(u=>u.setPluginDownloadProgress),s=$(u=>u.setStep),i=$(u=>u.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let u=await ls();e(u);}catch(u){r(u instanceof Error?u.message:String(u));}finally{t(false);}},[t,r,e]);useEffect(()=>{ce.getState().loadFromDisk(),a();},[a]);let l=useRef(0),c=useCallback(async()=>{let u=$.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of u){n(m.name,"installing"),l.current=0;let p="",f=false;for(let g=1;g<=nw;g++)try{await Te(m.name,{onDownloadProgress:(h,w)=>{let v=Date.now();(v-l.current>100||h>=w)&&(l.current=v,o(m.name,h,w));}}),n(m.name,"success"),f=!0;break}catch(h){if(h instanceof Ne){n(m.name,"success"),f=true;break}p=h instanceof Error?h.message:"Unknown error";}f||(n(m.name,"failed",p),P(b.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:J().interfaceType}).catch(()=>{}));}let d=kr();Cr("summary_review"),P(b.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),ce.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:c}}var uo={cursorDelta:0,confirm:false,back:false};function yd(e,t){return t.upArrow?{...uo,cursorDelta:-1}:t.downArrow?{...uo,cursorDelta:1}:t.escape?{...uo,back:true}:t.return?{...uo,confirm:true}:uo}var ow={cursorDelta:0,select:false};function wd(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:ow}var Sd=cg.memo(function({starterKit:t,isSelected:r}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":"\u25CB "}),jsx(Text,{bold:r,color:r?"cyan":"white",children:y(t.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",t.plugins.length," ",t.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:y(t.description)})})]})});var Ma=5;function xd({onRetry:e}){let t=$(u=>u.starterKits),r=$(u=>u.selectedStarterKitIndex),n=$(u=>u.isLoadingStarterKits),o=$(u=>u.starterKitsError);if(n)return jsx(Yo,{message:"Loading Starter Kits..."});if(o)return jsx(es,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(nn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Ma/2)),i=Math.min(t.length,s+Ma);i===t.length&&(s=Math.max(0,i-Ma));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(Sd,{starterKit:u,isSelected:s+d===r},u.slug)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var bd=cg.memo(function({plugin:t,isCursor:r}){return jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:r,color:r?"cyan":"white",children:[" ",y(t.name)]}),t.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});var _a=8;function vd(){let e=$(u=>u.selectedStarterKit),t=$(u=>u.plugins),r=$(u=>u.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,P(b.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:t.length}).catch(()=>{}));},[e,t.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let o=t.filter(u=>u.installed).length,s=Math.max(0,r-Math.floor(_a/2)),i=Math.min(t.length,s+_a);i===t.length&&(s=Math.max(0,i-_a));let a=t.slice(s,i),l=s,c=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((u,d)=>jsx(bd,{plugin:u,isCursor:s+d===r},u.name)),c>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",c," more below"]})})]})}var mw=["Retry failed","Continue anyway"];function Pd({name:e,status:t,error:r,downloadProgress:n,downloadTotal:o}){let s=y(e);return t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Qo,{received:n,total:o})})]}):t==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",s]})}):t==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",s]}),r&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(r)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",s]})})}function Ed({onComplete:e,onRetry:t}){let r=$(c=>c.plugins),n=$(c=>c.step),o=$(c=>c.successCount),s=$(c=>c.failedCount),i=$(c=>c.summaryActionIndex),a=r.filter(c=>c.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let c=setTimeout(e,1500);return ()=>clearTimeout(c)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(c=>jsx(Pd,{name:c.name,status:c.status,error:c.error,downloadProgress:c.downloadProgress,downloadTotal:c.downloadTotal},c.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(c=>c.status==="failed").map(c=>jsx(Pd,{name:c.name,status:c.status,error:c.error},c.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:mw.map((c,u)=>jsx(Box,{children:jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",c]})},c))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Td(){let e=$(x=>x.step),t=$(x=>x.starterKits),r=$(x=>x.selectedStarterKitIndex),n=$(x=>x.setSelectedStarterKitIndex),o=$(x=>x.selectStarterKit),s=$(x=>x.plugins),i=$(x=>x.pluginCursorIndex),a=$(x=>x.setPluginCursorIndex),l=$(x=>x.setStep),c=$(x=>x.summaryActionIndex),u=$(x=>x.setSummaryActionIndex),d=$(x=>x.failedCount),m=$(x=>x.resetForRetry),p=$(x=>x.goBackToList),f=S(x=>x.setScreen),g=S(x=>x.setFocus),h=S(x=>x.focus),w=Ge(x=>x.setJustAuthenticated),v=Ge(x=>x.justAuthenticated),{loadStarterKits:D,installSelected:U}=hd(),T=useRef(false);useEffect(()=>{e==="starterKitList"?(g("starterKitList"),T.current||(T.current=true,Cr("bundle_selection"))):g(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,g]);let L=useCallback(async()=>{let x=$.getState().selectedStarterKit;if(x){let j=await q();j&&await Nt({...j,starterKit:x.slug});}P(b.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:kr()}).catch(()=>{});let{successCount:k}=$.getState();P(b.CLI_ONBOARDING_COMPLETED,{duration_ms:Bt(),tools_installed_count:k}).catch(()=>{}),w(false),g("verify"),f("verify");},[w,g,f]),F=useCallback(()=>{m(),U();},[m,U]),V=useCallback(()=>{D();},[D]),R=useCallback(()=>{g("verify"),f("verify");},[g,f]);return useInput((x,k)=>{if(k.escape)Ho("esc"),R();else if(k.upArrow&&r>0)n(r-1);else if(k.downArrow&&r<t.length-1)n(r+1);else if(k.return&&t.length>0){let j=kr();o(t[r]),Cr("kit_display"),P(b.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:j}).catch(()=>{});}},{isActive:h==="starterKitList"}),useInput((x,k)=>{let j=yd(x,k);if(j.cursorDelta!==0){let O=i+j.cursorDelta;O>=0&&O<s.length&&a(O);}if(j.confirm){let O=$.getState().selectedStarterKit;O&&(async()=>(await q())?.starterKit!==O.slug&&P(b.CLI_KIT_ACCEPTED,{bundle_slug:O.slug}).catch(()=>{}))();let Ke=kr();Cr("kit_confirmation"),P(b.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:Ke}).catch(()=>{});let Gr=kr();Cr("tool_installation"),P(b.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:Gr}).catch(()=>{}),l("installing"),U();}if(j.back){let O=$.getState().selectedStarterKit;O&&P(b.CLI_KIT_REJECTED,{bundle_slug:O.slug}).catch(()=>{}),p();}},{isActive:h==="starterKitDetail"}),useInput((x,k)=>{if(d===0)return;let j=wd(x,k);if(j.cursorDelta!==0){let O=c+j.cursorDelta;O>=0&&O<=1&&u(O);}j.select&&(c===0?F():L());},{isActive:h==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(rn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!v&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(xd,{onRetry:V}),e==="starterKitDetail"&&jsx(vd,{}),(e==="installing"||e==="summary")&&jsx(Ed,{onComplete:L,onRetry:F})]}),jsx(qo,{})]})}var Sw=I("moduleState");function Ns(){let e=process.env.FLOW_HOME??fe__default.join(be__default.homedir(),".flow");return fe__default.join(e,"modules.json")}var xw={retries:5,minTimeout:50};async function Cd(e,t){ge__default.mkdirSync(fe__default.dirname(e),{recursive:true});let r=await Wg.lock(e+".lock",{realpath:false,retries:xw});try{return await t()}finally{await r();}}function kd(){let e=Ns();if(!ge__default.existsSync(e))return [];try{let t=JSON.parse(ge__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Sw.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ge__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ge__default.rmSync(e,{force:true}),[]}}function jr(){return kd()}function Ad(e){let t=Ns();ge__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ge__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8"}),process.platform!=="win32"&&ge__default.chmodSync(r,384),ge__default.renameSync(r,t);}function rt(e){return jr().find(t=>t.alias===e)??null}async function gt(e){let t=Ns();await Cd(t,async()=>{let r=kd(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Ad(r);});}async function Kr(){let e=Ns();ge__default.existsSync(e)||await Cd(e,async()=>{ge__default.existsSync(e)||Ad([]);});}function Pw(){return te.filter(e=>e.platforms[process.platform]?.status==="supported")}function Md(e){let t=Pw();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var $d={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=fe__default.join(be__default.homedir(),".claude","settings.json"),r=ge__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=[];if(e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push(["flow-ai-obs","auth","login","--client-id",r,"--client-secret",n,"--tenant",o]);}return t.push(e.customUrl?["flow-ai-obs","init","--custom-url",e.customUrl]:["flow-ai-obs","init","--no-interactive"]),t},onDemand:null,mode:"non-interactive"}},Ew={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},te=sr()?[$d,Ew]:[$d];var kw=promisify(execFile);function hr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function $t(e){let t=process.platform==="win32"?"where":"which";try{return await kw(t,[e]),!0}catch{return false}}function Gt(){return process.platform==="win32"?"npm.cmd":"npm"}var Ld=promisify(execFile),Bs=class{type="npm";async isAvailable(){return $t("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=hr(t,"npm");if(!r)return null;try{let{stdout:n}=await Ld(Gt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=hr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await Ld(Gt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var Us=promisify(execFile),Rw=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Fs=class{type="homebrew";async isAvailable(){return $t("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=hr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=hr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await Us("brew",["tap",o.tap]),await Us("brew",["trust",o.tap])),await Us("brew",[r,o.formula]),{success:!0,version:await this.getVersionByFormula(o.formula)??void 0,method:"homebrew",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:s,message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}async getVersionByFormula(t){try{let{stdout:r}=await Us("brew",["list","--versions",t]),n=r.trim().match(Rw);return n?n[2]:null}catch{return null}}};var bn=promisify(execFile),_d=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Dd(){let e=process.env.FLOW_HOME??fe__default.join(be__default.homedir(),".flow");return fe__default.join(e,"bin")}var js=class{type="curl";async isAvailable(){return $t("curl")}async install(t){let r=Date.now(),n=hr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=fe__default.join(Dd(),fe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await bn(n,["--version"]),s=o.match(_d);if(s)return s[1]}catch{}return null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(t,r,n,o){if(!r)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${n.alias})`},durationMs:Date.now()-o};let s=fe__default.join(be__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await bn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ge__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ge__default.chmodSync(s,448),await bn("bash",[s]),{success:!0,version:await this.getInstalledVersion(n)??void 0,method:"curl",durationMs:Date.now()-o}}catch(i){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-o}}finally{try{ge__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=Dd(),i=fe__default.join(s,fe__default.basename(n.binaryName)),a=false;try{if(ge__default.mkdirSync(s,{recursive:!0}),a=!0,await bn("curl",["-L","--fail","-o",i,t]),r){let c=await this.validateChecksum(i,r);if(!c.valid)return ge__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:c.message},durationMs:Date.now()-o}}ge__default.chmodSync(i,493);let l=null;try{let{stdout:c}=await bn(i,["--version"]),u=c.match(_d);l=u?u[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ge__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=fe__default.join(be__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await bn("curl",["-L","--fail","-o",n,r]);let o=ge__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ge__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{ge__default.unlinkSync(n);}catch{}}}};var xe=I("moduleInstaller");function Lt(e){switch(e){case "npm":return new Bs;case "homebrew":return new Fs;case "curl":return new js}}async function fo(e,t,r){try{await P(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:r.code,error_message:r.message,trigger:t});}catch(n){xe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function vn(e,t,r,n){let o=Date.now(),s=e.platforms[process.platform];if(!s)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-o};if(s.status==="experimental"){xe.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let c={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await fo(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(s.status!=="supported"){let c={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await fo(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}if(!s.strategies.some(c=>c.type===r)){let c={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await fo(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}let i=Lt(r),a=false;try{a=await i.isAvailable();}catch(c){xe.warn(`${r} availability check failed: ${String(c)}`);}if(!a){let c={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await fo(e,t,c),{success:false,error:c,durationMs:Date.now()-o}}try{await P(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:t});}catch(c){xe.warn(`Failed to emit install started event: ${String(c)}`);}let l;try{l=await i.install(e);}catch(c){let u=c instanceof Error?c.message:String(c);xe.warn(`${r} install threw: ${u}`),l={success:false,error:{code:"INSTALL_THREW",message:u},durationMs:Date.now()-o};}if(l.success){await gt({alias:e.alias,name:e.name,installedVersion:l.version??null,installMethod:l.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await P(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:l.version??"unknown",duration_ms:l.durationMs,os:process.platform,trigger:t});}catch(u){xe.warn(`Failed to emit install completed event: ${String(u)}`);}let c=await Bw(e,t,n);return c?{...l,pendingInteractiveSetup:c}:e.configCheck&&!e.configCheck()?{...l,configCheckFailed:true}:l}return await fo(e,t,l.error??{code:"UNKNOWN",message:"unknown error"}),l}async function Bw(e,t,r){if(!e.postInstall)return null;let n=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(n==null)return null;let o;if(typeof n=="function"){let s=await q(),i={credentials:s?{clientId:s.clientId,clientSecret:s.clientSecret,tenant:s.tenant}:null,customUrl:r??null};try{o=n(i);}catch(a){return xe.warn(`postInstall function threw: ${String(a)}`),null}}else o=n;if(o.length===0)return null;if((e.postInstall.mode??"non-interactive")==="interactive")return o[0]??null;for(let s=0;s<o.length;s++){let i=o[s];if(i.length===0)continue;let a=spawnSync(i[0],i.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(a.status!==0){xe.warn(`postInstall "${i.join(" ")}" exited with status ${a.status??"null"}`),a.stderr&&xe.warn(a.stderr);let l=o.slice(s+1).filter(c=>c.length>0);l.length>0&&xe.warn(`continuing with remaining postInstall steps: ${l.map(c=>c.join(" ")).join(", ")}`);}}return null}async function Ks(e,t){let r=Date.now(),n=rt(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Lt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await P(b.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:oe,trigger:"command"});}catch(a){xe.warn(`Failed to emit update started event: ${String(a)}`);}let i;try{i=await o.update(e,s);}catch(a){let l=a instanceof Error?a.message:String(a);xe.warn(`${n.installMethod} update threw: ${l}`),i={success:false,error:{code:"UPDATE_THREW",message:l},durationMs:Date.now()-r};}if(i.success)if(await gt({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await P(b.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:i.version??"unknown",duration_ms:i.durationMs,os:process.platform,trigger:"command"});}catch(a){xe.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await P(b.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){xe.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await P(b.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:i.error?.code??"UNKNOWN",error_message:i.error?.message??"unknown error",trigger:"command"});}catch(a){xe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var Bd=null;function Ud(){return Bd}async function Vs(){let t=jr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=te.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await Fd(n);(o||s)&&await gt({...r,installedVersion:o,installMethod:s});}}async function Fd(e){let t=e.platforms[process.platform];if(t?.status!=="supported")return {installedVersion:null,installMethod:null};for(let r of t.strategies)if(r.type!=="curl")try{let o=await Lt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function Pn(e){let t=await Promise.all(e.map(r=>Uw(r)));return Bd=t,t}async function Uw(e){let t=Od(e.versionCommand);t==="permission-denied"&&(Fw(e.versionCommand[0]),t=Od(e.versionCommand));let n=t==="installed"&&(!e.configCheck||e.configCheck()),o=e.platforms[process.platform],s=o?.status==="supported"?o.strategies:[],a=(await Promise.all(s.map(async l=>{try{return await Lt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!rt(e.alias)){let{installedVersion:l,installMethod:c}=await Fd(e);await gt({alias:e.alias,name:e.name,installedVersion:l,installMethod:c,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Od(e){if(e.length===0)return "not-found";try{let t=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return t.status===0?"installed":t.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function Fw(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=ge__default.realpathSync(r),{mode:o}=ge__default.statSync(n);ge__default.chmodSync(n,o|73);}catch{}}function Vw(e){return e.filter(t=>t.module.platforms[process.platform]?.status==="supported").filter(t=>!t.alreadyInstalled).map(t=>({module:t.module,alreadyInstalled:t.alreadyInstalled,checked:!t.alreadyInstalled&&(t.availableStrategies.length>0||t.module.required===true),selectedStrategy:t.availableStrategies[0]??null,availableStrategies:t.availableStrategies}))}function Jd(e,t){let[r,n]=useState(()=>Vw(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),c=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,g=m.upArrow||d==="[A",h=m.downArrow||d==="[B";if(g||h)g&&p>0?s(p-1):h&&p<f.length-1&&s(p+1);else if(d===" "){let w=f[p];w&&!w.module.required&&l(w.module.alias);}else if(m.tab){let w=f[p];if(w&&w.availableStrategies.length>1){let v=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(v+1)%w.availableStrategies.length];n(U=>U.map(T=>T.module.alias===w.module.alias?{...T,selectedStrategy:D}:T));}}},{isActive:t});let u=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:c,confirmedItems:u}}function Wd({probeResults:e,onConfirm:t}){let r=S(p=>p.focus),n=S(p=>p.actionMenuOpen),o=S(p=>p.setActionMenuOpen),s=S(p=>p.setFocus),{items:i,focusedIndex:a,confirmedItems:l}=Jd(e,r==="moduleSetup"),c=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),u=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),c();},[l,t,c]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let g=f===a,h=y(p.module.name);return p.availableStrategies.length===0?jsxs(Box,{children:[jsxs(Text,{dimColor:true,children:[" [ ] ",h," "]}),jsx(Text,{dimColor:true,children:"\u2014 no installer available"})]},p.module.alias):jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:g?"cyan":void 0,children:[g?"\u25B6":" ",p.checked?" [\u2713] ":" [ ] ",h]}),p.module.required&&jsx(Text,{dimColor:true,children:" (required)"}),jsxs(Text,{dimColor:true,children:[" ",p.selectedStrategy??""]}),p.availableStrategies.length>1&&jsxs(Text,{dimColor:true,children:[" ","(",p.availableStrategies.indexOf(p.selectedStrategy??p.availableStrategies[0])+1,"/",p.availableStrategies.length," \u2194)"]})]}),p.module.description&&jsx(Box,{paddingLeft:6,children:jsx(Text,{dimColor:true,children:y(p.module.description)})})]},p.module.alias)})}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Space toggle \xB7 Tab change method \xB7 Enter confirm"})}),n&&jsx(ze,{itemName:m,actions:d,onAction:u,onClose:c})]})}var zw=/^https?:\/\/.+/;function zd({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,c)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||c.return){e(null);return}}if(t==="input"){if(c.escape){a.current="",o(""),r("confirm");return}if(c.return){let u=a.current.trim();u.length>0&&zw.test(u)?(i(false),e(u)):u.length>0&&i(true);return}if(c.backspace||c.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!c.ctrl&&!c.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function qw(e){let t=e.module.platforms[process.platform];return (t?.status==="supported"?t.strategies:[]).map(n=>n.type==="npm"?`npm install -g ${n.package}`:n.type==="homebrew"?`brew install ${n.formula}`:"curl (see docs)").join(" or ")}function Yd(e,t){let[r,n]=useState(()=>e.map(d=>({alias:d.module.alias,name:d.module.name,status:"pending"}))),[o,s]=useState(false),i=useCallback((d,m)=>{n(p=>p.map(f=>f.alias===d?{...f,...m}:f));},[]),a=useCallback(async()=>{for(let d of e){let m=qw(d);if(!d.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";i(d.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}i(d.module.alias,{status:"installing"});try{let p=await vn(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:c,skippedCount:u}}function Zd({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",t," \u2014 Installing..."]})]});if(e.status==="installed"){let r=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:r?"red":"green",children:[r?"\u2717":"\u2713"," ",t]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:y(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",t]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",y(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",y(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",t," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",t]})})}function rp({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:c}=Yd(e,t),u=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Kr().catch(()=>{}),n("list");let w=Q().some(v=>v.name===re);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!u&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,u,p]),useInput((w,v)=>{v.return&&p();},{isActive:i});let f=o.filter(w=>w.pendingSetupCommand).length,g=a-f,h=[];return g>0&&h.push(jsxs(Text,{color:"green",children:[g," installed"]},"i")),f>0&&h.push(jsxs(Text,{color:"red",children:[f," needs setup"]},"p")),l>0&&h.push(jsxs(Text,{color:"red",children:[l," failed"]},"f")),c>0&&h.push(jsxs(Text,{dimColor:true,children:[c," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(Zd,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:h.reduce((w,v,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(v),w),[])}),jsx(Box,{paddingX:1,children:l>0||u?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function op(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),c=S(p=>p.setScreen),u=useCallback(p=>{if(Md(p)){Kr().catch(()=>{}),l("list");let g=Q().some(h=>h.name===re);c(g?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,c]);useEffect(()=>{let p=Ud();if(p){u(p);return}Pn(te).then(u).catch(()=>{n([]),t("selection");});},[u]);let d=useCallback(p=>{s(p);let f=p.some(g=>g.module.alias==="metrics");t(f?"customUrl":"installation");},[]),m=useCallback(p=>{a(p),t("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Wd,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(zd,{onConfirm:m}),e==="installation"&&jsx(rp,{confirmedItems:o,customUrl:i})]})}var iS=I("ClaudeMdSuggestion"),aS=[`Install ${re}`,"Skip for now"],lS=["Retry","Skip for now"];function ap(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=$(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),c=useCallback(()=>{P(b.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),u=useCallback(async()=>{a.current+=1,P(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Te(re),o("installed");}catch(m){if(m instanceof Ne){o("installed");return}iS.warn(`Failed to install ${re}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?lS:aS;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?c():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),u()):c());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(rn,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:r>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),n==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(ip,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),n==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Cu,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",re,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",re," 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:["/",re]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),n==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",re]}),jsx(ip,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function ip({options:e,cursorIndex:t}){return jsx(Box,{flexDirection:"column",children:e.map((r,n)=>jsxs(Text,{bold:n===t,color:n===t?"cyan":void 0,children:[n===t?"\u203A ":" ",r]},r))})}var pS=promisify(execFile),zs="@ciandt-flow/cli";async function lp(){let e=oe;if(xa.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:zs};try{let t=await fetch(`https://registry.npmjs.org/${zs}/latest`);if(!t.ok)throw new Error(`Registry returned ${t.status}`);let n=(await t.json()).version;return {currentVersion:e,latestVersion:n,isOutdated:n!==e,packageName:zs}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:zs}}}async function Xs(e){try{return await pS(Gt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function mS(e){let t=rt(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Lt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await gt({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function cp(e){let t=await mS(e),r=null,n=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let s=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:n});if(!s.ok)throw new Error(`Registry returned ${s.status}`);r=(await s.json()).version;}else if(e.versionCheck.type==="github-releases"){let s=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:n});if(!s.ok)throw new Error(`GitHub returned ${s.status}`);r=(await s.json()).tag_name.replace(/^v/,"");}}catch{}let o=t!==null&&r!==null&&t!==r;return {moduleAlias:e.alias,currentVersion:t,latestVersion:r,isOutdated:o}}async function up(e,t){let r=rt(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Lt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await gt({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function dp(e){let r=rt(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function pp(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...te.map(n=>({id:n.alias,label:n.name,status:"pending"}))]}),r=useCallback((n,o)=>{t(s=>({...s,items:s.items.map(i=>i.id===n?{...i,...o}:i)}));},[]);return useEffect(()=>{async function n(){try{let[o,s,i]=await Promise.all([lp(),Pn(te),Promise.all(te.map(l=>cp(l)))]);if(Vs(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await Xs(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(c=>({...c,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(c=>({...c,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let c=te.find(d=>d.alias===l.moduleAlias);if(!c)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let u=await up(c,l);u.success?r(l.moduleAlias,{status:"updated",detail:`v${u.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:dp(c)});}t(l=>({...l,items:l.items.map(c=>c.status==="pending"?{...c,status:"ok"}:c)})),await Kr(),t(l=>({...l,outcome:"done"}));}catch{await Kr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function SS({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Cu,{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 xS({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 mp(){let{outcome:e,items:t}=pp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=Q().some(i=>i.name===re);r(s?"main":"claudeMdSuggestion"),n("list");},1500);return ()=>clearTimeout(o)}if(e==="module-missing"){let o=setTimeout(()=>{r("moduleSetup"),n("moduleSetup");},500);return ()=>clearTimeout(o)}},[e,r,n]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:t.map(o=>jsx(SS,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(xS,{outcome:e})})]})}var PS={debug:"gray",info:"cyan",warn:"yellow",error:"red"},fp=10;function gp(){let[e,t]=useState(fi());useEffect(()=>fl(()=>{t([...fi()]);}),[]);let r=e.slice(-fp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",fp,") \u2014 press Ctrl+D to close"]}),r.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):r.map((n,o)=>jsxs(Text,{color:PS[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var kS=I("app"),AS={auth:Vl,starterKitSetup:Td,moduleSetup:op,claudeMdSuggestion:ap,verify:mp,main:fd};function wp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Fn(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Sp(){P(b.CLI_SESSION_STARTED,{cli_version:oe,os:process.platform,node_version:process.version,duration_ms:Bt(),interface:"tui"}).catch(()=>{});}async function Ip(){let e=await q();if(e&&Fl()&&await nr()){let{clientSecret:n,...o}=e;Ge.getState().setCredentials(o),Sp(),Fn(e);return}if(!e){wp();return}try{await xt();}catch(n){kS.debug(`Token validation failed: ${String(n)}`),wp();return}Sp();let{clientSecret:t,...r}=e;Ge.getState().setCredentials(r),Fn(e);}function bp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=AS[r],{pendingExit:o}=Ol(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let c=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!c);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(gp,{}),o&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",r]})}async function Wa(e,t={}){let r=Go({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant},t);return Wo(r),await Nt(e),{jwt:r.jwt,previousToken:r.previousToken,hadExistingFile:r.hadExistingFile}}var yt=I("auth");function Pp(){De.clearFallbackFile(),Uo();}var $S=3,vp=3,Ep=` \u2139 The data collected during setup is used solely to improve
|
|
117
117
|
Flow's internal tools and will not be shared externally.
|
|
118
|
-
`;function
|
|
118
|
+
`;function Hr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=u=>{if(u===""){l(),n(new Error("SIGINT"));return}if(u==="\r"||u===`
|
|
119
119
|
`){l(),process.stdout.write(`
|
|
120
|
-
`),r(i);return}if(u==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(i+=u,process.stdout.write(o?"*".repeat(u.length):u));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function
|
|
121
|
-
`+
|
|
122
|
-
`),(await
|
|
123
|
-
|
|
124
|
-
`))
|
|
125
|
-
`)):r?process.stdout.write(k.yellow(`
|
|
126
|
-
\u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
|
|
127
|
-
`)):process.stdout.write(k.green(` done
|
|
128
|
-
`)),{initFailed:r}}async function _p(){for(let e=1;e<=Ap;e++)try{return await Is()}catch{if(e===Ap)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Dp(){let e=await _p();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
129
|
-
`+k.cyan(" ? ")+`Starter Kit:
|
|
130
|
-
`),e.forEach((t,r)=>{process.stdout.write(` ${k.cyan(`${r+1})`)} ${y(t.name)}
|
|
120
|
+
`),r(i);return}if(u==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}u.startsWith("\x1B")||(i+=u,process.stdout.write(o?"*".repeat(u.length):u));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c),process.removeListener("SIGINT",c),process.removeListener("SIGTERM",c);}function c(){try{process.stdin.setRawMode(!1);}catch{}}process.on("uncaughtException",c),process.on("unhandledRejection",c),process.on("SIGINT",c),process.on("SIGTERM",c),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function MS(){let e=Ar();return process.stdout.write(`
|
|
121
|
+
`+M.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
122
|
+
`),(await Hr(M.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function Tp(e,t){try{await Wa(e);return}catch(r){if(!(r instanceof $r))throw r;if(!t)throw new Error(`${r.message}. Fix or remove ${Ar()} and retry.`);if(!await MS())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Wa(e,{allowOverwriteMalformed:true});}}async function Cp(){for(let e=1;e<=vp;e++)try{return await ls()}catch{if(e===vp)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function kp(){let e=await Cp();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
123
|
+
`+M.cyan(" ? ")+`Starter Kit:
|
|
124
|
+
`),e.forEach((t,r)=>{process.stdout.write(` ${M.cyan(`${r+1})`)} ${y(t.name)}
|
|
131
125
|
`);}),process.stdout.write(`
|
|
132
|
-
`);;){let t=(await
|
|
133
|
-
`));}}async function
|
|
126
|
+
`);;){let t=(await Hr(M.cyan(" ? ")+`Select starter kit (1-${e.length}): `)).trim(),r=parseInt(t,10)-1;if(!isNaN(r)&&r>=0&&r<e.length)return e[r];process.stderr.write(M.yellow(` \u26A0 Invalid selection. Please try again.
|
|
127
|
+
`));}}async function Ap(e){if(e.plugins.length===0)return process.stdout.write(M.dim(`
|
|
134
128
|
Starter kit '${y(e.name)}' has no plugins to install.
|
|
135
129
|
`)),true;process.stdout.write(`
|
|
136
130
|
Installing ${e.plugins.length} plugins from '${y(e.name)}'...
|
|
137
|
-
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(
|
|
138
|
-
`)):(r++,process.stdout.write(
|
|
139
|
-
`)));}return r===0?process.stdout.write(
|
|
140
|
-
`)):process.stdout.write(
|
|
141
|
-
`)),r===0}async function
|
|
142
|
-
`),process.stdout.write(
|
|
143
|
-
`)),process.stdout.write(
|
|
131
|
+
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(M.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=$S;a++)try{await Te(o),t++,i=!0;break}catch(l){if(l instanceof Ne){t++,i=true;break}}i?process.stdout.write(M.green(` done
|
|
132
|
+
`)):(r++,process.stdout.write(M.red(` failed
|
|
133
|
+
`)));}return r===0?process.stdout.write(M.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
|
|
134
|
+
`)):process.stdout.write(M.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
|
|
135
|
+
`)),r===0}async function $p(){process.stdout.write(`
|
|
136
|
+
`),process.stdout.write(M.bold(` Personalize your Claude Code
|
|
137
|
+
`)),process.stdout.write(M.dim(` This plugin helps Claude understand your preferences and work style.
|
|
144
138
|
|
|
145
|
-
`));let e=(await
|
|
139
|
+
`));let e=(await Hr(M.cyan(" ? ")+`Install ${re}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){P(b.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(M.dim(`
|
|
146
140
|
You can always install it later from the catalog.
|
|
147
|
-
`));return}b
|
|
148
|
-
`));}catch(t){if(t instanceof
|
|
149
|
-
`));else {
|
|
150
|
-
`)),process.stdout.write(
|
|
141
|
+
`));return}P(b.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(M.dim(` Installing ${re}...`));try{await Te(re),process.stdout.write(M.green(` done
|
|
142
|
+
`));}catch(t){if(t instanceof Ne)process.stdout.write(M.green(` already installed
|
|
143
|
+
`));else {yt.warn(`Failed to install ${re}: ${t instanceof Error?t.message:t}`),process.stdout.write(M.red(` failed
|
|
144
|
+
`)),process.stdout.write(M.dim(` You can install it later from the catalog.
|
|
151
145
|
`));return}}process.stdout.write(`
|
|
152
146
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
153
|
-
`),process.stdout.write(
|
|
147
|
+
`),process.stdout.write(M.cyan.bold(` /${re}
|
|
154
148
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
155
|
-
`);}async function
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
`),
|
|
159
|
-
`)),1}let{initFailed:t}=await Rp(e.customUrl??null);try{let r;if(e.starterKit){let n=await _p(),o=n.find(s=>s.slug===e.starterKit);if(!o){process.stderr.write(k.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
149
|
+
`);}async function LS(e){Pp(),process.stdout.write(`
|
|
150
|
+
`+Ep+`
|
|
151
|
+
`),yt.debug(`[${e.tenant}] Authenticating tenant`);try{await Tr(e);}catch(t){let r=y(t instanceof Error?t.message:"unknown error");return yt.error(`[${e.tenant}] Authentication failed: ${r}`),process.stderr.write(M.red(` \u2717 Authentication failed: ${r}
|
|
152
|
+
`)),1}try{let t;if(e.starterKit){let r=await Cp(),n=r.find(o=>o.slug===e.starterKit);if(!n){process.stderr.write(M.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
160
153
|
`)),process.stderr.write(` Available starter kits:
|
|
161
|
-
`);for(let
|
|
162
|
-
`);return 1}
|
|
163
|
-
\u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${
|
|
164
|
-
|
|
165
|
-
`)),process.
|
|
166
|
-
`),
|
|
167
|
-
`)
|
|
168
|
-
`),process.
|
|
169
|
-
`);
|
|
170
|
-
`)),1
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
`)),
|
|
174
|
-
`)),process.stdout.write(`
|
|
175
|
-
`),
|
|
176
|
-
`)
|
|
177
|
-
`),130;throw t}}async function RS(){try{return process.stdout.write(`
|
|
178
|
-
`),(await er(k.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(k.yellow(` \u26A0 Logout cancelled
|
|
154
|
+
`);for(let o of r)process.stderr.write(` - ${y(o.slug)} (${y(o.name)})
|
|
155
|
+
`);return 1}t=n;}else t=await kp();return await Tp({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:t.slug},!1),await Ap(t),await $p(),yt.info(`[${e.tenant}] Authentication successful`),process.stdout.write(M.green(`
|
|
156
|
+
\u2713 Setup complete. Tenant: ${e.tenant}. JWT written to ${Ar()}.
|
|
157
|
+
|
|
158
|
+
`)),0}catch(t){if(t instanceof Error&&t.message==="SIGINT")throw t;let r=y(t instanceof Error?t.message:"unknown error");return yt.error(`[${e.tenant}] Starter kit setup failed: ${r}`),process.stderr.write(M.red(` \u2717 Starter kit setup failed: ${r}
|
|
159
|
+
`)),1}}async function RS(){Pp(),yt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
160
|
+
`),process.stdout.write(Ep+`
|
|
161
|
+
`);let e=(await Hr(M.cyan(" ? ")+"Client ID: ")).trim(),t=(await Hr(M.cyan(" ? ")+"Client Secret: ",{masked:!0})).trim(),r=(await Hr(M.cyan(" ? ")+"Tenant: ")).trim();if(!e||!t||!r)return yt.error("[auth] Validation failed: all fields are required"),process.stderr.write(M.red(` \u2717 All fields are required
|
|
162
|
+
`)),1;yt.debug(`[${r}] Authenticating tenant`);try{await Tr({clientId:e,clientSecret:t,tenant:r});}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return yt.error(`[${r}] Authentication failed: ${s}`),process.stderr.write(M.red(` \u2717 Authentication failed: ${s}
|
|
163
|
+
`)),1}let n=await kp();return await Tp({clientId:e,clientSecret:t,tenant:r,starterKit:n.slug},!0),await Ap(n),await $p(),yt.info(`[${r}] Authentication successful`),process.stdout.write(M.green(`
|
|
164
|
+
\u2713 Setup complete. Tenant: ${r}. JWT written to ${Ar()}.
|
|
165
|
+
|
|
166
|
+
`)),0}catch(e){if(e instanceof Error&&e.message==="SIGINT")throw e;let t=y(e instanceof Error?e.message:"unknown error");return yt.error(`[auth] Unexpected error: ${t}`),process.stderr.write(M.red(` \u2717 Unexpected error: ${t}
|
|
167
|
+
`)),1}}async function za(e={}){if(e.clientId&&e.clientSecret&&e.tenant)return LS({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,starterKit:e.starterKit});try{return await RS()}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
168
|
+
`),130;throw t}}async function _S(){try{return process.stdout.write(`
|
|
169
|
+
`),(await Hr(M.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(M.yellow(` \u26A0 Logout cancelled
|
|
179
170
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
180
|
-
`),130;throw e}}async function
|
|
181
|
-
`)),0;if(!e){let t=await
|
|
182
|
-
`)),0}catch{return process.stderr.write(
|
|
183
|
-
`)),1}}async function
|
|
184
|
-
`+
|
|
185
|
-
`)),process.stdout.write(
|
|
186
|
-
`),process.stdout.write(
|
|
187
|
-
`),process.stdout.write(
|
|
188
|
-
`),process.stdout.write(
|
|
171
|
+
`),130;throw e}}async function Mp(e){if(!await q())return process.stdout.write(M.yellow(` \u26A0 You are not authenticated
|
|
172
|
+
`)),0;if(!e){let t=await _S();if(t!==null)return t}try{return await bl(),process.stdout.write(M.green(` \u2713 Credentials removed successfully
|
|
173
|
+
`)),0}catch{return process.stderr.write(M.red(` \u2717 Error removing credentials
|
|
174
|
+
`)),1}}async function Lp(){let e=await q();return e?await nr()?(process.stdout.write(`
|
|
175
|
+
`+M.bold(` Authenticated
|
|
176
|
+
`)),process.stdout.write(M.dim(" Tenant: ")+y(e.tenant)+`
|
|
177
|
+
`),process.stdout.write(M.dim(" Client ID: ")+y(e.clientId)+`
|
|
178
|
+
`),process.stdout.write(M.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
179
|
+
`),process.stdout.write(M.dim(" Config: ")+y(await vl())+`
|
|
189
180
|
`),process.stdout.write(`
|
|
190
|
-
`),0):(process.stdout.write(
|
|
181
|
+
`),0):(process.stdout.write(M.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(M.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function DS(e){let t=Q(),r;try{r=await lr();}catch{r=[];}let n=new Set(t.map(o=>o.name));return P(b.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(er(r.map(o=>({...o,installed:n.has(o.name)}))),0):(Zr(["","Name","Version","Category","Status"],r.map(o=>[n.has(o.name)?"*":" ",o.name??"",o.version??"n/a",o.category??"",n.has(o.name)?"installed":"available"])),0)}async function OS(e){let t=Q(),r=await lr(),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Ae(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return P(b.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(C("All plugins are up to date."),0):e.json?(er(o),0):(Zr(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
191
182
|
${o.length} plugin(s) outdated.
|
|
192
|
-
`),0)}async function
|
|
183
|
+
`),0)}async function NS(e){let t=Q();if(P(b.CLI_CATALOG_VIEWED,{interface:J().interfaceType,filter_type:"all",result_count:t.length}).catch(()=>{}),t.length===0)return C("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return er(t),0;let r=[];try{r=await lr();}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=co.indexOf(s.scope??"user"),l=co.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return Zr(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??ba(s.marketplace);return [s.name??"",s.version??"n/a",zr[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",St(s.installedAt??"")]})),process.stdout.write(`
|
|
193
184
|
${t.length} plugin(s) installed.
|
|
194
|
-
`),0}async function
|
|
185
|
+
`),0}async function Rp(e){if(!await se())return 1;try{return e.available?await DS(e):e.outdated?await OS(e):await NS(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}var ie=I("manage");function Ys(e,t){return t?Q().find(r=>r.name===e&&r.scope===t):Q().find(r=>r.name===e)}function BS(e,t){let r=t;return {callbacks:{onStatus:o=>{r&&(r.text=`${e}${o}`);},onError:o=>{r?.stop(),r=void 0,C(`${e}${o}`);},onPause:()=>{r?.stop(),r=void 0;},onResume:o=>{r?.stop(),r=Xa({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function US(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(ln(e,r.scope));if(!await vt(`${t}Install external plugin "${i}"?
|
|
195
186
|
This will run: ${a}
|
|
196
|
-
[y/N] `))return
|
|
197
|
-
Installation summary: ${t} succeeded, ${r} failed`);}async function
|
|
198
|
-
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function
|
|
187
|
+
[y/N] `))return ie.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Xa({text:`${t}Installing ${e}...`}).start());}let s=o?BS(t,o):void 0;try{let i=await Xu(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Je({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?_e({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):ne(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=H(i);return r.silent?Je({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function FS(e,t,r){let n=r.silent?void 0:Xa({text:`${t}Installing ${e}...`}).start();if(sn(e))return US(e,t,r,n);try{let o=await Te(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:c}=Zo(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${c})`;}});return n?.stop(),r.silent?_e({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):ne(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof Ne)return r.silent?_e({status:"already_installed",plugin:e,message:o.message}):C(`${t}${o.message}`),{name:e,success:true};let s=H(o);return r.silent?Je({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function jS(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;C(`
|
|
188
|
+
Installation summary: ${t} succeeded, ${r} failed`);}async function Zs(e,t={}){if(!await se())return 1;let r=[];for(let n=0;n<e.length;n++){let o=e.length>1?`[${n+1}/${e.length}] `:"",s=await FS(e[n],o,t);r.push(s);}return e.length>1&&(t.silent?_e({status:"summary",succeeded:r.filter(n=>n.success).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.error?{error:n.error}:{}}))}):jS(r)),r.some(n=>!n.success)?1:0}async function _p(e,t){if(!await se())return 1;if(ie.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Ys(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;let n=y(r.name),o=r.version?y(r.version):void 0,s=t.scope?` (${t.scope})`:"";if(!await vt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return ie.debug(`[${e}] Uninstall cancelled by user`),C("Operation cancelled."),0}try{return ie.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Wn(e,t.scope),ie.info(`[${e}] Uninstalled successfully`),ne("Plugin removed successfully"),0}catch(r){return ie.error(`[${e}] Failed to uninstall: ${H(r)}`),E(H(r)),1}}async function Dp(e,t={}){if(!await se())return 1;ie.debug(`[${e}] Looking up installed plugin`);let r=Ys(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return ie.debug(`[${e}] Already enabled, skipping`),C(`${r.name} is already enabled`),0;try{return ie.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await zn(e,"enabled",t.scope),ie.info(`[${e}] Enabled successfully`),ne(`${r.name} enabled successfully`),0}catch(n){return ie.error(`[${e}] Failed to enable: ${H(n)}`),E(H(n)),1}}async function Op(e,t={}){if(!await se())return 1;ie.debug(`[${e}] Looking up installed plugin`);let r=Ys(e,t.scope);if(!r)return ie.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return ie.debug(`[${e}] Already disabled, skipping`),C(`${r.name} is already disabled`),0;try{return ie.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await zn(e,"disabled",t.scope),ie.info(`[${e}] Disabled successfully`),ne(`${r.name} disabled successfully`),0}catch(n){return ie.error(`[${e}] Failed to disable: ${H(n)}`),E(H(n)),1}}async function Np(e,t,r){r.silent||C(`${t}Updating ${e}...`);try{let n=await Ps(e,r);return r.silent?_e({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):ne(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof ar)return r.silent?_e({status:"up_to_date",plugin:e,message:n.message}):C(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=H(n);return r.silent?Je({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function KS(e){let t=e.filter(o=>o.success&&!o.skipped).length,r=e.filter(o=>o.skipped).length,n=e.filter(o=>!o.success).length;C(`
|
|
189
|
+
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function VS(e,t,r){try{let n=await un(e);Ae(t,n.version,r.force)?C(`Would update ${e}: v${t} \u2192 v${n.version}`):C(`${e} is already up to date (v${t})`);}catch(n){return E(H(n)),1}return 0}function HS(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function JS(e,t,r){let n=t.get(e.name);return n?e.version&&Ae(e.version,n,r)?(C(`Would update ${e.name}: v${e.version} \u2192 v${n}`),true):(C(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(C(`Skipping ${e.name}: not found in catalog`),false)}async function GS(e,t){try{let r=await lr(),n=HS(r),o=0;for(let s of e)JS(s,n,t.force)&&o++;o===0&&C("All plugins are up to date");}catch(r){return E(H(r)),1}return 0}async function WS(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Np(e[n].name,o,t);r.push(s);}return t.silent?_e({status:"summary",updated:r.filter(n=>n.success&&!n.skipped).length,upToDate:r.filter(n=>n.skipped).length,failed:r.filter(n=>!n.success).length,results:r.map(n=>({plugin:n.name,success:n.success,...n.skipped?{skipped:true}:{},...n.error?{error:n.error}:{}}))}):KS(r),r.some(n=>!n.success)?1:0}async function Bp(e,t={}){if(!await se())return 1;if(e){let o=Ys(e,t.scope);return o?t.dryRun?VS(e,o.version??"",t):(await Np(e,"",t)).success?0:1:(t.silent?Je({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=Q().filter(o=>o.marketplace===z);return n.length===0?(t.silent?_e({status:"empty",message:"No plugins installed"}):C("No plugins installed"),0):t.dryRun?GS(n,t):WS(n,t)}var ho=I("cli:bundle");function zS(e){let t=y(e.name??e.flowId),r=y(e.type??"unknown");return e.available?` \u2713 ${t} (${r})`:` \u2717 ${t} (${r}) \u2014 unavailable`}function XS(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
|
|
199
190
|
Bundle: ${y(e)} (${t.length} artifacts)
|
|
200
191
|
`);for(let o of t)process.stdout.write(`${zS(o)}
|
|
201
192
|
`);process.stdout.write(`
|
|
202
193
|
${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
|
|
203
194
|
|
|
204
|
-
`);}async function
|
|
195
|
+
`);}async function Up(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await se())return 1;ho.debug(`Fetching bundle "${e}"`);let r;try{r=await ks(e);}catch(a){return a instanceof xn||a instanceof lo?(E(a.message),1):(E(`Failed to fetch bundle: ${a instanceof Error?a.message:String(a)}`),1)}let n=r.artifact.artifacts,o=n.filter(a=>a.available);if(ho.debug(`Bundle "${r.title}" \u2014 ${n.length} artifact(s), ${o.length} available`),XS(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await vt(`Install ${o.length} artifact(s)? [Y/n] `))return ho.debug("Installation cancelled by user"),0;ho.debug(`Starting installation of ${o.length} artifact(s)`);let i=await xs(r,{onProgress:({index:a,total:l,artifact:c,success:u,error:d})=>{let m=y(c.name??c.flowId),p=y(c.type??"unknown"),f=u?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
|
|
205
196
|
`),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
|
|
206
197
|
`),a===l&&process.stdout.write(`
|
|
207
|
-
`);}});if(
|
|
198
|
+
`);}});if(ho.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&ne(`${i.installed} installed successfully`),i.failed>0){let a=i.failures.map(l=>l.name).join(", ");E(`${i.failed} failed: ${y(a)}`);}if(i.skipped>0){let a=n.filter(l=>!l.available).map(l=>y(l.name??l.flowId)).join(", ");C(`${i.skipped} unavailable: ${a}`);}return 0}var Fp=I("marketplace");function YS(e){return `claude plugin marketplace add ${e}`}async function jp(e,t){if(!await se())return 1;let r;try{r=is(e);}catch(s){let i=H(s);return t.silent?Je({status:"error",source:e,message:i}):E(i),1}Fp.debug(`[marketplace] Adding marketplace source: ${r}`);let n=YS(r);if(!t.force){let s=y(r),i=y(n);if(!await vt(`Add marketplace "${s}"?
|
|
208
199
|
This will run: ${i}
|
|
209
|
-
[y/N] `))return
|
|
210
|
-
`+
|
|
200
|
+
[y/N] `))return Fp.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:Xa({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await we(n);return o?.stop(),s.exitCode!==0?(t.silent?Je({status:"error",source:r,exitCode:s.exitCode,message:s.stderr||"Command failed"}):(E(`Failed to add marketplace "${r}": ${s.stderr||"Command failed"}`),t.verbose&&s.stdout&&C(`stdout: ${s.stdout}`)),1):(t.silent?_e({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(ne(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&C(s.stdout)),0)}catch(s){o?.stop();let i=H(s);return t.silent?Je({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}async function tx(){return await q()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function rx(){let e=Date.now();try{await lr();let t=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${t}ms)`,latency:t}}catch(t){return t instanceof Error&&t.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${t instanceof Error?t.message:"Unknown"}`}}}async function nx(){return await nr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function ox(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}async function Kp(){process.stdout.write(`
|
|
201
|
+
`+M.bold(` FlowSetup CLI Diagnostics
|
|
211
202
|
|
|
212
|
-
`));let e=[{name:"Credentials",fn:
|
|
203
|
+
`));let e=[{name:"Credentials",fn:tx},{name:"Prompt Manager",fn:rx},{name:"Valid Token",fn:nx},{name:"Claude Code",fn:ox}],t=true;for(let r of e){let n=await r.fn(),o="",s=M.green;n.passed?o=M.green("[OK] "):(o=M.red("[FAIL]"),s=M.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
|
|
213
204
|
`);}return process.stdout.write(`
|
|
214
|
-
`),t?(process.stdout.write(
|
|
205
|
+
`),t?(process.stdout.write(M.green(` \u2713 All checks passed!
|
|
215
206
|
|
|
216
|
-
`)),0):(process.stdout.write(
|
|
207
|
+
`)),0):(process.stdout.write(M.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
217
208
|
|
|
218
|
-
`)),1)}
|
|
219
|
-
|
|
220
|
-
`)
|
|
209
|
+
`)),1)}tn();async function Vp(e){let t=await q(),r=or("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Dt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await Mc.get(`${r}rate-limit/me`,{searchParams:{mode:"budget"},headers:n}).json();if(typeof o.consumed_usd!="number"||typeof o.budget_limit!="number"||typeof o.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return o}var ix=I("commands:usage"),Qs=20,Hp="EMAIL",Jp="MONTHLY CONSUMPTION (USD)",Gp="STATUS";function ax(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*Qs),n=Qs-r,o=M.green;return t>=90?o=M.red:t>=70&&(o=M.yellow),o("\u2588".repeat(r))+M.dim("\u2591".repeat(n))}function Wp(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function lx(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?M.green(`\u2299 ${n}`):t==="warning"?M.yellow(`\u26A0 ${n}`):t==="blocked"?M.red("\u2717 Budget limit reached"):M.red(`\u2717 ${n}`)}function cx(e){let t=St(e),r=Math.ceil((new Date(e).getTime()-Date.now())/864e5),n=r>0?` (in ${r} day${r===1?"":"s"})`:"";return `${t}${n}`}async function ux(e){try{let t=await Ko();if(t?.email)return y(t.email);let r=en(e);return y(r.email??"")}catch(t){return ix.debug(`JWT email decode failed: ${String(t)}`),""}}async function zp(e){if(!await se())return 1;let r;try{r=await xt();}catch(h){return E(`Authentication error: ${H(h)}`),1}let n;try{n=await Vp(r);}catch(h){return E(`Failed to fetch usage data: ${H(h)}`),1}if(e.json)return er(n),0;let o=await ux(r)||y(n.user_id),s=Wp(n.consumed_usd),i=Wp(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,c=Math.max(Hp.length,o.length+2),u=Math.max(Jp.length,Qs+2+l.length),d=` ${Hp.padEnd(c)} ${Jp.padEnd(u)} ${Gp}`,m=` ${"\u2500".repeat(c)} ${"\u2500".repeat(u)} ${"\u2500".repeat(Gp.length)}`,p=`${M.cyan("\u2022")} ${o.padEnd(c-2)}`,f=`${ax(n.percentage)} ${l.padEnd(u-Qs-2)}`,g=` ${M.dim("Resets")} ${cx(n.renewal_date)}`;return process.stdout.write(`
|
|
210
|
+
`),process.stdout.write(M.dim(d)+`
|
|
211
|
+
`),process.stdout.write(M.dim(m)+`
|
|
212
|
+
`),process.stdout.write(` ${p} ${f} ${lx(n.status)}
|
|
213
|
+
`),process.stdout.write(g+`
|
|
214
|
+
`),process.stdout.write(`
|
|
215
|
+
`),0}var mx=["github.com","www.github.com"],fx=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,gx=/^([^@]+)@(.+)$/;function hx(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function qa(e){let t=e.replace(/\\/g,"/");t=t.replace(/^\/+/,"").replace(/\/+$/,"");let r=t.split("/").filter(Boolean);for(let n of r)if(n==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return r.join("/")}function yx(e){let t=e.pathname.split("/").filter(Boolean);if(t.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let r=t[0],n=t[1];n.endsWith(".git")&&(n=n.slice(0,-4));let o={type:"github",url:`https://github.com/${r}/${n}.git`};if(t.length>=3&&(t[2]==="tree"||t[2]==="blob")){if(t.length>=4&&(o.ref=t[3]),t.length>=5){let s=t.slice(4).join("/");o.subpath=qa(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=qa(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function ei(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(hx(t)){let r=resolve(t);return {type:"local",url:r,localPath:r}}try{let r=new URL(t);if((r.protocol==="https:"||r.protocol==="http:")&&mx.includes(r.hostname))return yx(r);if(r.protocol==="https:"||r.protocol==="http:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}if(r.protocol==="git:"){let n={type:"git",url:t};return r.hash&&r.hash.length>1&&(n.ref=decodeURIComponent(r.hash.slice(1)),n.url=t.replace(r.hash,"")),n}}catch{}if(t.startsWith("git@")||t.includes(":")&&t.includes(".git")){let r=t,n,o=t.indexOf("#");o!==-1&&(n=t.slice(o+1),r=t.slice(0,o));let s={type:"git",url:r};return n&&(s.ref=n),s}{let r=t,n,o=r.indexOf("#");o!==-1&&(n=r.slice(o+1),r=r.slice(0,o));let s=r.match(fx);if(s){let i=s[1],a=s[2],l=s[3],c,u=a.match(gx);u&&(a=u[1],c=u[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),c&&(d.skillFilter=c),l){let m=l.replace(/^\//,"");m&&(d.subpath=qa(m));}return d}}return {type:"git",url:t}}function ti(e){if(e.type!=="github")return null;try{let r=new URL(e.url).pathname.split("/").filter(Boolean);if(r.length<2)return null;let n=r[1];return n.endsWith(".git")&&(n=n.slice(0,-4)),`${r[0]}/${n}`}catch{return null}}function Xp(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return t?{data:parse(t[1])??{},content:t[2]??""}:{data:{},content:e}}var Za=new Set(["node_modules",".git","dist","build","__pycache__"]);function Zp(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function bx(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Ya(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function yo(e){try{let t=await readFile(e,"utf-8"),{data:r}=Xp(t);return typeof r.name!="string"||typeof r.description!="string"?null:{name:r.name,description:r.description,path:dirname(e),rawContent:t,metadata:r.metadata}}catch{return null}}async function Qp(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Ya(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Za.has(a.name)).map(a=>Qp(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function oi(e,t){let r=[],n=new Set;if(t&&!bx(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Ya(o)){let i=await yo(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let c=join(i,l.name);if(await Ya(c)){let u=await yo(join(c,"SKILL.md"));u&&!n.has(u.name)&&(r.push(u),n.add(u.name));}}}catch{}if(r.length===0){let i=await Qp(o);for(let a of i){let l=await yo(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function em(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}var nm=1,kx={retries:5,minTimeout:50};async function om(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Wg.lock(e+".lock",{realpath:false,retries:kx});try{return await t()}finally{await r();}}function tm(){return {version:nm,skills:{}}}async function si(e){let t=Mn(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<nm?tm():n}catch{return tm()}}function Ax(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function sm(e,t){let r=Mn(t);await mkdir(dirname(r),{recursive:true});let n={version:e.version,skills:Ax(e.skills)};await writeFile(r,JSON.stringify(n,null,2)+`
|
|
216
|
+
`,"utf-8");}async function im(e,t,r){let n=Mn(r);await om(n,async()=>{let o=await si(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await sm(o,r);});}async function am(e,t){let r=Mn(t);await om(r,async()=>{let n=await si(t);e in n.skills&&(delete n.skills[e],await sm(n,t));});}var lm=I("skillInstaller");async function Ox(e,t,r,n){try{await P(b.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:J().interfaceType});}catch(o){lm.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function Nx(e,t){try{await P(b.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:J().interfaceType});}catch(r){lm.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function Bx(e,t){await cp$1(e,t,{recursive:true,dereference:true,filter:r=>!Za.has(basename(r))});}async function Ux(e,t,r){let n=Ze(e.name),o=vr(t),s=join(o,n);if(!Zp(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await Bx(e.path,s);let a=ti(r)??r.url;return await im(n,{source:a,sourceType:r.type,sourceUrl:r.url,ref:r.ref,skillPath:r.subpath},t),{skill:e.name,success:!0,path:s}}catch(i){return {skill:e.name,success:false,path:s,error:i instanceof Error?i.message:String(i)}}}async function cm(e,t){let r=ei(e),n;try{let o;if(r.type==="local"){if(!r.localPath||!existsSync(r.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};o=r.localPath;}else n=await Pt(r.url,r.ref),o=n;let s=await oi(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?em(s,i):s,l=[],c=r.ref??"latest";for(let u of a){let d=Date.now(),m=await Ux(u,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await Ox(u.name,t.scope,c,p):await Nx(u.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(u=>u.success).length,failed:l.filter(u=>!u.success).length}}finally{n&&await Et(n).catch(()=>{});}}var Hx=I("skills");async function Jx(e){try{await P(b.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:J().interfaceType});}catch(t){Hx.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function Gx(e){let t=createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(`${y(e)} (y/N) `,n=>{t.close(),r(n.trim().toLowerCase()==="y");});})}async function Wx(e){let t=ei(e),r;try{let n;if(t.type==="local"){if(!t.localPath)return E("Invalid local path."),1;n=t.localPath;}else C(`Fetching skills from ${y(e)}...`),r=await Pt(t.url,t.ref),n=r;let o=await oi(n,t.subpath);if(o.length===0)return C("No skills found in this source."),0;let i=ti(t)??y(e);C(`Found ${o.length} skill(s) in ${i}:
|
|
217
|
+
`);for(let a of o){let l=y(a.name),c=y(a.description);process.stdout.write(` ${M.bold(l)} ${M.dim(c)}
|
|
221
218
|
`);}return process.stdout.write(`
|
|
222
|
-
`),0}catch(n){return n instanceof
|
|
223
|
-
`);let t=e.source;e.installed>0&&C(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&
|
|
224
|
-
`);for(let s of r){let i=n.skills[
|
|
225
|
-
`),process.stdout.write(` ${
|
|
219
|
+
`),0}catch(n){return n instanceof pr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await Et(r).catch(()=>{});}}function zx(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);ne(`${n} installed ${M.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
220
|
+
`);let t=e.source;e.installed>0&&C(`Installed ${e.installed} of ${e.discovered} skill(s) from ${y(t)}`),e.failed>0&&E(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?C("No skills found in this source."):e.results.length===0&&e.discovered>0&&C(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function dm(e,t){if(t.list)return Wx(e);let r=t.global?"global":"project";try{let n=await cm(e,{scope:r,skillFilter:t.skill,yes:t.yes});return zx(n),n.failed>0?1:0}catch(n){return n instanceof pr?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function pm(e){let t=vr(e),r=[];try{let n=await readdir(t,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=join(t,o.name),i=join(s,"SKILL.md");try{if(!(await stat(i)).isFile())continue}catch{continue}let a=await yo(i);a?r.push({name:a.name,description:a.description,path:s}):r.push({name:o.name,description:"(no metadata)",path:s});}}catch{}return r}async function mm(e){let t=e.global?"global":"project",r=await pm(t),n=await si(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[Ze(i.name)]?.source}));return er(s),0}if(r.length===0)return C(`No skills installed (${t==="global"?"global":"project"} scope).`),0;C(`${t==="global"?"Global":"Project"} skills (${r.length}):
|
|
221
|
+
`);for(let s of r){let i=n.skills[Ze(s.name)]?.source,a=y(s.name),l=y(s.description),c=l.length>80?l.slice(0,77)+"...":l,u=i?M.dim(` (${i})`):"";process.stdout.write(` ${M.bold(a)}${u}
|
|
222
|
+
`),process.stdout.write(` ${M.dim(c)}
|
|
226
223
|
|
|
227
|
-
`);}return 0}async function
|
|
224
|
+
`);}return 0}async function fm(e,t){let r=t.global?"global":"project";if(!e){let i=await pm(r);if(i.length===0)return C("No skills installed."),0;C("Installed skills:");for(let a of i)process.stdout.write(` - ${y(a.name)}
|
|
228
225
|
`);return process.stdout.write(`
|
|
229
|
-
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=
|
|
230
|
-
Import summary: 0 installed, ${o.length} failed`);for(let a of o)
|
|
231
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)
|
|
226
|
+
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=Ze(e),o=vr(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await Gx(`Remove skill "${y(n)}"?`))return C("Cancelled."),0;try{return await rm(s,{recursive:!0,force:!0}),await am(n,r),await Jx(n),ne(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}var ii=I("transfer"),el=1;function Xx(e){return e.marketplace&&e.marketplace!==z?`${e.name}@${e.marketplace}`:e.name}function qx(e,t){let r=e.filter(o=>t.has(o.name)),n=e.filter(o=>!t.has(o.name));r.length>0&&C(`Already installed (${r.length}): ${r.map(o=>o.name).join(", ")}`),C(`To install (${n.length}): ${n.length>0?n.map(o=>o.name).join(", "):"none"}`);}function ym(e){let t=fe__default.resolve(e.output);try{let r=Q(),n={version:el,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return ge__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),ne(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=H(r);return ii.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function wm(e,t={}){if(!await se())return 1;let r;try{let a=ge__default.readFileSync(fe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${H(a)}`),1}if(r.version!==el)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${el}`),1;if(!Array.isArray(r.plugins))return E('Invalid export file format: missing or invalid "plugins" array'),1;if(r.plugins.length===0)return C("No plugins to import"),0;let n=[],o=[],s=0;for(let[a,l]of r.plugins.entries())if(!l?.name||typeof l.name!="string"){let c=`entry[${a}]`;ii.warn(`Skipping ${c}: missing or invalid name`),o.push({name:c,error:"missing or invalid name"});}else l.type==="mcp"?(ii.debug(`[${l.name}] Skipping MCP entry`),s++):n.push(l);if(s>0&&C(`Skipping ${s} MCP(s) \u2014 use 'flow mcp add' to install them manually`),t.diff||t.dryRun){let a=new Set(Q().map(l=>l.name));qx(n,a);}if(t.dryRun)return C("Dry-run mode: no plugins were installed"),0;if(n.length===0){C(`
|
|
227
|
+
Import summary: 0 installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}C(`Importing ${n.length} plugin(s)...`);let i=0;for(let a of n){let l=t.scope??a.scope??"user",c=Xx(a);ii.debug(`[${a.name}] Installing as "${c}" in scope "${l}"`),await Zs([c],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}C(`
|
|
228
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function N(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}var Zx=I("moduleProxy");function Qx(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=aa.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(!["n","no"].includes(n.toLowerCase().trim()));});})}async function Sm(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await P(b.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{Zx.warn(`Failed to emit proxy executed event: ${String(s)}`);}),N(o);}async function Im(e,t){let r=te.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),N(1);return}if(!await $t(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await P(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),N(1);return}let s=(await Promise.all(o.strategies.map(async a=>{try{return await Lt(a.type).isAvailable()?a.type:null}catch{return null}}))).find(a=>a!==null)??null;if(!s){E(`No supported installation method available for '${e}' on this platform.`),N(1);return}if(await Qx("Would you like to install it now? [Y/n] ")){await P(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await vn(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),N(1);return}await Sm(r,t);}else C(`To install manually, run: flow modules install ${e}`),await P(b.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),N(1);return}await Sm(r,t);}var nI=promisify(execFile);async function oI(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await nI(Gt(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${oe}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(n.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let o=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t.signal,headers:n});return o.ok?(await o.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(r);}}catch{return null}}function sI(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Ae(t,r)?"outdated":"installed"}async function tl(){let e=await Promise.all(te.map(async t=>{let[r,n]=await Promise.all([$t(t.binaryName),oI(t)]),s=rt(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=sI(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return Zr(["Name","Alias","Version","Status","Platform"],e),0}async function Pm(e){let t=te.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await Pn([t]);if(r.alreadyInstalled){let i=rt(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return C(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Xa({text:`Installing ${t.name}...`}).start(),s;try{s=await vn(t,"on_demand",n);}finally{o.stop();}return s.success?(ne(`${t.name} v${s.version??"unknown"} installed`),s.pendingInteractiveSetup&&spawnSync(s.pendingInteractiveSetup[0],s.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(E(s.error?.message??"Installation failed"),1)}async function bm(e,t){let r=Xa({text:`Updating ${e.name}...`}).start(),n;try{n=await Ks(e,"command");}catch(o){return r.error(`${e.name}: ${o instanceof Error?o.message:String(o)}`),"error"}if(n.success){let o=n.version??"unknown";return o===t?(r.success(`${e.name}: already up to date (v${t})`),"up_to_date"):(r.success(`${e.name}: v${t} \u2192 v${o}`),"success")}return r.error(`${e.name}: ${n.error?.message??"Update failed"}`),"error"}async function Em(e){if(e!==null){let n=te.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=rt(n.alias);return o?.installMethod?await bm(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=jr().filter(n=>n.installMethod!==null);if(t.length===0)return C("No installed modules to update."),0;let r=0;for(let n of t){let o=te.find(i=>i.alias===n.alias);if(!o)continue;await bm(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function Tm(e){let t=new Command;t.enablePositionalOptions(),t.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${oe}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
232
229
|
Without arguments, opens the interactive interface (TUI).
|
|
233
230
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let r=new Command("setup").description("Configure the CLI by detecting Claude Code credentials");r.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
234
231
|
Examples:
|
|
235
|
-
$ flow setup init`).action(async()=>{let u=await
|
|
232
|
+
$ flow setup init`).action(async()=>{let u=await za();N(u);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).addHelpText("after",`
|
|
236
233
|
Examples:
|
|
237
234
|
$ flow plugin list
|
|
238
235
|
$ flow plugin list --available
|
|
239
236
|
$ flow plugin list --outdated
|
|
240
|
-
$ flow plugin list --json`).action(async u=>{let d=await
|
|
237
|
+
$ flow plugin list --json`).action(async u=>{let d=await Rp(u);N(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
241
238
|
Examples:
|
|
242
239
|
$ flow plugin install flow-adr-writer
|
|
243
240
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -245,11 +242,11 @@ Examples:
|
|
|
245
242
|
$ flow plugin install flow-adr-writer --force
|
|
246
243
|
$ flow plugin install flow-adr-writer --silent
|
|
247
244
|
$ flow plugin install superpowers@claude-plugins-official
|
|
248
|
-
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(u,d)=>{let m=u.filter(f=>f.trim());if(m.length===0){
|
|
245
|
+
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code`).action(async(u,d)=>{let m=u.filter(f=>f.trim());if(m.length===0){E("No valid plugin names provided"),N(1);return}Re("cli",{verbose:d.verbose,silent:d.silent});let p=await Zs(m,d);N(p);}),n.command("uninstall").description("Remove an installed plugin from Claude Code").argument("<name>","Name of the plugin to remove").option("--force","Skip interactive confirmation").addOption(new Option("--scope <scope>","Scope to uninstall from: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
249
246
|
Examples:
|
|
250
247
|
$ flow plugin uninstall flow-adr-writer
|
|
251
248
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
252
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(u,d)=>{let m=await
|
|
249
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(u,d)=>{let m=await _p(u,d);N(m);}),n.command("update").description("Update plugins to the latest version").argument("[name]","Name of the plugin to update (omit to update all)").option("--force","Force update even if already on latest version").option("--dry-run","Show what would be updated without making changes").option("--verbose","Display each step of the update process").option("--silent","Output in JSON only").addOption(new Option("--scope <scope>","Scope to update in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
253
250
|
Examples:
|
|
254
251
|
$ flow plugin update flow-adr-writer
|
|
255
252
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -258,75 +255,77 @@ Examples:
|
|
|
258
255
|
$ flow plugin update flow-adr-writer --verbose
|
|
259
256
|
$ flow plugin update flow-adr-writer --silent
|
|
260
257
|
$ flow plugin update
|
|
261
|
-
$ flow plugin update --dry-run`).action(async(u,d)=>{
|
|
258
|
+
$ flow plugin update --dry-run`).action(async(u,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let m=await Bp(u??null,d);N(m);}),n.command("enable").description("Enable an installed plugin").argument("<name>","Name of the plugin to enable").addOption(new Option("--scope <scope>","Scope to enable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
262
259
|
Examples:
|
|
263
260
|
$ flow plugin enable flow-adr-writer
|
|
264
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(u,d)=>{
|
|
261
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(u,d)=>{Re("cli");let m=await Dp(u,d);N(m);}),n.command("disable").description("Disable an installed plugin").argument("<name>","Name of the plugin to disable").addOption(new Option("--scope <scope>","Scope to disable in: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
265
262
|
Examples:
|
|
266
263
|
$ flow plugin disable flow-adr-writer
|
|
267
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(u,d)=>{
|
|
264
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(u,d)=>{Re("cli");let m=await Op(u,d);N(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
268
265
|
Examples:
|
|
269
266
|
$ flow plugin export
|
|
270
|
-
$ flow plugin export --output my-plugins.json`).action(async u=>{let d=await
|
|
267
|
+
$ flow plugin export --output my-plugins.json`).action(async u=>{let d=await ym(u);N(d);}),n.command("import").description("Install plugins from an exported JSON file").argument("<file>","Path to the export JSON file").option("--force","Force reinstall even if already installed",false).option("--dry-run","Preview what would be installed without installing",false).option("--diff","Show which plugins are already installed vs new",false).addOption(new Option("--scope <scope>","Override scope for all plugins: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
271
268
|
Examples:
|
|
272
269
|
$ flow plugin import flow-plugins.json
|
|
273
270
|
$ flow plugin import flow-plugins.json --scope user
|
|
274
271
|
$ flow plugin import flow-plugins.json --force
|
|
275
272
|
$ flow plugin import flow-plugins.json --dry-run
|
|
276
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(u,d)=>{let m=await
|
|
273
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(u,d)=>{let m=await wm(u,d);N(m);});let o=new Command("marketplace").description("Manage plugin marketplaces");o.command("add").description("Register a plugin marketplace in Claude Code").argument("<source>","Marketplace source (owner/repo or URL)").option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
277
274
|
Examples:
|
|
278
275
|
$ flow plugin marketplace add anthropics/claude-code
|
|
279
276
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
280
277
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
281
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(u,d)=>{
|
|
278
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(u,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let m=await jp(u,d);N(m);}),n.addCommand(o),t.addCommand(n);let s=new Command("mcp").description("Manage MCP servers from the Findr catalog");s.command("add").description("Install an MCP server into Claude Code").argument("<name>","Name of the MCP server to install").argument("[args...]","Arguments to pass to the MCP server (URL for http, command for stdio)").addOption(new Option("--transport <type>","Transport type: http or stdio").choices(["http","stdio"]).makeOptionMandatory()).addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
282
279
|
Examples:
|
|
283
280
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
284
281
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
285
282
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
286
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(u,d,m)=>{
|
|
283
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(u,d,m)=>{Re("cli",{verbose:m.verbose,silent:m.silent});let p=await ed(u,d,m);N(p);}),s.command("remove").description("Remove an MCP server from Claude Code").argument("<name>","Name of the MCP server to remove").addOption(new Option("--scope <scope>","Scope to remove from: user, project, or local").choices(["user","project","local"])).option("--force","Skip confirmation prompt").option("--verbose","Display command output").option("--silent","Output as JSON only").addHelpText("after",`
|
|
287
284
|
Examples:
|
|
288
285
|
$ flow mcp remove notion
|
|
289
286
|
$ flow mcp remove notion --scope project
|
|
290
|
-
$ flow mcp remove playwright-mcp --force`).action(async(u,d)=>{
|
|
287
|
+
$ flow mcp remove playwright-mcp --force`).action(async(u,d)=>{Re("cli",{verbose:d.verbose,silent:d.silent});let m=await td(u,d);N(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--client-id <id>","Client ID for non-interactive authentication").option("--client-secret <secret>","Client Secret for non-interactive authentication").option("--tenant <tenant>","Tenant for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
291
288
|
Examples:
|
|
292
289
|
$ flow auth login
|
|
293
290
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT
|
|
294
291
|
$ flow auth login --client-id ID --client-secret SECRET --tenant TENANT --starter-kit dev
|
|
295
|
-
$ flow auth login --
|
|
296
|
-
$ flow auth login --verbose`).action(async u=>{Ne("cli",{verbose:u.verbose});let d=await el(u);j(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
292
|
+
$ flow auth login --verbose`).action(async u=>{Re("cli",{verbose:u.verbose});let d=await za(u);N(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
297
293
|
Examples:
|
|
298
294
|
$ flow auth logout
|
|
299
|
-
$ flow auth logout --force`).action(async u=>{let d=await
|
|
295
|
+
$ flow auth logout --force`).action(async u=>{let d=await Mp(u.force);N(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
300
296
|
Examples:
|
|
301
|
-
$ flow auth status`).action(async()=>{let u=await
|
|
297
|
+
$ flow auth status`).action(async()=>{let u=await Lp();N(u);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
|
|
302
298
|
Examples:
|
|
303
299
|
$ flow skills add vercel-labs/agent-skills
|
|
304
300
|
$ flow skills add owner/repo -g
|
|
305
301
|
$ flow skills add owner/repo --skill pr-review commit
|
|
306
302
|
$ flow skills add ./local/skills -y
|
|
307
|
-
$ flow skills add owner/repo --list`).action(async(u,d)=>{let m=await
|
|
303
|
+
$ flow skills add owner/repo --list`).action(async(u,d)=>{let m=await dm(u,d);N(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
308
304
|
Examples:
|
|
309
305
|
$ flow skills list
|
|
310
306
|
$ flow skills list -g
|
|
311
|
-
$ flow skills list --json`).action(async u=>{let d=await
|
|
307
|
+
$ flow skills list --json`).action(async u=>{let d=await mm(u);N(d);}),a.command("remove").description("Remove an installed skill").argument("[name]","Name of the skill to remove").option("-g, --global","Remove from global scope").option("--force","Skip confirmation").addHelpText("after",`
|
|
312
308
|
Examples:
|
|
313
309
|
$ flow skills remove pr-review
|
|
314
|
-
$ flow skills remove pr-review -g --force`).action(async(u,d)=>{let m=await
|
|
310
|
+
$ flow skills remove pr-review -g --force`).action(async(u,d)=>{let m=await fm(u,d);N(m);}),t.addCommand(a);let l=new Command("bundle").description("Manage Flow bundles");l.command("install").description("Install all artifacts from a Findr bundle").argument("<name>","Bundle name to install").option("--verbose","Display each step of the installation process").addHelpText("after",`
|
|
315
311
|
Examples:
|
|
316
312
|
$ flow bundle install "My React Kit"
|
|
317
313
|
$ flow bundle install "Squad Setup Bundle"
|
|
318
|
-
$ flow bundle install "My React Kit" --verbose`).action(async(u,d)=>{
|
|
314
|
+
$ flow bundle install "My React Kit" --verbose`).action(async(u,d)=>{Re("cli",{verbose:d.verbose});let m=await Up(u);N(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
315
|
+
Examples:
|
|
316
|
+
$ flow health`).action(async()=>{let u=await Kp();N(u);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
|
|
319
317
|
Examples:
|
|
320
|
-
$ flow
|
|
318
|
+
$ flow usage
|
|
319
|
+
$ flow usage --json`).action(async u=>{let d=await zp(u);N(d);});let c=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");c.action(async()=>{let u=await tl();N(u);}),c.command("list").description("List available and installed modules").addHelpText("after",`
|
|
321
320
|
Examples:
|
|
322
|
-
$ flow modules list`).action(async()=>{let u=await
|
|
321
|
+
$ flow modules list`).action(async()=>{let u=await tl();N(u);}),c.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
323
322
|
Examples:
|
|
324
323
|
$ flow modules install metrics
|
|
325
|
-
$ flow modules install dashboard`).action(async u=>{let d=await
|
|
324
|
+
$ flow modules install dashboard`).action(async u=>{let d=await Pm(u);N(d);}),c.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
326
325
|
Examples:
|
|
327
326
|
$ flow modules update
|
|
328
|
-
$ flow modules update metrics`).action(async u=>{let d=await
|
|
327
|
+
$ flow modules update metrics`).action(async u=>{let d=await Em(u??null);N(d);}),t.addCommand(c);for(let u of te)t.command(u.alias).description(u.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Im(u.alias,d);});return t.hook("preAction",()=>{Vs();}),t}function lI(){return fe__default.join(be__default.homedir(),".claude","settings.json")}function km(){let e=lI();try{if(!ge__default.existsSync(e))return !0;let r=JSON.parse(ge__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}var fI=I("updateChecker"),gI=promisify(execFile),hI=1440*60*1e3,Am=3e4;function yI(){let e=process.env.FLOW_HOME??fe__default.join(be__default.homedir(),".flow");return fe__default.join(e,"update.lock")}async function $m(e){try{let{stdout:t}=await gI(Gt(),["view",e,"version"],{timeout:Am,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function wI(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Am);try{let n=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:t.signal});return n.ok?(await n.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(r);}}async function SI(e){return e.versionCheck.type==="npm-registry"?$m(e.versionCheck.package):wI(e.versionCheck.repo)}async function xI(){let e=await $m("@ciandt-flow/cli");return e&&Ae(oe,e)?(Xs({currentVersion:oe,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function II(){let e=jr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=te.find(i=>i.alias===t.alias);if(!r||r.hasOwnUpdateCheck)return;let n=Date.now(),o=t.lastChecked?new Date(t.lastChecked).getTime():0;if(n-o<hI)return;let s=await SI(r);try{await gt({...t,lastChecked:new Date().toISOString()});}catch(i){fI.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Ae(t.installedVersion,s)&&Ks(r,"background").catch(()=>{});}));}async function nl(){let e=km();if(e===false)return;let t=yI();ge__default.mkdirSync(fe__default.dirname(t),{recursive:true});let r=null;try{r=await Wg.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await xI().catch(()=>null);n&&process.stdout.write(`
|
|
329
328
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
330
329
|
Restart flow to apply the update.
|
|
331
330
|
|
|
332
|
-
`);}await
|
|
331
|
+
`);}await II().catch(()=>{});}finally{await r().catch(()=>{});}}var vI=I("cli"),ol=Tm(async()=>{Re("tui"),Ml("tui"),Ll(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();Dn("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();Dn("sigterm",t,r).finally(()=>process.exit(143));}),await nl().catch(()=>{}),await Dc().catch(t=>{vI.error(`Failed to init catalog registry: ${String(t)}`);}),await Ip();let{waitUntilExit:e}=render(jsx(bp,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});ol.hook("preAction",async(e,t)=>{t!==ol&&await nl().catch(()=>{});});ol.parse();
|