@ciandt-flow/cli 2.6.1-beta.9 → 2.7.0-beta.10
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 +123 -121
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,19 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {execa}from'execa';import wu,{HTTPError}from'ky';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import hh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import*as on from'crypto';import {randomUUID,createHash}from'crypto';import*as ye from'fs';import ye__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import*as he from'path';import he__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as Pe from'os';import Pe__default,{tmpdir,homedir}from'os';import {execFile,exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import*as Da from'readline';import {createInterface}from'readline';import T from'chalk';import Hi from'conf';import {StatusCodes}from'http-status-codes';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import Tg from'jsonwebtoken';import Bg from'proper-lockfile';import ah from'ink-big-text';import md from'ink-spinner';import*as Ct from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import py from'unzipper';import {simpleGit}from'simple-git';import Wa from'semver';import Il from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var yf=Object.defineProperty;var ki=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var wf=(e,t)=>{for(var r in t)yf(e,r,{get:t[r],enumerable:true});};function eg(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 Yi(e){if(Zl.some(r=>r.test(e)))return true;let t=eg(e);return !!(t&&Zl.some(r=>r.test(t)))}function tg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function ar(e,t){let r=tg(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&Yi(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var Zl,dn=ki(()=>{"use strict";Zl=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function cy(){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 hu(){return gu??=cy(),gu}var gu,yu=ki(()=>{"use strict";});var xu={};wf(xu,{GitRepoAdapter:()=>bn});function Su(e,t){if(!uy.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var uy,bn,va=ki(()=>{"use strict";yu();dn();uy=/^[a-zA-Z0-9_.-]+$/;bn=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(Yi(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return Su(a,"owner"),Su(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 wu.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 wu.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 hu();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 tr="FLOW",q="flow-skills",Ai="flow-cli",Fn="internal",Zr="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"}},Ll={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},$i=new Set(["internal","external"]),jn={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"}},oe="flow-claude-md-setup",Je=5,Ut=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Do="https://flow.ciandt.com",en=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,tn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",rn=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,nn="Must be a valid email address (e.g. name@example.com)";var Ml=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(Ml),origins:new Set($i)},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(Ml)},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($i)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));var Oo="aes-256-gcm",xf=16,Rl=16,Kn=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=on.randomBytes(xf),n=on.createCipheriv(Oo,this.key,r,{authTagLength:Rl}),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:Oo}}decrypt(t){if(t.algorithm!==Oo)throw new Error(`Unsupported encryption algorithm: ${t.algorithm}`);let r=on.createDecipheriv(Oo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:Rl});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};var If=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,bf=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,vf=/[A-Za-z0-9+/]{40,}={0,2}/g,Ef=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,Pf=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Tf=/\x1b/g;function Li(e){return e.replace(Ef,"").replace(Pf,"").replace(Tf,"").replace(If,"Bearer ***").replace(bf,"***").replace(vf,"***").replace(/\r\n|\r|\n/g,"\\n")}var kr=".claude",Uo=".flow";function _l(e,t){return Ri(q,e,t)}function Mi(e){return he.join(Pe.homedir(),kr,"plugins","marketplaces",q,"plugins","native",e)}function Bo(){return he.join(Pe.homedir(),kr,"plugins","marketplaces",q,".claude-plugin","marketplace.json")}function No(){return he.join(Pe.homedir(),kr,"plugins","known_marketplaces.json")}function Dl(){return he.join(Pe.homedir(),kr,"plugins","marketplaces",q)}function Ol(){return he.join(Pe.homedir(),Uo,"cache","install.lock")}function Ul(){return he.join(Pe.homedir(),Uo,"logs","flowsetup.log")}function Ri(e,t,r){return he.join(Pe.homedir(),kr,"plugins","cache",e,t,r)}function Ar(e){let t=e==="global"?Pe.homedir():process.cwd();return he.join(t,".claude","skills")}function Vn(e){let t=e==="global"?Pe.homedir():process.cwd();return he.join(t,".claude","skills-lock.json")}function Fo(e="user"){return e==="project"?he.join(process.cwd(),".opencode","plugins"):he.join(Pe.homedir(),".config","opencode","plugins")}function Bl(){return he.join(Pe.homedir(),Uo,"flow-catalogs.json")}function Nl(){let e=process.env.FLOW_HOME??he.join(Pe.homedir(),Uo);return he.join(e,"config.json")}function jo(e="user"){return e==="project"||e==="local"?he.join(process.cwd(),kr,"agents"):he.join(Pe.homedir(),kr,"agents")}var Cf=5*1024*1024,kf=3,Ko=class{filePath;constructor(){this.filePath=Ul(),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
|
-
`);}};
|
|
2
|
+
import*as pn from'crypto';import {randomUUID,createHash}from'crypto';import*as $e from'os';import $e__default,{tmpdir,homedir}from'os';import*as xe from'path';import xe__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as Ie from'fs';import Ie__default,{readFileSync,mkdirSync,existsSync,realpathSync,lstatSync,writeFileSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import T from'chalk';import*as ol from'readline';import {createInterface}from'readline';import pa from'conf';import Xu,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import Gh,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import rh from'jsonwebtoken';import fh from'proper-lockfile';import Uh from'ink-big-text';import Jd from'ink-spinner';import*as Mt from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import Hy from'unzipper';import {simpleGit}from'simple-git';import hl from'semver';import Jl from'yocto-spinner';import {Command,Option}from'commander';import {parse}from'yaml';var zf=Object.defineProperty;var H=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var ec=(e,t)=>{for(var r in t)zf(e,r,{get:t[r],enumerable:true});};var lr,ee,Ki,Yn,sn,an,tc,Vi,Zn,le,Xe,Kt,zo,ln,cn,un,dn,K=H(()=>{"use strict";lr="FLOW",ee="flow-skills",Ki="flow-cli",Yn="internal",sn="external",an={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"}},tc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},Vi=new Set(["internal","external"]),Zn={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"}},le="flow-claude-md-setup",Xe=5,Kt=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,zo="https://flow.ciandt.com",ln=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,cn="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",un=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,dn="Must be a valid email address (e.g. name@example.com)";});var Xo,qf,nc,Qn,Ji=H(()=>{"use strict";Xo="aes-256-gcm",qf=16,nc=16,Qn=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=pn.randomBytes(qf),n=pn.createCipheriv(Xo,this.key,r,{authTagLength:nc}),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=pn.createDecipheriv(Xo,this.key,Buffer.from(t.iv,"hex"),{authTagLength:nc});return r.setAuthTag(Buffer.from(t.authTag,"hex")),Buffer.concat([r.update(Buffer.from(t.ciphertext,"hex")),r.final()]).toString("utf8")}};});function Hi(e){return e.replace(eg,"").replace(tg,"").replace(rg,"").replace(Yf,"Bearer ***").replace(Zf,"***").replace(Qf,"***").replace(/\r\n|\r|\n/g,"\\n")}var Yf,Zf,Qf,eg,tg,rg,Gi=H(()=>{"use strict";Yf=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,Zf=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,Qf=/[A-Za-z0-9+/]{40,}={0,2}/g,eg=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,tg=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,rg=/\x1b/g;});function oc(e,t){return zi(ee,e,t)}function Wi(e){return xe.join($e.homedir(),Dr,"plugins","marketplaces",ee,"plugins","native",e)}function Yo(){return xe.join($e.homedir(),Dr,"plugins","marketplaces",ee,".claude-plugin","marketplace.json")}function Zo(){return xe.join($e.homedir(),Dr,"plugins","known_marketplaces.json")}function sc(){return xe.join($e.homedir(),Dr,"plugins","marketplaces",ee)}function ic(){return xe.join($e.homedir(),qo,"cache","install.lock")}function ac(){return xe.join($e.homedir(),qo,"logs","flowsetup.log")}function zi(e,t,r){return xe.join($e.homedir(),Dr,"plugins","cache",e,t,r)}function Or(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills")}function eo(e){let t=e==="global"?$e.homedir():process.cwd();return xe.join(t,".claude","skills-lock.json")}function Qo(e="user"){return e==="project"?xe.join(process.cwd(),".opencode","plugins"):xe.join($e.homedir(),".config","opencode","plugins")}function lc(){return xe.join($e.homedir(),qo,"flow-catalogs.json")}function cc(){let e=process.env.FLOW_HOME??xe.join($e.homedir(),qo);return xe.join(e,"config.json")}function es(e="user"){return e==="project"||e==="local"?xe.join(process.cwd(),Dr,"agents"):xe.join($e.homedir(),Dr,"agents")}var Dr,qo,qe=H(()=>{"use strict";K();Dr=".claude",qo=".flow";});var ng,og,ts,uc=H(()=>{"use strict";qe();ng=5*1024*1024,og=3,ts=class{filePath;constructor(){this.filePath=ac(),this.ensureDir(),this.rotateIfNeeded();}write(t){let r=`[${t.timestamp.toISOString()}] [${t.level.toUpperCase()}] [${t.module}] ${t.message}
|
|
3
|
+
`;try{Ie.appendFileSync(this.filePath,r,"utf-8");}catch{}}ensureDir(){try{let t=xe.dirname(this.filePath);Ie.mkdirSync(t,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(Ie.statSync(this.filePath).size>ng){let r=new Date().toISOString().replace(/[:.]/g,"-"),n=this.filePath.replace(".log",`-${r}.log`);Ie.renameSync(this.filePath,n),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let t=xe.dirname(this.filePath),r=xe.basename(this.filePath,".log"),n=Ie.readdirSync(t).filter(o=>o.startsWith(r+"-")&&o.endsWith(".log")).sort().reverse();for(let o of n.slice(og))Ie.unlinkSync(xe.join(t,o));}catch{}}};});var rs,dc=H(()=>{"use strict";rs=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 ns,pc=H(()=>{"use strict";ns=class{write(t){process.stdout.write(t.message+`
|
|
5
|
+
`);}};});function qi(){return os}function mc(e){return Xi.add(e),()=>{Xi.delete(e);}}var os,Xi,ss,Yi=H(()=>{"use strict";os=[],Xi=new Set;ss=class{write(t){os.push(t),os.length>100&&os.shift();for(let r of Xi)r();}};});function sg(){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 Fe(e,t){if(e==="tui"){let r=sg();Br={context:e,transports:[new ss,new ts],minLevel:r?"debug":"warn",debugModules:r};}else t?.silent?Br={context:e,transports:[],minLevel:"error",debugModules:null}:t?.verbose?Br={context:e,transports:[new rs("cli")],minLevel:"debug",debugModules:null}:Br={context:e,transports:[new ns],minLevel:"info",debugModules:null};}function fc(){return Br.transports}function gc(e,t){let{debugModules:r,minLevel:n}=Br;return Br.context==="tui"&&r&&r!=="all"?r.has(t)?mn[e]>=mn.debug:mn[e]>=mn.warn:mn[e]>=mn[n]}var mn,Br,Zi=H(()=>{"use strict";uc();dc();pc();Yi();mn={debug:0,info:1,warn:2,error:3},Br={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function is(e,t,r){if(!gc(e,t))return;let n={level:e,module:t,message:Hi(r),timestamp:new Date};for(let o of fc())o.write(n);}function x(e){let t=hc.get(e);if(t)return t;let r={debug:n=>is("debug",e,n),info:n=>is("info",e,n),warn:n=>is("warn",e,n),error:n=>is("error",e,n)};return hc.set(e,r),r}var hc,yc=H(()=>{"use strict";Gi();Zi();hc=new Map;});var L=H(()=>{"use strict";yc();Zi();Gi();});function ig(e){return typeof e=="object"&&e!==null&&ea in e&&e[ea]===true}function ta(e){return {serialize(t){let r=JSON.stringify(t),n=e.encrypt(r),o={[ea]:true,envelope:n};return JSON.stringify(o,null," ")},deserialize(t){let r;try{r=JSON.parse(t);}catch{return Qi.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(ig(r))try{let n=e.decrypt(r.envelope);return JSON.parse(n)}catch(n){return Qi.error(`[encryption] Decryption failed: ${n instanceof Error?n.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return Qi.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),r}}}var Qi,ea,ra=H(()=>{"use strict";L();Qi=x("encryption"),ea="__encrypted__";});var na,cg,pt,fn,oa=H(()=>{"use strict";L();na=promisify(execFile),cg=promisify(exec),pt=x("encryption:macos-keyvault"),fn=class{static async isAvailable(){try{let{stdout:t}=await cg("command -v security");return pt.debug(`security binary found at: ${t.trim()}`),!0}catch{return pt.debug("security binary not found in PATH"),!1}}async getSecret(t,r){try{pt.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await na("security",["find-generic-password","-w","-a",r,"-s",t]),o=n.trim();return pt.debug(`security find-generic-password result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return pt.debug(`security find-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){try{pt.debug(`Storing secret: service=${t}, account=${r}`),await na("security",["add-generic-password","-U","-a",r,"-s",t,"-w",n]),pt.debug("security add-generic-password succeeded");}catch(o){let s=o;throw pt.error(`security add-generic-password failed: code=${s.code}, stderr=${s.stderr?.trim()}, message=${s.message}`),o}}async deleteSecret(t,r){try{return pt.debug(`Deleting secret: service=${t}, account=${r}`),await na("security",["delete-generic-password","-a",r,"-s",t]),pt.debug("security delete-generic-password succeeded"),!0}catch(n){let o=n;return pt.debug(`security delete-generic-password failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}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\x0d\x0e-\x1f\x7f]/g,"")}function ce(e){process.stdout.write(T.green(` \u2713 ${y(e)}
|
|
6
6
|
`));}function E(e){process.stderr.write(T.red(` \u2717 ${y(e)}
|
|
7
7
|
`));}function C(e){process.stdout.write(T.cyan(` \u2139 ${y(e)}
|
|
8
|
-
`));}function
|
|
8
|
+
`));}function gn(e,t){let r=t.map(a=>a.map(y)),n=[e,...r],o=e.map((a,l)=>Math.max(...n.map(u=>(u[l]??"").length))),s=o.map(a=>"\u2500".repeat(a)).join(" "),i=a=>a.map((l,u)=>l.padEnd(o[u])).join(" ");process.stdout.write(`
|
|
9
9
|
`),process.stdout.write(` ${T.bold(i(e))}
|
|
10
10
|
`),process.stdout.write(` ${T.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 cr(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
|
+
`);}function je(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
|
+
`);}function Ze(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
+
`);}function q(e){return e instanceof Error?e.message:String(e)}function Pt(e){let t=new Date(e);return isNaN(t.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(t)}var V=H(()=>{"use strict";});async function fg(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 gg(e){let t=ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim().toLowerCase());});})}var sa,ia,mg,te,ur,aa=H(()=>{"use strict";L();V();sa=promisify(execFile),ia=promisify(exec),mg=[{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"}],te=x("encryption:linux-keyvault");ur=class e{static async isAvailable(){try{let{stdout:t}=await ia("command -v secret-tool");te.debug(`secret-tool found at: ${t.trim()}`);}catch{return te.debug("secret-tool binary not found in PATH"),!1}try{return await sa("secret-tool",["lookup","service","__flow_connectivity_check__"]),te.debug("Secret Service D-Bus connectivity check passed"),!0}catch(t){let n=t.stderr?.trim()??"";return n.includes("org.freedesktop.secrets")?(te.debug(`Secret Service D-Bus not available: ${n}`),!1):(te.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let t of mg)try{return await ia(`command -v ${t.name}`),t}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;te.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 te.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let r=await gg(" ? Install secret-tool? This requires sudo. (y/N) ");if(r!=="y"&&r!=="yes")return !1;try{return te.info(`Running: ${t.command}`),await fg("Installing secret-tool...",()=>ia(t.command)),e.isAvailable()}catch{return te.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(t,r){try{te.debug(`Looking up secret: service=${t}, account=${r}`);let{stdout:n}=await sa("secret-tool",["lookup","service",t,"account",r]),o=n.trim();return te.debug(`secret-tool lookup result: ${o?"found":"empty"}`),o||null}catch(n){let o=n;return te.debug(`secret-tool lookup failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),null}}async setSecret(t,r,n){te.debug(`Storing secret: service=${t}, account=${r}`),te.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),te.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),te.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?(te.debug("secret-tool store succeeded"),o()):(te.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=>{te.error(`secret-tool store spawn error: ${l.message}`),s(l);});});}async deleteSecret(t,r){try{return te.debug(`Deleting secret: service=${t}, account=${r}`),await sa("secret-tool",["clear","service",t,"account",r]),te.debug("secret-tool clear succeeded"),!0}catch(n){let o=n;return te.debug(`secret-tool clear failed: code=${o.code}, stderr=${o.stderr?.trim()}, message=${o.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function ca(e,t){return `${e}:${t}`}function ro(e){return e.replace(/'/g,"''")}function as(e){return ["-NoProfile","-NonInteractive","-Command",e]}function bg(e){return `Add-Type -TypeDefinition @'
|
|
17
|
+
${ua}
|
|
18
|
+
'@
|
|
19
|
+
[FlowCredManager]::Read('${ro(e)}')`}function vg(e,t,r){return `Add-Type -TypeDefinition @'
|
|
20
|
+
${ua}
|
|
21
|
+
'@
|
|
22
|
+
[FlowCredManager]::Write('${ro(e)}', '${ro(t)}', '${ro(r)}')`}function Eg(e){return `Add-Type -TypeDefinition @'
|
|
23
|
+
${ua}
|
|
24
|
+
'@
|
|
25
|
+
[FlowCredManager]::Delete('${ro(e)}')`}async function ls(e){return wg("powershell.exe",e)}var wg,mt,la,Sg,xg,Ig,ua,hn,da=H(()=>{"use strict";L();wg=promisify(execFile),mt=x("encryption:windows-keyvault"),la=1,Sg=1,xg=2,Ig=3;ua=`
|
|
17
26
|
using System;
|
|
18
27
|
using System.Runtime.InteropServices;
|
|
19
28
|
using System.Text;
|
|
@@ -49,7 +58,7 @@ public class FlowCredManager {
|
|
|
49
58
|
|
|
50
59
|
public static string Read(string target) {
|
|
51
60
|
IntPtr credPtr;
|
|
52
|
-
if (!CredRead(target, ${
|
|
61
|
+
if (!CredRead(target, ${la}, 0, out credPtr)) return "";
|
|
53
62
|
try {
|
|
54
63
|
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
|
55
64
|
if (cred.CredentialBlobSize <= 0) return "";
|
|
@@ -63,7 +72,7 @@ public class FlowCredManager {
|
|
|
63
72
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
64
73
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
65
74
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
66
|
-
int[] persistLevels = new int[] { ${
|
|
75
|
+
int[] persistLevels = new int[] { ${xg}, ${Ig}, ${Sg} };
|
|
67
76
|
int lastErr = 0;
|
|
68
77
|
try {
|
|
69
78
|
foreach (int persist in persistLevels) {
|
|
@@ -71,7 +80,7 @@ public class FlowCredManager {
|
|
|
71
80
|
try {
|
|
72
81
|
Marshal.Copy(bytes, 0, blobPtr, bytes.Length);
|
|
73
82
|
var cred = new CREDENTIAL();
|
|
74
|
-
cred.Type = ${
|
|
83
|
+
cred.Type = ${la};
|
|
75
84
|
cred.TargetName = targetPtr;
|
|
76
85
|
cred.CredentialBlobSize = bytes.Length;
|
|
77
86
|
cred.CredentialBlob = blobPtr;
|
|
@@ -89,167 +98,159 @@ public class FlowCredManager {
|
|
|
89
98
|
}
|
|
90
99
|
|
|
91
100
|
public static bool Delete(string target) {
|
|
92
|
-
return CredDelete(target, ${
|
|
101
|
+
return CredDelete(target, ${la}, 0);
|
|
93
102
|
}
|
|
94
103
|
}
|
|
95
|
-
`;
|
|
96
|
-
${
|
|
97
|
-
|
|
98
|
-
[
|
|
99
|
-
${Ji}
|
|
100
|
-
'@
|
|
101
|
-
[FlowCredManager]::Write('${Hn(e)}', '${Hn(t)}', '${Hn(r)}')`}function zf(e){return `Add-Type -TypeDefinition @'
|
|
102
|
-
${Ji}
|
|
103
|
-
'@
|
|
104
|
-
[FlowCredManager]::Delete('${Hn(e)}')`}async function Xo(e){return Kf("powershell.exe",e)}var cn=class{static async isAvailable(){try{let{stdout:t}=await Xo(zo('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=Vi(t,r);at.debug(`Looking up secret: target=${n}`);let o=Gf(n),{stdout:s}=await Xo(zo(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=Vi(t,r);at.debug(`Storing secret: target=${o}`);let s=Wf(o,n,r),{stdout:i}=await Xo(zo(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];at.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
-
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw at.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=Vi(t,r);at.debug(`Deleting secret: target=${n}`);let o=zf(n),{stdout:s}=await Xo(zo(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 Xf=32,qf="flow-plugins-cli-fallback",Gi="flow-plugins-cli-fallback",Yf={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 Zf(){let e=`${Pe.hostname()}${Pe.userInfo().username}`;return on.scryptSync(e,qf,Xf)}function Qf(){let e=Zf(),t=new Kn(e),r=Bi(t);return new Hi({projectName:Gi,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}var Yo=null;function qo(){return Yo||(Yo=Qf()),Yo}var Ue=class{warned=false;async getSecret(t,r){return qo().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Yf[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
104
|
+
`;hn=class{static async isAvailable(){try{let{stdout:t}=await ls(as('Write-Output "ok"')),r=t.trim()==="ok";return mt.debug(`PowerShell availability check: ${r?"available":"unexpected output"}`),r}catch(t){let r=t instanceof Error?t.message.split(`
|
|
105
|
+
`)[0]:"unknown error";return mt.debug(`PowerShell not available: ${r}`),!1}}async getSecret(t,r){try{let n=ca(t,r);mt.debug(`Looking up secret: target=${n}`);let o=bg(n),{stdout:s}=await ls(as(o)),i=s.trim();return mt.debug(`CredRead result: ${i?"found":"empty"}`),i||null}catch(n){let o=n instanceof Error?n.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return mt.error(`Failed to read secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),null}}async setSecret(t,r,n){try{let o=ca(t,r);mt.debug(`Storing secret: target=${o}`);let s=vg(o,n,r),{stdout:i}=await ls(as(s)),a=i.trim();if(a.startsWith("OK:")){let u=a.split(":")[1];mt.debug(`CredWrite succeeded (persist=${u})`);return}let l=a.startsWith("ERR:")?a.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${l}`)}catch(o){let s=o instanceof Error?o.message.split(`
|
|
107
|
+
`)[0]:"unknown error",i=`Failed to store secret in Windows Credential Manager [service="${t}", account="${r}"]: ${s}`;throw mt.error(i),new Error(i)}}async deleteSecret(t,r){try{let n=ca(t,r);mt.debug(`Deleting secret: target=${n}`);let o=Eg(n),{stdout:s}=await ls(as(o)),i=s.trim()==="True";return mt.debug(`CredDelete result: ${i}`),i}catch(n){let o=n instanceof Error?n.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return mt.debug(`Failed to delete secret from Windows Credential Manager [service="${t}", account="${r}"]: ${o}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function kg(){let e=`${$e.hostname()}${$e.userInfo().username}`;return pn.scryptSync(e,Tg,Pg)}function Ag(){let e=kg(),t=new Qn(e),r=ta(t);return new pa({projectName:ma,serialize:r.serialize,deserialize:r.deserialize,configFileMode:384})}function cs(){return us||(us=Ag()),us}var Pg,Tg,ma,Cg,us,Ke,no=H(()=>{"use strict";Ji();ra();Pg=32,Tg="flow-plugins-cli-fallback",ma="flow-plugins-cli-fallback",Cg={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)"};us=null;Ke=class{warned=!1;async getSecret(t,r){return cs().get(`${t}:${r}`)??null}async setSecret(t,r,n){if(!this.warned){let o=Cg[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;}qo().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=qo(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),true):false}getStoragePath(){return qo().path}static hasExistingData(){try{let t=new Hi({projectName:Gi});return ye.existsSync(t.path)}catch{return false}}static clearFallbackFile(){try{let t=new Hi({projectName:Gi});ye.rmSync(t.path,{force:!0});}catch{}Yo=null;}};async function Wi(){if(Ue.hasExistingData())return new Ue;switch(process.platform){case "darwin":return await an.isAvailable()?new an:new Ue;case "linux":return await nr.isAvailable()?new nr:await nr.ensureInstalled()?new nr:new Ue;case "win32":return await cn.isAvailable()?new cn:new Ue;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var zl=x("config:credentials"),Bt="flow-plugins-cli",zi="credentials",Xi="token-cache",qi="user-info",es=null;async function or(){return es||(es=Wi()),es}function ts(){es=null;}async function Z(){let t=await(await or()).getSecret(Bt,zi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function sr(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 zl.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await or()).setSecret(Bt,zi,JSON.stringify(e));}async function Xl(){let e=await or();await e.deleteSecret(Bt,zi),await e.deleteSecret(Bt,Xi),await e.deleteSecret(Bt,qi);}async function ql(){return (await or()).getStoragePath()}async function Yl(e){await(await or()).setSecret(Bt,Xi,JSON.stringify(e));}async function rs(){let t=await(await or()).getSecret(Bt,Xi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ns(e){await(await or()).setSecret(Bt,qi,JSON.stringify(e));}async function os(){let t=await(await or()).getSecret(Bt,qi);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function ir(){let e=await rs();return e?new Date(e.expiresAt)>new Date:false}function It(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,zl.debug(`[customUrl] Service URLs overridden to base: ${t}`);}function un(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")}}dn();var Zi=x("api:auth");function og(e){if(!Ut.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}var Ql={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 sg(e){if(e instanceof HTTPError){let t=e.response.status;Zi.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&&Ql[r]?new Error(Ql[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?(Zi.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Zi.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Mr(e){let t=ar("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");og(e.tenant);let r;try{r=await wu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await sg(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await sr(e),await Yl({accessToken:r.access_token,expiresAt:n});let o=un(r.access_token);await ns({sub:o.sub,name:o.name,email:o.email});}var ec=x("lib:tokenProvider");async function bt(){if(await ir()){let n=await rs();if(n)return n.accessToken}ec.debug("Token expired or missing, re-authenticating...");let t=await Z();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ue.clearFallbackFile(),ts(),await Mr(t);let r=await rs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return ec.debug("Token refreshed successfully"),r.accessToken}dn();var ss=x("api:metrics");function tc(){return ar("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function rc(e,t,r){return wu.post(e,{json:t,headers:r})}async function ag(e){let t=await os();if(t)return t;let r=un(e),n={sub:r.sub,name:r.name,email:r.email};return await ns(n),n}async function v(e,t){let r=await bt(),n=await ag(r),o=await Z();if(!Ut.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ai,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await rc(tc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),ss.debug(`Metrics event sent: ${e}`);}catch(i){throw ss.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function nc(e,t,r){try{let n=r&&Ut.test(r)?r:"unknown",o={action:e,booster:Ai,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await rc(tc(),o,{FlowTenant:n}),ss.debug(`Anonymous metrics event sent: ${e}`);}catch(n){ss.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 lg={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},lt={...lg};function oc(e){let t=Date.now();lt={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Rr(e){lt.currentStep=e,lt.stepStart=Date.now();}function W(){return {...lt}}function lr(){return lt.sessionStart===0?0:Date.now()-lt.sessionStart}function _r(){return lt.stepStart===0?0:Date.now()-lt.stepStart}function sc(){lt.tuiSessionStart=Date.now();}function ic(){return lt.tuiSessionStart===0?0:Date.now()-lt.tuiSessionStart}var cg=3e3,ug=x("abandonment");async function is(e){let{currentStep:t,sessionStart:r}=W();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:lr()};try{await Promise.race([v(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),cg))]);}catch(o){ug.warn(`Abandonment event failed: ${String(o)}`);}}function ac(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}var dg=3e3,pg=x("session-end");async function Wn(e,t,r){let n=ic(),s=[v(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(is(e));try{await ac(Promise.all(s).then(()=>{}),dg);}catch(i){pg.warn(`Session end event failed: ${String(i)}`);}}var hg=2e3;function cc(){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),Wn("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},hg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var xg=16;function uc({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(xg)}),jsx(Text,{color:o?"cyan":"gray",children:a}),o&&jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",s]})})]})}function dc({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();rn.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:nn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}function pc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[tr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}function mc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[tr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var We=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:t=>e({credentials:t,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:t=>e({justAuthenticated:t})}));function Ur(){return he__default.join(Pe__default.homedir(),".claude","settings.json")}function gc(e){return `${(e&&e.trim().length>0?e.trim():Do).replace(/\/+$/,"")}/flow-litellm/`}function eo(){let e=Ur();if(!ye__default.existsSync(e))return {status:"missing"};let t=ye__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 ls(e){let t=Ur();ye__default.mkdirSync(he__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;ye__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ye__default.renameSync(r,t);}function hc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function sa(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function yc(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var Cg=3600,Br=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function to(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function kg(e){return Tg.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:Cg})}function cs(e,t={}){let r=eo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Br;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?sa(r.settings):null,s=r.status==="ok"?yc(r.settings):null,i=t.jwtOverride??kg(e),a=gc(e.customUrl),l=hc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function us(e){ls(e.merged);}function wc(){let e=eo();return e.status!=="ok"?false:sa(e.settings)!==null}function Ag(){let e=Nl();if(!ye__default.existsSync(e))return {};try{return JSON.parse(ye__default.readFileSync(e,"utf-8"))}catch{return {}}}var ia=null;function $g(){return ia===null&&(ia=Ag()),ia}function dr(){return !!$g().ENABLE_EXPERIMENTAL_BETAS}function _g(){return te.filter(e=>e.platforms[process.platform]?.status==="supported")}function xc(e){let t=_g();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var ds={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=he__default.join(Pe__default.homedir(),".claude","settings.json"),r=ye__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??Do),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},Dg={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=dr()?[ds,Dg]:[ds];var Ng=x("moduleState");function ms(){let e=process.env.FLOW_HOME??he__default.join(Pe__default.homedir(),".flow");return he__default.join(e,"modules.json")}var Fg={retries:5,minTimeout:50};async function Ic(e,t){ye__default.mkdirSync(he__default.dirname(e),{recursive:true});let r=await Bg.lock(e+".lock",{realpath:false,retries:Fg});try{return await t()}finally{await r();}}function bc(){let e=ms();if(!ye__default.existsSync(e))return [];try{let t=JSON.parse(ye__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(Ng.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),ye__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return ye__default.rmSync(e,{force:true}),[]}}function Nr(){return bc()}function vc(e){let t=ms();ye__default.mkdirSync(he__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};ye__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),ye__default.renameSync(r,t);}function ze(e){return Nr().find(t=>t.alias===e)??null}async function ct(e){let t=ms();await Ic(t,async()=>{let r=bc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,vc(r);});}async function Fr(){let e=ms();ye__default.existsSync(e)||await Ic(e,async()=>{ye__default.existsSync(e)||vc([]);});}var Vg=promisify(execFile);function pr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function Et(e){let t=process.platform==="win32"?"where":"which";try{return await Vg(t,[e]),!0}catch{return false}}function Nt(){return process.platform==="win32"?"npm.cmd":"npm"}var Ec=promisify(execFile),mn=class{type="npm";async isAvailable(){return Et("npm")}async install(t){let r=await this.getInstalledVersion(t);return r?{success:true,version:r,method:"npm",durationMs:0}:this.runNpmInstall(t,false)}async update(t,r){return this.runNpmInstall(t,true)}async getInstalledVersion(t){let r=pr(t,"npm");if(!r)return null;try{let{stdout:n}=await Ec(Nt(),["list","-g",r.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(n).dependencies?.[r.package]?.version??null}catch{return null}}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(t,r){let n=Date.now(),o=pr(t,"npm");if(!o)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-n};let s=r?`${o.package}@latest`:o.package;try{return await Ec(Nt(),["install","-g",s],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"npm",durationMs:Date.now()-n}}catch(i){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:i instanceof Error?i.message:String(i)},durationMs:Date.now()-n}}}};var fs=promisify(execFile),zg=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,gs=class{type="homebrew";async isAvailable(){return Et("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=pr(t,"homebrew");return r?this.getVersionByFormula(r.formula):null}async uninstall(t){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(t,r){let n=Date.now(),o=pr(t,"homebrew");if(!o)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-n};let s=r==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return o.tap&&(await fs("brew",["tap",o.tap]),await fs("brew",["trust",o.tap])),await fs("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 fs("brew",["list","--versions",t]),n=r.trim().match(zg);return n?n[2]:null}catch{return null}}};var fn=promisify(execFile),Tc=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Cc(){let e=process.env.FLOW_HOME??he__default.join(Pe__default.homedir(),".flow");return he__default.join(e,"bin")}var hs=class{type="curl";async isAvailable(){return Et("curl")}async install(t){let r=Date.now(),n=pr(t,"curl");if(!n)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-r};let o=typeof n.url=="function"?n.url(process.arch):n.url;return (n.mode??"binary")==="script"?this.installScript(o,n.checksumUrl,t,r):this.installBinary(o,n.checksumUrl,t,r)}async update(t,r){return this.install(t)}async getInstalledVersion(t){let r=he__default.join(Cc(),he__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await fn(n,["--version"]),s=o.match(Tc);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=he__default.join(Pe__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await fn("curl",["-sSL","--fail","-o",s,t]),r){let a=await this.validateChecksum(s,r);if(!a.valid){try{ye__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return ye__default.chmodSync(s,448),await fn("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{ye__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=Cc(),i=he__default.join(s,he__default.basename(n.binaryName)),a=false;try{if(ye__default.mkdirSync(s,{recursive:!0}),a=!0,await fn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return ye__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}ye__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await fn(i,["--version"]),c=u.match(Tc);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{ye__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=he__default.join(Pe__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await fn("curl",["-L","--fail","-o",n,r]);let o=ye__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=ye__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{ye__default.unlinkSync(n);}catch{}}}};var kc="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(kc=e.version);}catch{}var le=kc;var xe=x("moduleInstaller");function Tt(e){switch(e){case "npm":return new mn;case "homebrew":return new gs;case "curl":return new hs}}async function ro(e,t,r){try{await v(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){xe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function fr(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){xe.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Tt(r),u=false;try{u=await l.isAvailable();}catch(d){xe.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await ro(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,trigger:t});}catch(d){xe.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);xe.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await ct({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await v(I.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){xe.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await th(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await ro(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function th(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await Z(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return xe.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,xe.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&xe.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&xe.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function ys(e,t){let r=Date.now(),n=ze(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Tt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:le,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 ct({...n,installedVersion:i.version??n.installedVersion,lastChecked:new Date().toISOString()}),t==="command")try{await v(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){xe.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(I.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 v(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){xe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}var ws=x("flowAiObsSetup");async function Ss(e,t){try{if(!await new mn().isAvailable().catch(()=>!1))return ws.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await fr(ds,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(ws.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(ws.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return ws.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}function Ac(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 rh=x("useAuthSetup");function $c(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:b}=We(),_=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},M=()=>{v(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:lr(),interface:"tui"}).catch(()=>{});},P=async F=>{g.current=true;let J={...r.current,customUrl:n.current??void 0};try{F&&us(F),await sr(J);}catch(K){l(K instanceof Error?K.message:"Failed to persist credentials"),_(),g.current=false;return}let{clientSecret:A,...U}=J;w(U),b(true),M(),await Ss(n.current,o.current).catch(K=>rh.warn(`installFlowAiObs threw unexpectedly: ${String(K)}`)),xs({starterKit:U.starterKit});},$=async()=>P(),R=async F=>P(F),D=F=>{try{let J={...r.current,customUrl:n.current??void 0};return cs(J,{allowOverwriteMalformed:F,jwtOverride:e.trim()})}catch(J){return J instanceof Br?(m("malformedConfirm"),null):(l(J instanceof Error?J.message:"Failed to read settings.json"),m("fields"),null)}},X=()=>{let F=D(true);F&&(f(F),R(F));},k=async()=>{let F=e.trim();if(!F){i("This field is required");return}let J;try{J=to(F);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=J,m("customUrl");},j=F=>{n.current=F,m("email");},z=F=>{o.current=F,B();},B=async()=>{let F=n.current;F&&It(F),c(true),l(null),h.current+=1;try{await Mr(r.current);let J=D(!1);J&&(f(J),m("preview"));}catch(J){let A=J instanceof Error?J.message:"Authentication failed";l(A),nc(I.CLI_AUTH_FAILED,{error_code:Ac(J),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:_,handleSubmit:k,goToEmailStep:j,handleEmailConfirm:z,commitAndProceed:R,skipJwtAndProceed:$,planPersistOverwrite:X}}function Lc(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=$c(),[g,w]=useState("confirm"),[b,_]=useState(""),M=useRef(""),[P,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),M.current="",_(""),$(false));},[o]),useInput((R,D)=>{if(!(n||i.current)){if(o==="preview"){D.return&&s?p(s):D.escape?f():R==="q"&&u();return}if(o==="malformedConfirm"){D.return?h():D.escape&&u();return}if(o==="customUrl"){if(g==="confirm")R==="y"||R==="Y"?w("input"):(R==="n"||R==="N"||D.return)&&d(null);else if(D.escape)M.current="",_(""),w("confirm");else if(D.return){let X=M.current.trim();X.length>0&&en.test(X)?($(false),d(X)):X.length>0&&$(true);}else D.backspace||D.delete?(M.current=M.current.slice(0,-1),_(M.current)):R&&!D.ctrl&&!D.meta&&(M.current=M.current+R,_(M.current),$(false));return}o!=="email"&&D.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[tr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:b}),jsx(Text,{color:"cyan",children:"\u2588"})]}),P&&jsx(Text,{color:"red",children:tn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[tr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(dc,{onConfirm:m})]}):o==="preview"&&s?jsx(pc,{plan:s}):o==="malformedConfirm"?jsx(mc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[tr," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:jsx(Box,{marginBottom:1,children:jsx(uc,{label:"JWT",value:e,onChange:R=>{a(R),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function hn(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(ah,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",le]})})]})}var Dc=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],Q=dr()?Dc:Dc.slice(0,3);function lh(e){return Q.findIndex(t=>t.id===e)}function ca(e,t,r){let n=lh(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 Bc={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Nc({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?`${Bc[r]} (${e})`:Bc[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Be=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function jc(){let e=S(i=>i.focus),t=Be(i=>i.query),r=Be(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 ph=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...Qr[e]})),mh=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...Ll[e]}));function Kc(){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"]})]}),ph.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"]})]}),mh.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 Vc({type:e}){let{label:t,color:r}=Qr[e];return jsx(Text,{color:r,children:t})}function Gc({origin:e}){return e===Fn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}var bs=hh.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(Vc,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(Gc,{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 ",xt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function yn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}function Xc({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(yn,{message:t});let n=Math.max(0,r-Math.floor(Je/2)),o=Math.min(e.length,n+Je);o===e.length&&(n=Math.max(0,o-Je));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(bs,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function Zc({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}function eu({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(yn,{message:t});let i=n.findIndex(p=>p.kind==="item"&&p.itemIndex===r),a=i>=0?i:0,l=Math.max(0,a-Math.floor(Je/2)),u=Math.min(n.length,l+Je);u===n.length&&(l=Math.max(0,u-Je));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(Zc,{label:p.label,pathHint:p.pathHint},p.key):jsx(bs,{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 Eh={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Ph({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(jc,{}),jsx(Kc,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:Eh[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx(eu,{groups:n,emptyMessage:r}):jsx(Xc,{items:e,emptyMessage:r})]})}function tu({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(Ph,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var kh={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 vs(){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:[kh[e],t?" | Ctrl+D: debug log":""]})})}function ru({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 Es({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(md,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function ha(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var iu=20;function Ps(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*iu),s="\u2588".repeat(o)+"\u2591".repeat(iu-o),i=`${ha(e)} / ${ha(t)}`;return {bar:s,percent:n,label:i}}function Ts({received:e,total:t}){let{bar:r,percent:n,label:o}=Ps(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Cs({message:e,onRetry:t,onBack:r}){return useInput((n,o)=>{n==="r"&&o.ctrl&&t?t():o.escape&&r&&r();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),t&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),r&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function Xe({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}var xa=Object.entries(jn),uu=[...xa.map(([,e])=>e.actionLabel),"Cancel"],du=Object.fromEntries(xa.map(([,e])=>[e.actionLabel,e.description]));function pu(e){let t=xa.find(([,r])=>r.actionLabel===e);return t?t[0]:null}var Vh=x("provider.registry"),Jh=3e4,As=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()+Jh}),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"&&Vh.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 Hh={user:"global",project:"project",local:"local"};function $s(e){return e?Hh[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},hr=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};dn();function mt(){return wu.create({prefix:ar("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await bt();e.headers.set("Authorization",`Bearer ${t}`);let r=await Z();r?.tenant&&Ut.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var Wh=x("catalog.registry"),Ls=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);Wh.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 ty={retries:5,minTimeout:50};async function Ia(e,t){mkdirSync(dirname(e),{recursive:true});let r=await Bg.lock(e+".lock",{realpath:false,retries:ty});try{return await t()}finally{await r();}}var Ms=class{filePath;constructor(t){this.filePath=t??Bl();}async read(){try{let t=await readFile(this.filePath,"utf-8");return JSON.parse(t).catalogs??[]}catch(t){if(t.code==="ENOENT")return [];throw t}}async write(t){let r=dirname(this.filePath);await mkdir(r,{recursive:true});let n=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(n,JSON.stringify({catalogs:t},null,2),"utf-8"),await rename(n,this.filePath);}async add(t){await Ia(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 Ia(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Ia(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 ry=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;function io(e){if(!e||!ry.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}var ny=/^[^@]+@[^@]+$/;function Sn(e){return ny.test(e)}function xn(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}var oy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;function ba(e){if(!oy.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 In(e,t){let r=xn(e);ba(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}var sy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,iy=/^https:\/\/[\w./:@?&=+#%-]+$/;function Rs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!sy.test(t)&&!iy.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var ay=x("catalog.flow-api"),_s=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 mt().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){io(t);try{return await mt().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 mt().head("v1/plugins/catalog"),ay.debug("ping ok"),!0}catch{return false}}};var ce=new Ls,jt=new Ms;ce.register(new _s);var Iu=false;async function bu(){if(Iu)return;Iu=true;let e=await jt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(va(),xu));for(let r of e)ce.register(new t(r.id,r.name,r.source));}var vu=2;async function yr(){return ce.fetchAll()}async function Eu(){return ce.fetchAllWithErrors()}async function vn(e){io(e);try{return await mt().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 Pu(e,t){io(e);try{let r=await mt().get(`v1/plugins/${e}/archive`),n=r.headers.get("x-archive-size"),o=n?Number(n):NaN,s=Number.isFinite(o)&&o>0?o:0,i=s>0,a=r.body;if(!a)throw new Error("Failed to download plugin: response has no body");let l=a.getReader(),u=[],c=0;for(;;){let{done:d,value:m}=await l.read();if(d)break;if(c+=m.byteLength,i&&c>s*vu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${c} bytes, expected at most ${s*vu}`);u.push(m),i&&t?.(c,s);}return Buffer.concat(u)}catch(r){throw r instanceof Error?r.message.includes("Download exceeded expected size")?r:new Error(`Failed to download plugin: ${r.message}`):r}}async function Ds(){try{let{profiles:e}=await mt().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 Tu(e,t){let r=he.resolve(t);await Ct.mkdir(r,{recursive:true});let n=he.join(he.dirname(r),`${randomUUID()}.zip`);try{await Ct.writeFile(n,e);let o=await py.Open.file(n),s=he.normalize(r+he.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=he.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(he.resolve(he.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Ct.unlink(n);}catch{}}}async function Ea(e){await Ct.rm(e,{recursive:true,force:true});}async function wr(){let e=Ol();await Ct.mkdir(he.dirname(e),{recursive:true});try{await Ct.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await Bg.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}function gy(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:q,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Au(){let e=Bo();if(!ye__default.existsSync(e))return null;try{return JSON.parse(ye__default.readFileSync(e,"utf-8"))}catch{return null}}function hy(){let e=Au();if(e)return e;let t=gy(),r=Bo();return ye__default.mkdirSync(he__default.dirname(r),{recursive:true}),Pa(t),t}function Pa(e){let t=Bo(),r=`${t}.${randomUUID()}.tmp`;ye__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),ye__default.renameSync(r,t);}function yy(){let e=No(),t={};try{ye__default.existsSync(e)&&(t=JSON.parse(ye__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[q])return;t[q]={source:{source:"github",repo:"cit-flow/flow-skills"},installLocation:Dl(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;ye__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ye__default.renameSync(r,e);}function $u(e,t){ft(e.name),yy();let r=Mi(e.name);ye__default.mkdirSync(he__default.dirname(r),{recursive:true});try{ye__default.lstatSync(r),ye__default.rmSync(r,{recursive:!0,force:!0});}catch{}ye__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=hy();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}),Pa(n));}function Ta(e){ft(e);let t=Mi(e);try{ye__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=Au();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&Pa(r);}var Sy=x("mcpConfigReader"),xy=500,Iy=512;function by(){return he__default.join(Pe__default.homedir(),".claude.json")}function vy(){return he__default.join(process.cwd(),".mcp.json")}function Mu(e){if(!ye__default.existsSync(e))return null;try{return JSON.parse(ye__default.readFileSync(e,"utf-8"))}catch{return Sy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ca(e){if(!ao(e))return {};let t=e.mcpServers;return ao(t)?t:{}}function ka(e,t){return Object.keys(e).slice(0,xy).map(n=>({name:y(n.slice(0,Iy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function _u(){let e=[],t=by(),r=Mu(t);if(ao(r)){let a=r,l=Ca(a);e.push(...ka(l,"user"));let u=process.cwd();if(ao(a.projects)){let c=a.projects[u];if(ao(c)){let d=Ca(c);e.push(...ka(d,"local"));}}}let n=vy(),o=Mu(n),s=Ca(o);e.push(...ka(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}var qe=x("storage");async function Py(e,t,r){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:W().interfaceType});}catch(n){qe.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function Ty(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:W().interfaceType}).catch(o=>qe.warn(`Failed to send ${t} metrics: ${String(o)}`));}function Ma(){return he__default.join(Pe__default.homedir(),".claude","plugins","installed_plugins.json")}function Cy(){return he__default.join(Pe__default.homedir(),".claude","plugins")}function Os(e){let t;try{t=ye__default.realpathSync(e);}catch{t=he__default.resolve(e);}let r=he__default.resolve(Cy()),n=he__default.resolve(he__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+he__default.sep),s=t.startsWith(n+he__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Du(e="user"){return e==="local"?he__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?he__default.join(process.cwd(),".claude","settings.json"):he__default.join(Pe__default.homedir(),".claude","settings.json")}function Ze(){let e=Ma();if(!ye__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(ye__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function Ra(){let e=Ma();try{let t=await ye__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function ky(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function Ou(e,t){try{ye__default.mkdirSync(he__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;ye__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),ye__default.renameSync(r,e);}catch(r){throw ky(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function Ye(e){Ou(Ma(),e);}function lo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function Ay(e,t){let r=he__default.join(e,".claude-plugin"),n=he__default.join(r,"plugin.json");if(ye__default.existsSync(n))try{return JSON.parse(ye__default.readFileSync(n,"utf-8"))}catch{return null}let o=he__default.join(r,"marketplace.json");if(ye__default.existsSync(o))try{let s=JSON.parse(ye__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function _a(e="user"){let t=Du(e);if(!ye__default.existsSync(t))return {};try{return JSON.parse(ye__default.readFileSync(t,"utf-8"))}catch{return {}}}function Uu(e,t="user"){Ou(Du(t),e);}function $y(e,t){let{name:r,marketplace:n}=lo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>lo(i).name===r)[0],!o)throw qe.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function Ly(e,t){let{name:r,marketplace:n}=lo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>lo(i).name===r)[0],o?{key:o,name:r}:null}function Aa(e="user"){return _a(e).enabledPlugins??{}}function $a(e,t="user"){let r=_a(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,Uu(r,t);}function co(e,t,r="user"){let n=_a(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},Uu(n,r);}function My(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 re(){let e=Ze(),t=Aa(),r=Aa("project"),n=Aa("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=lo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return My(p).map(h=>{let g=Ay(h.installPath,d),b=(o[h.scope]??t)[u];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:b===false?"disabled":"enabled"}})}),i=_u(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function uo(e,t){qe.debug(`[${e}] Acquiring lock to uninstall`);let r=await wr();try{let n=Ze(),o=Ly(e,n.plugins);if(!o)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:s,name:i}=o,a=n.plugins[s];if(t){let l=a.find(d=>d.scope===t);if(!l)throw new Error(`Plugin '${i}' is not installed in ${t} scope`);qe.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),Os(l.installPath);let u=he__default.dirname(l.installPath);Os(u),qe.debug(`[${i}] Removing directory: ${u}`),ye__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;Ye({...n,plugins:m}),$a(s,t),Ta(i);}else n.plugins[s]=c,Ye(n),$a(s,t);}else {qe.debug(`[${i}] Resolved key: ${s}`);for(let c of a){Os(c.installPath);let d=he__default.dirname(c.installPath);Os(d),qe.debug(`[${i}] Removing directory: ${d}`),ye__default.rmSync(d,{recursive:!0,force:!0}),$a(s,c.scope);}Ta(i);let{[s]:l,...u}=n.plugins;Ye({...n,plugins:u});}await Py(i,a[0].origin??"internal",a[0].type??"skill"),qe.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function po(e,t,r){qe.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await wr();try{let o=Ze(),{key:s,name:i}=$y(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";qe.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),co(s,t==="enabled",l),Ty(i,t,u),qe.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}var Ry=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,_y=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function ft(e){if(!Ry.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Dy(e){if(!_y.test(e))throw new Error(`Invalid plugin version from manifest: "${e}". Versions must follow semver format (e.g. 1.0.0 or 1.0.0-beta.1).`)}var Sr=x("installer");function Oy(e,t){let r=`${e}@${q}`,o=Ze().plugins[r];if(o&&!t)throw new Ne(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function Uy(e,t,r){r&&await Ea(t);try{Sr.debug(`[${t}] Extracting archive...`),await Tu(e,t);}catch(n){throw await Ea(t),n}}function By(e,t,r,n,o,s="claude-code",i){let a=Ze(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],Ye(a),co(e,true,n);}async function Ny(e,t,r,n,o,s){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:W().interfaceType});}catch(i){Sr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Fy(e,t,r,n){try{await v(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:W().interfaceType});}catch(o){Sr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function ke(e,t={}){let r=Date.now(),n=null;try{Sr.debug(`[${e}] Acquiring lock...`),n=await wr();let{pluginKey:o,alreadyInstalled:s}=Oy(e,t.force);Sr.debug(`[${e}] Fetching manifest...`);let i=await vn(e);ft(i.name),Dy(i.version),Sr.debug(`[${e}] Downloading archive...`);let a=await Pu(e,t.onDownloadProgress),l=t.scope??"user",u=t.type??"skill",c=_l(i.name,i.version);await Uy(a,c,!!s&&!!t.force),By(o,c,i.version,l,"internal",t.providerId,u),$u(i,c);let d=Date.now()-r;Sr.debug(`[${e}] Installed successfully in ${d}ms`);let m={name:i.name,version:i.version,path:c,duration_ms:d};return t.skipMetrics||await Ny(i.name,i.version,d,$s(l),"internal",u),m}catch(o){throw await Fy(e,o,"internal",t.type??"skill"),Sr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}var jy=x("commands:helpers");async function ie(){let e=await Z();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&It(e.customUrl);try{await bt();}catch(t){return jy.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function kt(e){let t=Da.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 Bu(e){let t=Da.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}var Pn=x("claudeProxy"),Na="claude ",Nu="flow ",Oa=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},En=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";}},Ky=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Vy=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,Jy={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Hy=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Gy=/^(flow|claude)\s+auth\s+login(\s|$)/,Fu=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function ju(e){return Fu.test(e.trim())}function Wy(e){return Fu.exec(e.trim())?.[2]??""}async function Ku(e){let t=Wy(e);ba(t);let r=Date.now();Pn.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 Fa(n)?new Ua:n}}function zy(e){Vu(e);let t=e.slice(Na.length);if(!Ky.test(t))throw new En(e)}var Us=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 Vu(e){if(!e||!/^claude /.test(e))throw new Oa(e)}function Xy(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!Vy.test(r))throw new En(`Unexpected flag: ${r}`);let n=Jy[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new En(`Flag ${r} requires a value`);if(!n.test(o))throw new En(`Unsafe value for flag ${r}`);t++;}}}async function be(e){Vu(e);let t=e.slice(Na.length).split(/\s+/).filter(Boolean);Xy(t);let r=qy(t);Pn.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 Pn.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 Fa(o)?new Us:o}}function qy(e){return e.length>=3?e[2]:e.join(" ")}function Fa(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Yy(e){return e.startsWith(Nu)?Na+e.slice(Nu.length):e}function Zy(e){return Hy.test(e)||Gy.test(e)}function Qy(e){let t=0;for(;t<e.length&&Zy(e[t]);)t++;return e.slice(t)}var ew=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function tw(e,t){return !t||e.includes("--scope")||!ew.test(e)?e:`${e} --scope ${t}`}async function mo(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Qy(r).map(i=>Yy(i)).map(i=>tw(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)zy(i);Pn.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await be(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await be(o[i]),s.exitCode!==0)return s;return s}async function Bs(e,t,r){let n=xn(e),o=t?.trim();if(!o&&(o=(await Bu(`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=Rs(o),r?.(),Pn.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"}`);Pn.debug(`[${n}] Marketplace added successfully`);}catch(s){throw Fa(s)?new Us:s}}var iw=6e4,xr=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:iw}}).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 xr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new xr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new xr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function $t(e){let t=normalize(resolve(e)),r=normalize(resolve(tmpdir()));if(!t.startsWith(r+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function Gr(e,t=["--version"]){try{return (await execa(e,t,{reject:!1})).exitCode===0}catch(r){if(r instanceof Error&&"code"in r&&r.code==="ENOENT")return false;throw r}}function lw(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function cw(e){return typeof e=="object"&&e!==null&&e.source==="url"}function uw(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Tn(e,t){let r=e.source;if(lw(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(cw(r))return {cloneUrl:r.url,subPath:"."};if(uw(r))return {cloneUrl:`https://github.com/${r.repo}`,subPath:"."};if(typeof r=="string"){if(r.startsWith("https://")||r.startsWith("git@"))return {cloneUrl:r,subPath:"."};if((r.startsWith("./")||r===".")&&t){let n=r==="."?".":r.replace(/^\.\//,"")||".";return {cloneUrl:t,subPath:n}}}return null}function Qe(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Lt=x("claude-code.adapter");function mw(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=No();if(!ye__default.existsSync(s))return r;try{let i=JSON.parse(ye__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 qu(e,t){let r=e.catalogId?ce.getAdapter(e.catalogId):void 0,n=Tn(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=mw(e.catalogId,r?.source),i=t.scope??"user",a;o?a=Ri(s,e.name,"external"):a=join(Ar(i==="user"?"global":"project"),e.name);let l=null;try{ft(e.name),l=await At(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(ye__default.existsSync(a)&&ye__default.rmSync(a,{recursive:!0,force:!0}),ye__default.mkdirSync(dirname(a),{recursive:!0}),ye__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await Ra(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],Ye(d),co(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Lt.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await $t(l).catch(()=>{});}}async function ja(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:$s(n),version:"unknown",duration_ms:t,interface:W().interfaceType});}catch(o){Lt.warn(`Failed to send external install metrics: ${String(o)}`);}}async function zu(e,t,r){try{await v(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:W().interfaceType});}catch(n){Lt.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var fw={async install(e,t){if(e.origin===Zr&&!e.installCommand&&!Sn(e.name))return qu(e,t);if(e.origin===Zr&&e.installCommand){let r=e.type??"skill",n=await mo(e.installCommand,t.scope);return n.exitCode===0?(await ja(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await zu(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=In(e.name,t.scope);Lt.debug(`[${e.name}] Attempting install: ${n}`);let o=await be(n);if(o.exitCode===0)return await ja(e.name,o.duration_ms,r,t.scope),{success:true};Lt.debug(`[${e.name}] First attempt failed, adding marketplace`),await Bs(e.name,t.marketplaceSource,()=>{});let s=await be(n);return s.exitCode===0?(await ja(e.name,s.duration_ms,r,t.scope),{success:true}):(await zu(e.name,new Error(s.stderr||"Install failed"),r),{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`})}try{let r=await ke(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Lt.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await uo(e,t);},getInstallPath(e,t){return ""}};function Xu(e){return {async install(t,r){if(t.origin===Zr&&!t.installCommand&&!Sn(t.name))return qu(t,r);if(!t.installCommand)try{let o=await ke(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Lt.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Lt.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await mo(t.installCommand,r.scope);return n.exitCode===0?{success:true}:{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`}},async uninstall(t,r){let n=Ze(),o=`${t}@${q}`;if(n.plugins[o]){await uo(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 gw(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!ye__default.existsSync(t))continue;let r=ye__default.readdirSync(t).filter(n=>n.endsWith(".md")&&ye__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function Ka(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,Ka(r)]))}function Yu(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(Ka(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(Ka(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=Yu(s,o):r[n]=o;}return r}async function Zu(e,t,r,n){let o=await Ra(),s=`${e}@claude-code`,i={scope:t,installPath:r,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:n},a=o.plugins[s]??[];o.plugins[s]=[...a.filter(l=>l.scope!==t),i],Ye(o);}var hw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ce.getAdapter(e.catalogId):void 0,o=Tn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ft(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=gw(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=jo(r);ye__default.mkdirSync(l,{recursive:!0});let u=Qe(e.name);if(a.length===1)ye__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=Qe(basename(d,".md"));ye__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Zu(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Lt.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=jo(t),n=Qe(e);if(ye__default.existsSync(r))for(let a of ye__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))ye__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=Ze(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;Ye({...s,plugins:l});}else Ye({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(jo(t),`${Qe(e)}.md`)}},yw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ce.getAdapter(e.catalogId):void 0,o=Tn(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{ft(e.name),s=await At(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!ye__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(ye__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=eo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=Yu(m,u);return ls({...d,hooks:p}),await Zu(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Lt.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 ""}},Ns=class{id="claude-code";name="Claude Code";async isAvailable(){return Gr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:fw,skill:Xu("skill"),mcp:Xu("mcp"),agent:hw,hook:yw}};function Fs(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 Sw=new Set(["gh"]),xw=Fs(Sw,"use: gh copilot mcp remove <name>"),js=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Gr("gh",["--version"])?Gr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:xw}};var Iw=new Set(["opencode"]),bw=Fs(Iw,"use: opencode config remove mcp <name>");function vw(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
112
|
-
`)}function Qu(){return {async install(e,t){try{ft(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ce.getAdapter(e.catalogId):void 0,n=Tn(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=Fo(t.scope??"user"),a=join(s,".opencode","plugins");if(ye__default.existsSync(a)){let l=ye__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};ye__default.mkdirSync(i,{recursive:!0}),ye__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);ye__default.existsSync(l)&&ye__default.rmSync(l,{recursive:!0,force:!0}),ye__default.mkdirSync(l,{recursive:!0}),ye__default.cpSync(s,l,{recursive:!0}),ye__default.mkdirSync(i,{recursive:!0}),ye__default.writeFileSync(join(i,`${e.name}.js`),vw(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){ft(e);let r=Fo(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);ye__default.existsSync(n)&&ye__default.rmSync(n,{force:true}),ye__default.existsSync(o)&&ye__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Fo(t),`${e}.js`)}}}var Ks=class{id="opencode";name="OpenCode";async isAvailable(){return Gr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:bw,skill:Qu(),bundle:Qu()}};var Mt=new As;Mt.register(new Ns);dr()&&(Mt.register(new js),Mt.register(new Ks));function ed({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Mt.getAvailableProviders(t??"bundle").then(u).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(b=>b.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=pu(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(Xe,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(Xe,{itemName:`${e} \u2014 Choose scope`,actions:uu,descriptions:du,onAction:f,onClose:h},"scope"):jsx(Xe,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}function rd({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,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:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.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(Xe,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function Hs({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 sd({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=Hs({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(Xe,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function ld({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=Hs({activeFocus:"actionMenu",onConfirm:()=>r(t)});return o?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(Xe,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}var An=x("bundle:installer"),cd=/already exists/i;async function Lw(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(ju(t)){let r=await Ku(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(cd.test(n))return;throw new Error(n)}}else {let r=await mo(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(cd.test(n))return;throw new Error(n)}}}async function Mw(e,t){try{await v(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){An.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function Rw(e,t,r){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){An.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function ud(e,t,r,n){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){An.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function _w(e,t,r,n,o){try{await v(I.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){An.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function zs(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 Mw(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){An.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await ud(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await Lw(f),u++,await Rw(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let b=w instanceof Error?w.message:String(w);An.error(`Failed to install artifact "${h}": ${b}`),l.push({name:h,type:g,reason:b}),await ud(i,h,g,b),r?.({index:p+1,total:c,artifact:f,success:false,error:b});}}let d=Date.now()-a,m=l.length;return await _w(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}function fd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,zs(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(md,{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(md,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var ue=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:re()})}));function gd({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",xt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}function hd({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${xt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((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:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function yd(e){return e.adapter.removable!==false?4:2}function wd({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function xd({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 Id({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(R=>Math.max(0,R-1));return}$.downArrow&&u(R=>Math.min(a.length-1,R+1));},{isActive:c===null}),c!==null)return jsx(wd,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Je/2)),p=Math.min(a.length,m+Je);p===a.length&&(m=Math.max(0,p-Je));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,b=p>s.length,_=f.filter(P=>r.has(`${P.name}@${o}`)),M=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children: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"]}),_.map(P=>jsx(xd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),b&&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"]}),M.map(P=>jsx(xd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.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"})})]})}va();var jw=/^https?:\/\/.+/;function Kw(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Vw(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Pd(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!jw.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let b=randomUUID(),_=new bn(b,w,g);try{await _.fetchItems(),await jt.add({id:b,name:w,source:g}),ce.register(new bn(b,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(M){let P=Kw(M)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Vw(M)?M.message:M instanceof Error?`Could not reach catalog URL: ${M.message}`:"Failed to validate catalog URL";t(P,"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),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function Td(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await jt.remove(o),ce.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 kd(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=ue(A=>A.installedItems),[o,s]=useState(()=>ce.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,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 A=ce.listAdapters(),U=await jt.read(),K=new Map(U.map(Ee=>[Ee.id,Ee]));s(A.map(Ee=>({adapter:Ee,stored:K.get(Ee.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let U=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(K=>{U||p({items:K,loading:false,error:null});}).catch(K=>{U||p({items:[],loading:false,error:K instanceof Error?K.message:"Failed to load catalog"});}),()=>{U=true;}},[i]);let b=Pd(w),_=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:M}=Td(_),P=useCallback(async A=>{h("removing"),await M(A);},[M]),$=useCallback(async A=>{try{let U=await A.adapter.fetchItems();if(p({items:U,loading:!1,error:null}),A.stored){let K=new Date().toISOString();await jt.updateField(A.stored.id,{lastUpdated:K}),w();}r("Marketplace updated","success");}catch(U){r(U instanceof Error?U.message:"Update failed","error");}},[w,r]),R=useCallback(async A=>{if(!A.stored)return;let U=A.stored.autoUpdate!==false;await jt.updateField(A.stored.id,{autoUpdate:!U}),w();},[w]),D=useCallback(()=>h("browse"),[]),X=useCallback(A=>{let U=o[i-1];if(!U)return;let K=U.adapter.removable!==false;[D,()=>{$(U);},...K?[()=>{R(U);},()=>{P(U.adapter.id);}]:[]][A]?.();},[o,i,D,$,R,P]),k=useCallback(()=>h("main"),[]),j=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),z=useCallback(()=>{let A=o[i-1];A&&R(A);},[o,i,R]),B=useCallback(()=>{let A=o[i-1];A&&P(A.adapter.id);},[o,i,P]);if(useInput((A,U)=>{if(U.upArrow){a(K=>Math.max(0,K-1));return}if(U.downArrow){a(K=>Math.min(o.length,K+1));return}(U.return||U.tab)&&(i===0?b.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&b.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,U)=>{if(U.escape||U.tab){u("list");return}if(U.upArrow){d(K=>Math.max(0,K-1));return}if(U.downArrow){let K=o[i-1],Ee=K?yd(K)-1:0;d(_o=>Math.min(_o+1,Ee));return}U.return&&X(c);},{isActive:f==="main"&&b.phase==="idle"&&l==="detail"&&e==="marketplaces"}),b.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:b.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.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(b.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:b.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:b.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:b.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(b.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 U=A.adapter.id??"default",K=new Set(n.filter(Ee=>Ee.marketplace===A.adapter.name).map(Ee=>`${Ee.name}@${U}`));return jsx(Id,{entry:A,items:m?.items??[],installedKeys:K,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let F=o[i-1]??null,J=F?n.filter(A=>A.marketplace===F.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(gd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&F?jsx(hd,{entry:F,detailData:m,installedCount:J,focusPanel:l,actionIndex:c,onBrowse:D,onUpdate:j,onToggleAutoUpdate:z,onRemove:B}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:F?"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 Ad(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 $d(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Ld(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 zw=new Set(Q.filter(e=>e.focus!=="list").map(e=>e.focus));function vo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Be.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function Md({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=Be(h=>h.query),a=Be(h=>h.setQuery),l=Be(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Be.getState();g(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:_}=S.getState();vo(ca(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:b,actionMenuOpen:_}=S.getState();vo(ca("",g,{activeTab:w}));},{isActive:zw.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:_}=S.getState();vo(Ad(h,g,{activeTab:w,selectedIndex:b},u.current));},{isActive:t==="list"}),useInput((h,g)=>{vo($d(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=Ld(h,g,Be.getState().query),b=w.queryUpdate;if(vo(w.actions),b==="reset")l(),d("");else if(b!==null){let{query:_,cursorPosition:M,setCursorPosition:P}=Be.getState();if("backspace"in b)M>0&&(a(_.slice(0,M-1)+_.slice(M)),P(M-1));else if("append"in b)a(_.slice(0,M)+b.append+_.slice(M)),P(M+b.append.length);else if("cursorMove"in b){let $=M+b.cursorMove;$>=0&&$<=_.length&&P($);}}},{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(!c)return u.current=h.length,h;let g=c.toLowerCase(),w=h.filter(b=>b.name.toLowerCase().includes(g)||b.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function _d(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=We(a=>a.justAuthenticated),o=We(a=>a.credentials),s=We(a=>a.setJustAuthenticated);return useEffect(()=>{n&&o&&(t(`Authenticated. Tenant: ${o.tenant}`,"success"),s(false));},[n,o]),useEffect(()=>{if(!e)return;let a=setTimeout(r,3e3);return ()=>clearTimeout(a)},[e]),{notify:(a,l)=>{t(a,l);}}}function Le(e,t,r=false){return r?true:!Wa.valid(e)||!Wa.valid(t)?false:Wa.gt(t,e)}var Jt=x("updater");async function Xw(e,t,r,n,o,s){try{await v(I.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:W().interfaceType});}catch(i){Jt.warn(`Failed to send update metrics: ${String(i)}`);}}function qw(e){let t=Ze(),r=`${e}@${q}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function Zs(e,t={}){let r=Date.now(),n=null;try{Jt.debug(`[${e}] Acquiring lock...`),n=await wr();let o=qw(e);if(!o)throw Jt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Jt.debug(`[${e}] Fetching manifest...`);let u=(await vn(e)).version;if(!i||!Le(i,u,t.force))throw Jt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new hr(e,i??"unknown");Jt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await ke(e,{force:!0,skipMetrics:!0}),d=Date.now()-r;return await Xw(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Jt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Jt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await wr();let d=Ze(),m=`${e}@${q}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,Ye(d),Jt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}var Qs=x("dispatcher");async function Yw(e,t,r,n,o){let s=xn(e);return Qs.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Bs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),Qs.debug(`[${e}] Retrying install after marketplace add`),be(t)}async function Dd(e,t,r,n){let o=In(e,n),s=xn(e);r?.onStatus?.(`Installing ${s}...`),Qs.debug(`[${e}] Attempting install: ${o}`);let i=await be(o);if(i.exitCode===0)return i;Qs.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return Yw(e,o,a,t,r)}async function Od(e,t,r){let n=e.type??"bundle",o=await Mt.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 Ud(){let e=ue(i=>i.installedItems),t=ue(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await Od(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=re().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Mt.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await po(i,u,a),t();},[e,t]),s=useCallback(async i=>{await Zs(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}var ti=x("mcp");function Eo(e,t){e.silent?Ge({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 Nd(e,t){e.silent?Oe({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(se(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function Zw(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 za(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 Fd(e,t,r){if(!await ie())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Eo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}ti.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=Zw(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=!0;}cs().set(`${t}:${r}`,n);}async deleteSecret(t,r){let n=cs(),o=`${t}:${r}`;return n.has(o)?(n.delete(o),!0):!1}getStoragePath(){return cs().path}static hasExistingData(){try{let t=new pa({projectName:ma});return Ie.existsSync(t.path)}catch{return !1}}static clearFallbackFile(){try{let t=new pa({projectName:ma});Ie.rmSync(t.path,{force:!0});}catch{}us=null;}};});async function fa(){if(Ke.hasExistingData())return new Ke;switch(process.platform){case "darwin":return await fn.isAvailable()?new fn:new Ke;case "linux":return await ur.isAvailable()?new ur:await ur.ensureInstalled()?new ur:new Ke;case "win32":return await hn.isAvailable()?new hn:new Ke;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var bc=H(()=>{"use strict";oa();aa();da();no();});var vc=H(()=>{"use strict";Ji();ra();bc();oa();aa();da();no();});async function dr(){return ms||(ms=fa()),ms}function fs(){ms=null;}async function re(){let t=await(await dr()).getSecret(Vt,ga);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function pr(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 Ec.error(`missing or empty fields: ${o.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await dr()).setSecret(Vt,ga,JSON.stringify(e));}async function Pc(){let e=await dr();await e.deleteSecret(Vt,ga),await e.deleteSecret(Vt,ha),await e.deleteSecret(Vt,ya);}async function Tc(){return (await dr()).getStoragePath()}async function Cc(e){await(await dr()).setSecret(Vt,ha,JSON.stringify(e));}async function gs(){let t=await(await dr()).getSecret(Vt,ha);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function hs(e){await(await dr()).setSecret(Vt,ya,JSON.stringify(e));}async function ys(){let t=await(await dr()).getSecret(Vt,ya);if(!t)return null;try{return JSON.parse(t)}catch{return null}}async function mr(){let e=await gs();return e?new Date(e.expiresAt)>new Date:false}function Tt(e){let t=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${t}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${t}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${t}/metrics-collector-api/`,Ec.debug(`[customUrl] Service URLs overridden to base: ${t}`);}var Ec,Vt,ga,ha,ya,ms,Ee=H(()=>{"use strict";vc();L();Ec=x("config:credentials"),Vt="flow-plugins-cli",ga="credentials",ha="token-cache",ya="user-info",ms=null;});function yn(e){let t=e.split(".");if(t.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${t.length}`);let r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=Buffer.from(r,"base64").toString("utf8");try{return JSON.parse(n)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var ws=H(()=>{"use strict";});function $g(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 wa(e){if(kc.some(r=>r.test(e)))return true;let t=$g(e);return !!(t&&kc.some(r=>r.test(t)))}function Lg(e,t){let r=process.env[e]??t;if(!r)throw new Error(`Missing required environment variable: ${e}`);return r}function fr(e,t){let r=Lg(e,t),n;try{n=new URL(r);}catch{throw new Error(`${e} must be a valid URL. Got: "${r}"`)}let o=process.env.NODE_ENV==="development";if(!o&&n.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${n.protocol}"`);if(n.username||n.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(n.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(n.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(n.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${n.hostname}"`);if(!o&&wa(n.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${n.hostname}"`);return r}var kc,wn=H(()=>{"use strict";kc=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^0\./,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i];});function _g(e){if(!Kt.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Dg(e){if(e instanceof HTTPError){let t=e.response.status;Sa.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&&Ac[r]?new Error(Ac[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?(Sa.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Sa.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Nr(e){let t=fr("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");_g(e.tenant);let r;try{r=await Xu.post(t,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(s){throw await Dg(s)}let n=r.expires_at??new Date(Date.now()+(r.expires_in??3600)*1e3).toISOString();await pr(e),await Cc({accessToken:r.access_token,expiresAt:n});let o=yn(r.access_token);await hs({sub:o.sub,name:o.name,email:o.email});}var Sa,Ac,Ss=H(()=>{"use strict";Ee();ws();wn();L();K();Sa=x("api:auth");Ac={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 Ct(){if(await mr()){let n=await gs();if(n)return n.accessToken}$c.debug("Token expired or missing, re-authenticating...");let t=await re();if(!t)throw new Error("Not authenticated. Run: flow auth login");Ke.clearFallbackFile(),fs(),await Nr(t);let r=await gs();if(!r)throw new Error("Authentication succeeded but token was not persisted");return $c.debug("Token refreshed successfully"),r.accessToken}var $c,Sn=H(()=>{"use strict";Ee();Ss();no();L();$c=x("lib:tokenProvider");});function Gt(){return Xu.create({prefix:fr("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let t=await Ct();e.headers.set("Authorization",`Bearer ${t}`);let r=await re();r?.tenant&&Kt.test(r.tenant)&&e.headers.set("FlowTenant",r.tenant);}]}})}var So=H(()=>{"use strict";wn();Ee();Sn();K();});function Cn(e,t){let r=Gt();return t?r.get(e,{searchParams:{source:t}}):r.get(e)}async function kn(e){if(!(e instanceof HTTPError))return null;try{let t=await e.response.clone().json(),{message:r}=t;return Array.isArray(r)?r.filter(Boolean).join("; ")||null:typeof r=="string"&&r?r:null}catch{return null}}var Ka=H(()=>{"use strict";So();});function xo(e){if(!e||!Ry.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function An(e){return _y.test(e)}function $n(e){let t=e.indexOf("@");return t>0?e.slice(0,t):e}function Ja(e){if(!Dy.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=$n(e);Ja(r);let n=["claude","plugin","install",r];return t&&n.push("--scope",t),n.join(" ")}function zs(e){let t=e.trim();if(!t)throw new Error("No marketplace source provided.");if(!Oy.test(t)&&!Uy.test(t))throw new Error(`Invalid marketplace source: "${t}". Must be owner/repo or an https:// URL.`);return t}var Ry,_y,Dy,Oy,Uy,Er=H(()=>{"use strict";Ry=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;_y=/^[^@]+@[^@]+$/;Dy=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;Oy=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,Uy=/^https:\/\/[\w./:@?&=+#%-]+$/;});var Hu={};ec(Hu,{FlowApiAdapter:()=>Mn});var By,Mn,Ha=H(()=>{"use strict";So();Ka();L();Er();By=x("catalog.flow-api"),Mn=class{id;name;source;removable=!1;contentSource;constructor(t){this.contentSource=t,this.id=t?`flow-api:${t}`:"flow-api",this.name=t?`Flow Marketplace (${t})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:t}=await Cn("v1/plugins/catalog",this.contentSource).json();return t.map(r=>({...r,catalogId:this.id,origin:r.origin??"internal",type:r.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(t){let r=await kn(t);if(r)throw new Error(r);if(t instanceof HTTPError){let{status:n}=t.response;throw n===401||n===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${n}`)}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){xo(t);try{return await Cn(`v1/plugins/${t}/manifest`,this.contentSource).json()}catch(r){let n=await kn(r);if(n)throw new Error(n);if(r instanceof HTTPError){let{status:o}=r.response;throw o===404?new Error(`Plugin '${t}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${o}`)}throw r instanceof Error?new Error(`Failed to fetch manifest: ${r.message}`):r}}async ping(){try{return await Gt().head("v1/plugins/catalog"),By.debug("ping ok"),!0}catch{return !1}}};});function Fy(){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 Wu(){return Gu??=Fy(),Gu}var Gu,zu=H(()=>{"use strict";});var Yu={};ec(Yu,{GitRepoAdapter:()=>Rn});function qu(e,t){if(!jy.test(e))throw new Error(`Invalid ${t} in catalog source URL: "${e}"`)}var jy,Rn,Ga=H(()=>{"use strict";zu();wn();jy=/^[a-zA-Z0-9_.-]+$/;Rn=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(wa(o))throw new Error(`Catalog source URL points to a private/loopback address: "${o}"`);let i=s.replace(/^\//,"").split("/"),[a,l]=i;return qu(a,"owner"),qu(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 Xu.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 Xu.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 Wu();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}}};});K();var rc=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(rc),origins:new Set(Vi)},setScreen:t=>e({screen:t}),setActiveTab:t=>e({activeTab:t}),setFocus:t=>e({focus:t}),setSelectedIndex:t=>e({selectedIndex:t}),setActionMenuOpen:t=>e({actionMenuOpen:t}),showNotification:(t,r)=>e({notification:{message:t,type:r}}),clearNotification:()=>e({notification:null}),setLoading:(t,r="")=>e({loading:t,loadingMessage:t?r:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(t,r)=>e({downloadProgress:t,downloadTotal:r}),setCatalogError:t=>e({catalogError:t}),setPendingExit:t=>e({pendingExit:t}),toggleTypeFilter:t=>e(r=>{let{types:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,types:new Set([t])},selectedIndex:0}}),selectAllTypes:()=>e(t=>({catalogFilters:{...t.catalogFilters,types:new Set(rc)},selectedIndex:0})),toggleOriginFilter:t=>e(r=>{let{origins:n}=r.catalogFilters;return n.size===1&&n.has(t)?{}:{catalogFilters:{...r.catalogFilters,origins:new Set([t])},selectedIndex:0}}),selectAllOrigins:()=>e(t=>({catalogFilters:{...t.catalogFilters,origins:new Set(Vi)},selectedIndex:0})),setDebugPanelOpen:t=>e({debugPanelOpen:t}),incrementCatalogVersion:()=>e(t=>({catalogVersion:t.catalogVersion+1})),setBundleInstallFlow:t=>e({bundleInstallFlow:t})}));Ee();Sn();ws();K();wn();L();var xs=x("api:metrics");function Lc(){return fr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function Mc(e,t,r){return Xu.post(e,{json:t,headers:r})}async function Ug(e){let t=await ys();if(t)return t;let r=yn(e),n={sub:r.sub,name:r.name,email:r.email};return await hs(n),n}async function v(e,t){let r=await Ct(),n=await Ug(r),o=await re();if(!Kt.test(o.tenant))throw new Error(`Invalid tenant value: "${o.tenant}"`);let s={action:e,booster:Ki,metadata:{...t},success:true,tenant:o.tenant,timestamp:new Date().toISOString(),user:{id:n.sub,name:n.name,email:n.email}};try{await Mc(Lc(),s,{Authorization:`Bearer ${r}`,FlowTenant:o.tenant}),xs.debug(`Metrics event sent: ${e}`);}catch(i){throw xs.warn(`Failed to send metrics event "${e}": ${String(i)}`),i}}async function Rc(e,t,r){try{let n=r&&Kt.test(r)?r:"unknown",o={action:e,booster:Ki,metadata:t,success:!0,tenant:n,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await Mc(Lc(),o,{FlowTenant:n}),xs.debug(`Anonymous metrics event sent: ${e}`);}catch(n){xs.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 Bg={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},ft={...Bg};function _c(e){let t=Date.now();ft={sessionStart:t,stepStart:t,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Fr(e){ft.currentStep=e,ft.stepStart=Date.now();}function Y(){return {...ft}}function gr(){return ft.sessionStart===0?0:Date.now()-ft.sessionStart}function jr(){return ft.stepStart===0?0:Date.now()-ft.stepStart}function Dc(){ft.tuiSessionStart=Date.now();}function Oc(){return ft.tuiSessionStart===0?0:Date.now()-ft.tuiSessionStart}L();var Ng=3e3,Fg=x("abandonment");async function Is(e){let{currentStep:t,sessionStart:r}=Y();if(r===0)return;let n={last_step:t,trigger:e,duration_ms:gr()};try{await Promise.race([v(I.CLI_ONBOARDING_ABANDONED,n),new Promise((o,s)=>setTimeout(()=>s(new Error("abandonment timeout")),Ng))]);}catch(o){Fg.warn(`Abandonment event failed: ${String(o)}`);}}function Uc(e,t){return Promise.race([e,new Promise(r=>setTimeout(r,t))])}L();var jg=3e3,Kg=x("session-end");async function so(e,t,r){let n=Oc(),s=[v(I.CLI_TUI_SESSION_ENDED,{duration_ms:n,active_tab:t,interface:"tui"})];r!=="main"&&s.push(Is(e));try{await Uc(Promise.all(s).then(()=>{}),jg);}catch(i){Kg.warn(`Session end event failed: ${String(i)}`);}}var Gg=2e3;function Nc(){let{exit:e}=useApp(),t=useRef(false),r=useRef(null),n=S(l=>l.pendingExit),o=S(l=>l.setPendingExit),s=S(l=>l.activeTab),i=S(l=>l.screen),a=useCallback(()=>{if(t.current){r.current&&clearTimeout(r.current),so("double-ctrl-c",s,i).finally(()=>e());return}t.current=true,o(true),r.current=setTimeout(()=>{t.current=false,o(false);},Gg);},[e,o,s,i]);return useInput((l,u)=>{u.ctrl&&l==="c"&&a();}),{pendingExit:n}}var qg=16;function Fc({label:e,value:t,onChange:r,masked:n=false,isActive:o,error:s}){let i=useRef(t);useEffect(()=>{i.current=t;},[t]),useInput((l,u)=>{if(u.backspace){let c=i.current.slice(0,-1);i.current=c,r(c);}else if(l&&!u.ctrl&&!u.meta&&!u.escape&&!u.return&&!u.tab&&!u.upArrow&&!u.downArrow&&!u.leftArrow&&!u.rightArrow){let c=i.current+l;i.current=c,r(c);}},{isActive:o});let a=n?"\u2022".repeat(t.length):t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u25B8 ":" "}),jsx(Text,{color:o?"white":"gray",bold:o,children:e.padEnd(qg)}),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]})})]})}K();function jc({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="n"||l==="N"){r("input");return}(l==="y"||l==="Y"||u.return)&&e(null);return}if(u.escape){a.current="",o(""),i(false),r("confirm");return}if(u.return){let c=a.current.trim();un.test(c)?(i(false),e(c)):i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[t==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:dn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}K();function Kc({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}K();function Vc(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[lr," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var Qe=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})}));Ss();K();function Jr(){return xe__default.join($e__default.homedir(),".claude","settings.json")}function Hc(e){return `${(e&&e.trim().length>0?e.trim():zo).replace(/\/+$/,"")}/flow-litellm/`}function mo(){let e=Jr();if(!Ie__default.existsSync(e))return {status:"missing"};let t=Ie__default.readFileSync(e,"utf-8"),r=t.charCodeAt(0)===65279?t.slice(1):t;try{let n=JSON.parse(r);return n===null||typeof n!="object"||Array.isArray(n)?{status:"malformed",raw:t}:{status:"ok",settings:n}}catch{return {status:"malformed",raw:t}}}function vs(e){let t=Jr();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function Gc(e,t,r){let n=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...n,ANTHROPIC_AUTH_TOKEN:t,ANTHROPIC_BASE_URL:r}}}function Ta(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_AUTH_TOKEN;return typeof r=="string"&&r.length>0?r:null}function Wc(e){let t=e.env;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.ANTHROPIC_BASE_URL;return typeof r=="string"&&r.length>0?r:null}var nh=3600,Hr=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function fo(e){let t=e.split(".");if(t.length!==3)throw new Error("Malformed JWT: invalid format");let r;try{r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Malformed JWT: payload must be a JSON object");let n=r;if(typeof n.clientId!="string"||!n.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(n.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof n.clientSecret!="string"||!n.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(n.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof n.tenant!="string"||!n.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(n.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}}function oh(e){return rh.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:nh})}function Es(e,t={}){let r=mo();if(r.status==="malformed"&&!t.allowOverwriteMalformed)throw new Hr;let n=r.status==="ok"?r.settings:{},o=r.status==="ok"?Ta(r.settings):null,s=r.status==="ok"?Wc(r.settings):null,i=t.jwtOverride??oh(e),a=Hc(e.customUrl),l=Gc(n,i,a);return {jwt:i,anthropicBaseUrl:a,merged:l,previousToken:o,previousBaseUrl:s,hadExistingFile:r.status!=="missing"}}function Ps(e){vs(e.merged);}function zc(){let e=mo();return e.status!=="ok"?false:Ta(e.settings)!==null}Ee();qe();function sh(){let e=cc();if(!Ie__default.existsSync(e))return {};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {}}}var Ca=null;function ih(){return Ca===null&&(Ca=sh()),Ca}function wr(){return !!ih().ENABLE_EXPERIMENTAL_BETAS}K();function uh(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function qc(e){let t=uh();return t.length>0&&t.every(r=>e.find(n=>n.module.alias===r.alias)?.alreadyInstalled===true)}var Ts={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=xe__default.join($e__default.homedir(),".claude","settings.json"),r=Ie__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),o=JSON.parse(r).env;return typeof o=="object"&&o!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in o}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let t=["flow-ai-obs","init","--no-interactive"];if(t.push("--custom-url",e.customUrl??zo),e.credentials){let{clientId:r,clientSecret:n,tenant:o}=e.credentials;t.push("--client-id",r,"--client-secret",n,"--tenant",o);}return e.customEmail&&t.push("--custom-email",e.customEmail),[t]},onDemand:null,mode:"non-interactive"}},dh={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},se=wr()?[Ts,dh]:[Ts];Ee();L();var gh=x("moduleState");function ks(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"modules.json")}var hh={retries:5,minTimeout:50};async function Yc(e,t){Ie__default.mkdirSync(xe__default.dirname(e),{recursive:true});let r=await fh.lock(e+".lock",{realpath:false,retries:hh});try{return await t()}finally{await r();}}function Zc(){let e=ks();if(!Ie__default.existsSync(e))return [];try{let t=JSON.parse(Ie__default.readFileSync(e,"utf-8"));return t.schemaVersion!==1?(gh.warn(`modules.json has unknown schemaVersion ${t.schemaVersion}, resetting`),Ie__default.rmSync(e,{force:!0}),[]):Array.isArray(t.modules)?t.modules.map(r=>({...r,name:r.name??null})):[]}catch{return Ie__default.rmSync(e,{force:true}),[]}}function Gr(){return Zc()}function Qc(e){let t=ks();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=`${t}.${randomUUID()}.tmp`,n={schemaVersion:1,modules:e};Ie__default.writeFileSync(r,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function et(e){return Gr().find(t=>t.alias===e)??null}async function gt(e){let t=ks();await Yc(t,async()=>{let r=Zc(),n=r.findIndex(o=>o.alias===e.alias);n===-1?r.push(e):r[n]=e,Qc(r);});}async function Wr(){let e=ks();Ie__default.existsSync(e)||await Yc(e,async()=>{Ie__default.existsSync(e)||Qc([]);});}var Sh=promisify(execFile);function Sr(e,t){let r=e.platforms[process.platform];return !r||r.status!=="supported"?null:r.strategies.find(n=>n.type===t)??null}async function At(e){let t=process.platform==="win32"?"where":"which";try{return await Sh(t,[e]),!0}catch{return false}}function Jt(){return process.platform==="win32"?"npm.cmd":"npm"}var eu=promisify(execFile),In=class{type="npm";async isAvailable(){return At("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=Sr(t,"npm");if(!r)return null;try{let{stdout:n}=await eu(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=Sr(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 eu(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 As=promisify(execFile),Eh=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,$s=class{type="homebrew";async isAvailable(){return At("brew")}async install(t){return this.runBrewCommand(t,"install")}async update(t,r){return this.runBrewCommand(t,"upgrade")}async getInstalledVersion(t){let r=Sr(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=Sr(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 As("brew",["tap",o.tap]),await As("brew",["trust",o.tap])),await As("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 As("brew",["list","--versions",t]),n=r.trim().match(Eh);return n?n[2]:null}catch{return null}}};var bn=promisify(execFile),ru=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function nu(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"bin")}var Ls=class{type="curl";async isAvailable(){return At("curl")}async install(t){let r=Date.now(),n=Sr(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=xe__default.join(nu(),xe__default.basename(t.binaryName));for(let n of [r,t.binaryName])try{let{stdout:o}=await bn(n,["--version"]),s=o.match(ru);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=xe__default.join($e__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{Ie__default.unlinkSync(s);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:a.message},durationMs:Date.now()-o}}}return Ie__default.chmodSync(s,448),await 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{Ie__default.unlinkSync(s);}catch{}}}async installBinary(t,r,n,o){let s=nu(),i=xe__default.join(s,xe__default.basename(n.binaryName)),a=false;try{if(Ie__default.mkdirSync(s,{recursive:!0}),a=!0,await bn("curl",["-L","--fail","-o",i,t]),r){let u=await this.validateChecksum(i,r);if(!u.valid)return Ie__default.unlinkSync(i),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:u.message},durationMs:Date.now()-o}}Ie__default.chmodSync(i,493);let l=null;try{let{stdout:u}=await bn(i,["--version"]),c=u.match(ru);l=c?c[1]:null;}catch{}return {success:!0,version:l??void 0,method:"curl",durationMs:Date.now()-o}}catch(l){if(a)try{Ie__default.unlinkSync(i);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:l instanceof Error?l.message:String(l)},durationMs:Date.now()-o}}}async validateChecksum(t,r){let n=xe__default.join($e__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await bn("curl",["-L","--fail","-o",n,r]);let o=Ie__default.readFileSync(n,"utf-8").trim().split(/\s+/)[0],s=Ie__default.readFileSync(t),i=createHash("sha256").update(s).digest("hex");return i!==o?{valid:!1,message:`SHA256 mismatch: expected ${o}, got ${i}`}:{valid:!0,message:""}}catch(o){return {valid:false,message:`Checksum validation failed: ${String(o)}`}}finally{try{Ie__default.unlinkSync(n);}catch{}}}};L();var ou="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(ou=e.version);}catch{}var me=ou;var Pe=x("moduleInstaller");function Lt(e){switch(e){case "npm":return new In;case "homebrew":return new $s;case "curl":return new Ls}}async function go(e,t,r){try{await v(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){Pe.warn(`Failed to emit install failed event: ${String(n)}`);}}async function Ir(e,t,r,n,o,s){let i=Date.now(),a=e.platforms[process.platform];if(!a)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-i};if(a.status==="experimental"){Pe.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let d={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(a.status!=="supported"){let d={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}if(!a.strategies.some(d=>d.type===r)){let d={code:"STRATEGY_NOT_FOUND",message:`Strategy "${r}" is not configured for module "${e.alias}" on ${process.platform}`};return await go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}let l=Lt(r),u=false;try{u=await l.isAvailable();}catch(d){Pe.warn(`${r} availability check failed: ${String(d)}`);}if(!u){let d={code:"STRATEGY_NOT_AVAILABLE",message:`"${r}" is not installed on this system`};return await go(e,t,d),{success:false,error:d,durationMs:Date.now()-i}}try{await v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:me,trigger:t});}catch(d){Pe.warn(`Failed to emit install started event: ${String(d)}`);}let c;try{c=s?.forceLatest?await l.update(e,"unknown"):await l.install(e);}catch(d){let m=d instanceof Error?d.message:String(d);Pe.warn(`${r} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-i};}if(c.success){await gt({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await v(I.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:t});}catch(p){Pe.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:d,failed:m}=await Lh(e,t,n,o);return d?{...c,pendingInteractiveSetup:d}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await go(e,t,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Lh(e,t,r,n){if(!e.postInstall)return {pendingCmd:null,failed:false};let o=t==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(o==null)return {pendingCmd:null,failed:false};let s;if(typeof o=="function"){let a=await re(),l={credentials:a?{clientId:a.clientId,clientSecret:a.clientSecret,tenant:a.tenant}:null,customUrl:r??null,customEmail:n??null};try{s=o(l);}catch(u){return Pe.warn(`postInstall function threw: ${String(u)}`),{pendingCmd:null,failed:false}}}else s=o;if(s.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:s[0]??null,failed:false};let i=false;for(let a=0;a<s.length;a++){let l=s[a];if(l.length===0)continue;let u=spawnSync(l[0],l.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(u.status!==0){i=true,Pe.warn(`postInstall "${l.join(" ")}" exited with status ${u.status??"null"}`),u.stderr&&Pe.warn(u.stderr);let c=s.slice(a+1).filter(d=>d.length>0);c.length>0&&Pe.debug(`continuing with remaining postInstall steps: ${c.map(d=>d.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:i}}async function Ms(e,t){let r=Date.now(),n=et(e.alias);if(!n?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-r};let o=Lt(n.installMethod),s=n.installedVersion??"unknown";if(t==="command")try{await v(I.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:me,trigger:"command"});}catch(a){Pe.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);Pe.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 v(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){Pe.warn(`Failed to emit update completed event: ${String(a)}`);}else try{await v(I.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:s,to_version:i.version??"unknown",duration_ms:i.durationMs});}catch(a){Pe.warn(`Failed to emit module updated event: ${String(a)}`);}else if(t==="command")try{await v(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){Pe.warn(`Failed to emit update failed event: ${String(a)}`);}return i}L();var Rs=x("flowAiObsSetup");async function _s(e,t){try{if(!await new In().isAvailable().catch(()=>!1))return Rs.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let o=await Ir(Ts,"onboarding","npm",e,t,{forceLatest:!0});return o.success?o.postInstallFailed||o.configCheckFailed?(Rs.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Rs.warn(`flow-ai-obs install failed: ${o.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(r){return Rs.warn(`installFlowAiObs threw: ${String(r)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}L();function su(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 Mh=x("useAuthSetup");function iu(){let[e,t]=useState(""),r=useRef(null),n=useRef(null),o=useRef(null),[s,i]=useState(),[a,l]=useState(null),[u,c]=useState(false),[d,m]=useState("fields"),[p,f]=useState(null),h=useRef(0),g=useRef(false),{setCredentials:w,setJustAuthenticated:b}=Qe(),D=()=>{m("fields"),f(null),t(""),r.current=null,n.current=null,o.current=null;},R=()=>{v(I.CLI_SESSION_STARTED,{cli_version:me,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});},P=async j=>{g.current=true;let z={...r.current,customUrl:n.current??void 0};try{j&&Ps(j),await pr(z);}catch(G){l(G instanceof Error?G.message:"Failed to persist credentials"),D(),g.current=false;return}let{clientSecret:A,...B}=z;w(B),b(true),R(),await _s(n.current,o.current).catch(G=>Mh.warn(`installFlowAiObs threw unexpectedly: ${String(G)}`)),Ds({starterKit:B.starterKit});},$=async()=>P(),_=async j=>P(j),O=j=>{try{let z={...r.current,customUrl:n.current??void 0};return Es(z,{allowOverwriteMalformed:j,jwtOverride:e.trim()})}catch(z){return z instanceof Hr?(m("malformedConfirm"),null):(l(z instanceof Error?z.message:"Failed to read settings.json"),m("fields"),null)}},Q=()=>{let j=O(true);j&&(f(j),_(j));},k=async()=>{let j=e.trim();if(!j){i("This field is required");return}let z;try{z=fo(j);}catch(A){i(A instanceof Error?A.message:"Invalid JWT");return}i(void 0),r.current=z,m("customUrl");},J=j=>{n.current=j,m("email");},Z=j=>{o.current=j,N();},N=async()=>{let j=n.current;j&&Tt(j),c(true),l(null),h.current+=1;try{await Nr(r.current);let z=O(!1);z&&(f(z),m("preview"));}catch(z){let A=z instanceof Error?z.message:"Authentication failed";l(A),Rc(I.CLI_AUTH_FAILED,{error_code:su(z),attempt:h.current},r.current.tenant).catch(()=>{}),t(""),r.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:s,authError:a,isSubmitting:u,step:d,plan:p,isCommittingRef:g,setJwtValue:t,setJwtError:i,cancelToFields:D,handleSubmit:k,goToEmailStep:J,handleEmailConfirm:Z,commitAndProceed:_,skipJwtAndProceed:$,planPersistOverwrite:Q}}K();V();function au(){let{jwtValue:e,jwtError:t,authError:r,isSubmitting:n,step:o,plan:s,isCommittingRef:i,setJwtValue:a,setJwtError:l,cancelToFields:u,handleSubmit:c,goToEmailStep:d,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:f,planPersistOverwrite:h}=iu(),[g,w]=useState("confirm"),[b,D]=useState(""),R=useRef(""),[P,$]=useState(false);return useEffect(()=>{o==="customUrl"&&(w("confirm"),R.current="",D(""),$(false));},[o]),useInput((_,O)=>{if(!(n||i.current)){if(o==="preview"){O.return&&s?p(s):O.escape?f():_==="q"&&u();return}if(o==="malformedConfirm"){O.return?h():O.escape&&u();return}if(o==="customUrl"){if(g==="confirm")_==="y"||_==="Y"?w("input"):(_==="n"||_==="N"||O.return)&&d(null);else if(O.escape)R.current="",D(""),w("confirm");else if(O.return){let Q=R.current.trim();Q.length>0&&ln.test(Q)?($(false),d(Q)):Q.length>0&&$(true);}else O.backspace||O.delete?(R.current=R.current.slice(0,-1),D(R.current)):_&&!O.ctrl&&!O.meta&&(R.current=R.current+_,D(R.current),$(false));return}o!=="email"&&O.return&&c();}},{isActive:true}),o==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!n&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!n&&g==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:b}),jsx(Text,{color:"cyan",children:"\u2588"})]}),P&&jsx(Text,{color:"red",children:cn}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):o==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Initial Setup"]})}),n?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(jc,{onConfirm:m})]}):o==="preview"&&s?jsx(Kc,{plan:s}):o==="malformedConfirm"?jsx(Vc,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[lr," \u2014 Initial Setup"]})}),jsxs(Box,{marginBottom:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."})]}),jsx(Box,{flexDirection:"column",children:jsx(Box,{marginBottom:1,children:jsx(Fc,{label:"JWT",value:e,onChange:_=>{a(_),t&&l(void 0);},masked:true,isActive:!n,error:t})})}),n&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),r&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",y(r)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function En(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Uh,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",me]})})]})}var du=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],ne=wr()?du:du.slice(0,3);function Bh(e){return ne.findIndex(t=>t.id===e)}function $a(e,t,r){let n=Bh(r.activeTab);if(t.rightArrow||t.tab){let o=ne[(n+1)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}if(t.leftArrow){let o=ne[(n-1+ne.length)%ne.length];return [{type:"setTab",tab:o.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:o.focus}]}return t.downArrow?[{type:"setFocus",focus:ne[n]?.focus??"list"}]:[]}var fu={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function gu({outdatedCount:e=0}){let t=S(r=>r.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:ne.map(({id:r})=>{let n=r===t,o=r==="updates"&&e>0?`${fu[r]} (${e})`:fu[r];return jsx(Box,{marginRight:1,children:n?jsx(Text,{bold:true,inverse:true,children:` ${o} `}):jsx(Text,{dimColor:true,children:` ${o} `})},r)})})}var Ve=create(e=>({query:"",cursorPosition:0,setQuery:t=>e({query:t}),setCursorPosition:t=>e({cursorPosition:t}),resetQuery:()=>e({query:"",cursorPosition:0})}));function yu(){let e=S(i=>i.focus),t=Ve(i=>i.query),r=Ve(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..."})]})}K();var Kh=["skill","mcp","bundle"].map((e,t)=>({key:String(t+2),type:e,...an[e]})),Vh=["internal","external"].map((e,t)=>({key:String(t+6),origin:e,...tc[e]}));function wu(){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"]})]}),Kh.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"]})]}),Vh.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)})]})}K();function Su({type:e}){let{label:t,color:r}=an[e];return jsx(Text,{color:r,children:t})}K();function bu({origin:e}){return e===Yn?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}V();var Us=Gh.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(Su,{type:t.type})]}),t.origin&&jsxs(Text,{children:[" ",jsx(bu,{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 ",Pt(t.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:t.description})})]})});function Pn({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}K();function Pu({items:e,emptyMessage:t}){let r=S(l=>l.selectedIndex);if(e.length===0)return jsx(Pn,{message:t});let n=Math.max(0,r-Math.floor(Xe/2)),o=Math.min(e.length,n+Xe);o===e.length&&(n=Math.max(0,o-Xe));let s=e.slice(n,o),i=n,a=e.length-o;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:i>0?`\u2191 ${i} more above`:" "})}),s.map((l,u)=>jsx(Us,{item:l,isSelected:n+u===r},l.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:a>0?`\u2193 ${a} more below`:" "})})]})}function ku({label:e,pathHint:t}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",t]})]})}K();function $u({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(Pn,{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(Xe/2)),u=Math.min(n.length,l+Xe);u===n.length&&(l=Math.max(0,u-Xe));let c=n.slice(l,u),d=l,m=n.length-u;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:d>0?`\u2191 ${d} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(ku,{label:p.label,pathHint:p.pathHint},p.key):jsx(Us,{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 ey={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function ty({items:e,tabId:t,emptyMessage:r,groups:n,actionHint:o}){return jsxs(Box,{flexDirection:"column",children:[jsx(yu,{}),jsx(wu,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:ey[t]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),o&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${o}`})]}),n&&n.length>0?jsx($u,{groups:n,emptyMessage:r}):jsx(Pu,{items:e,emptyMessage:r})]})}function Lu({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(ty,{items:e,tabId:o,emptyMessage:t,groups:o!=="discover"?r:void 0,actionHint:o==="updates"?"press 'a' to update all":void 0},o)})}var oy={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 Bs(){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:[oy[e],t?" | Ctrl+D: debug log":""]})})}V();function Mu({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 Ns({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jd,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Ua(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var Ou=20;function Fs(e,t){let r=t>0?Math.min(e/t,1):0,n=Math.round(r*100),o=Math.round(r*Ou),s="\u2588".repeat(o)+"\u2591".repeat(Ou-o),i=`${Ua(e)} / ${Ua(t)}`;return {bar:s,percent:n,label:i}}function js({received:e,total:t}){let{bar:r,percent:n,label:o}=Fs(e,t);return jsxs(Text,{dimColor:true,children:[r," ",n,"%"," ","(",o,")"]})}function Ks({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 tt({itemName:e,actions:t,descriptions:r,onAction:n,onClose:o}){let s=S(l=>l.focus),[i,a]=useState(0);return useInput((l,u)=>{u.upArrow?a(c=>c>0?c-1:c):u.downArrow?a(c=>c<t.length-1?c+1:c):u.return?n(t[i]):u.escape&&o();},{isActive:s==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:t.map((l,u)=>jsxs(Box,{children:[jsxs(Text,{bold:u===i,color:u===i?"cyan":void 0,children:[u===i?"\u203A ":" ",l]}),r?.[l]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",r[l]]})]},u))})]})}K();var ja=Object.entries(Zn),Fu=[...ja.map(([,e])=>e.actionLabel),"Cancel"],ju=Object.fromEntries(ja.map(([,e])=>[e.actionLabel,e.description]));function Ku(e){let t=ja.find(([,r])=>r.actionLabel===e);return t?t[0]:null}L();var Sy=x("provider.registry"),xy=3e4,Js=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()+xy}),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"&&Sy.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 Iy={user:"global",project:"project",local:"local"};function Hs(e){return e?Iy[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},vr=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};So();Ka();L();var Ey=x("catalog.registry"),Gs=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);Ey.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()]}};qe();var My={retries:5,minTimeout:50};async function Va(e,t){mkdirSync(dirname(e),{recursive:true});let r=await fh.lock(e+".lock",{realpath:false,retries:My});try{return await t()}finally{await r();}}var Ws=class{filePath;constructor(t){this.filePath=t??lc();}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 Va(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 Va(this.filePath,async()=>{let r=await this.read();await this.write(r.filter(n=>n.id!==t));});}async updateField(t,r){await Va(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));});}};Ha();var ue=new Gs,Wt=new Ws,Ky=["flow-harness"];function Vy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?Ky:e.split(",").map(t=>t.trim()).filter(Boolean)}ue.register(new Mn);for(let e of Vy())ue.register(new Mn(e));var Zu=false;async function Qu(){if(Zu)return;Zu=true;let e=await Wt.read(),{GitRepoAdapter:t}=await Promise.resolve().then(()=>(Ga(),Yu));for(let r of e)ue.register(new t(r.id,r.name,r.source));}Er();var ed=2;async function zt(e){if(e){let{FlowApiAdapter:t}=await Promise.resolve().then(()=>(Ha(),Hu));return new t(e).fetchItems()}return ue.fetchAll()}async function td(){return ue.fetchAllWithErrors()}async function _n(e,t){xo(e);try{return await Cn(`v1/plugins/${e}/manifest`,t).json()}catch(r){let n=await kn(r);throw n?new Error(n):r instanceof Error?r.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):r.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${r.message}`):r}}async function rd(e,t,r){xo(e);try{let n=await Cn(`v1/plugins/${e}/archive`,r),o=n.headers.get("x-archive-size"),s=o?Number(o):NaN,i=Number.isFinite(s)&&s>0?s:0,a=i>0,l=n.body;if(!l)throw new Error("Failed to download plugin: response has no body");let u=l.getReader(),c=[],d=0;for(;;){let{done:m,value:p}=await u.read();if(m)break;if(d+=p.byteLength,a&&d>i*ed)throw await u.cancel(),new Error(`Download exceeded expected size: received ${d} bytes, expected at most ${i*ed}`);c.push(p),a&&t?.(d,i);}return Buffer.concat(c)}catch(n){if(n instanceof Error&&n.message.includes("Download exceeded expected size"))throw n;let o=await kn(n);throw o?new Error(o):n instanceof Error?new Error(`Failed to download plugin: ${n.message}`):n}}async function Xs(){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}}qe();qe();async function nd(e,t){let r=xe.resolve(t);await Mt.mkdir(r,{recursive:true});let n=xe.join(xe.dirname(r),`${randomUUID()}.zip`);try{await Mt.writeFile(n,e);let o=await Hy.Open.file(n),s=xe.normalize(r+xe.sep);for(let i of o.files){if((i.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${i.path}" is a symbolic link and was rejected`);let l=xe.resolve(r,i.path);if(process.platform==="win32"&&l.length>=260)throw new Error(`Path too long: "${l}" (${l.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!l.startsWith(s)&&l!==r)throw new Error(`Zip Slip detected: entry "${i.path}" would escape target directory`)}await o.extract({path:r});try{let i=realpathSync(r);if(!i.startsWith(xe.resolve(xe.dirname(r))))throw new Error(`Zip Slip (post-extract): resolved path "${i}" is outside expected parent`)}catch(i){if(i.code!=="ENOENT")throw i}}finally{try{await Mt.unlink(n);}catch{}}}async function Wa(e){await Mt.rm(e,{recursive:true,force:true});}async function Pr(){let e=ic();await Mt.mkdir(xe.dirname(e),{recursive:true});try{await Mt.writeFile(e,"",{flag:"wx"});}catch(r){if(r.code!=="EEXIST")throw r}return await fh.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}qe();K();function zy(){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:ee,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function id(){let e=Yo();if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return null}}function Xy(){let e=id();if(e)return e;let t=zy(),r=Yo();return Ie__default.mkdirSync(xe__default.dirname(r),{recursive:true}),za(t),t}function za(e){let t=Yo(),r=`${t}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,t);}function qy(){let e=Zo(),t={};try{Ie__default.existsSync(e)&&(t=JSON.parse(Ie__default.readFileSync(e,"utf-8")));}catch{t={};}if(t[ee])return;t[ee]={source:{source:"github",repo:"cit-flow/flow-skills"},installLocation:sc(),lastUpdated:new Date().toISOString()};let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}function ad(e,t){St(e.name),qy();let r=Wi(e.name);Ie__default.mkdirSync(xe__default.dirname(r),{recursive:true});try{Ie__default.lstatSync(r),Ie__default.rmSync(r,{recursive:!0,force:!0});}catch{}Ie__default.symlinkSync(t,r,process.platform==="win32"?"junction":"dir");let n=Xy();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}),za(n));}function Xa(e){St(e);let t=Wi(e);try{Ie__default.rmSync(t,{recursive:!0,force:!0});}catch{}let r=id();if(!r)return;let n=r.plugins.length;r.plugins=r.plugins.filter(o=>o.name!==e),r.plugins.length!==n&&za(r);}V();L();var Zy=x("mcpConfigReader"),Qy=500,ew=512;function tw(){return xe__default.join($e__default.homedir(),".claude.json")}function rw(){return xe__default.join(process.cwd(),".mcp.json")}function cd(e){if(!Ie__default.existsSync(e))return null;try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return Zy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qa(e){if(!Io(e))return {};let t=e.mcpServers;return Io(t)?t:{}}function Ya(e,t){return Object.keys(e).slice(0,Qy).map(n=>({name:y(n.slice(0,ew)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:t,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function dd(){let e=[],t=tw(),r=cd(t);if(Io(r)){let a=r,l=qa(a);e.push(...Ya(l,"user"));let u=process.cwd();if(Io(a.projects)){let c=a.projects[u];if(Io(c)){let d=qa(c);e.push(...Ya(d,"local"));}}}let n=rw(),o=cd(n),s=qa(o);e.push(...Ya(s,"project"));let i=new Map;for(let a of e){let l=`${a.name}@${a.scope}`;i.has(l)||i.set(l,a);}return [...i.values()]}L();var rt=x("storage");async function ow(e,t,r){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:r,source:t,interface:Y().interfaceType});}catch(n){rt.warn(`Failed to send uninstall metrics: ${String(n)}`);}}function sw(e,t,r){let n=t==="enabled"?I.CLI_TOOL_ENABLED:I.CLI_TOOL_DISABLED;v(n,{tool_id:e,source:r,interface:Y().interfaceType}).catch(o=>rt.warn(`Failed to send ${t} metrics: ${String(o)}`));}function tl(){return xe__default.join($e__default.homedir(),".claude","plugins","installed_plugins.json")}function iw(){return xe__default.join($e__default.homedir(),".claude","plugins")}function qs(e){let t;try{t=Ie__default.realpathSync(e);}catch{t=xe__default.resolve(e);}let r=xe__default.resolve(iw()),n=xe__default.resolve(xe__default.join(process.cwd(),".claude","plugins")),o=t.startsWith(r+xe__default.sep),s=t.startsWith(n+xe__default.sep);if(!o&&!s)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function pd(e="user"){return e==="local"?xe__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?xe__default.join(process.cwd(),".claude","settings.json"):xe__default.join($e__default.homedir(),".claude","settings.json")}function ot(){let e=tl();if(!Ie__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(Ie__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function rl(){let e=tl();try{let t=await Ie__default.promises.readFile(e,"utf-8");return JSON.parse(t)}catch{return {version:2,plugins:{}}}}function aw(e){let t=e?.code;return t==="EACCES"||t==="EPERM"}function md(e,t){try{Ie__default.mkdirSync(xe__default.dirname(e),{recursive:!0});let r=`${e}.${randomUUID()}.tmp`;Ie__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),Ie__default.renameSync(r,e);}catch(r){throw aw(r)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):r}}function nt(e){md(tl(),e);}function bo(e){let t=e.lastIndexOf("@");return t===-1?{name:e,marketplace:""}:{name:e.slice(0,t),marketplace:e.slice(t+1)}}function lw(e,t){let r=xe__default.join(e,".claude-plugin"),n=xe__default.join(r,"plugin.json");if(Ie__default.existsSync(n))try{return JSON.parse(Ie__default.readFileSync(n,"utf-8"))}catch{return null}let o=xe__default.join(r,"marketplace.json");if(Ie__default.existsSync(o))try{let s=JSON.parse(Ie__default.readFileSync(o,"utf-8"));return {description:s.plugins?.find(a=>a.name===t)?.description,author:s.owner}}catch{return null}return null}function nl(e="user"){let t=pd(e);if(!Ie__default.existsSync(t))return {};try{return JSON.parse(Ie__default.readFileSync(t,"utf-8"))}catch{return {}}}function fd(e,t="user"){md(pd(t),e);}function cw(e,t){let{name:r,marketplace:n}=bo(e),o;if(n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],!o)throw rt.error(`[${r}] Plugin is not installed`),new Error(`Plugin '${r}' is not installed`);return {key:o,name:r}}function uw(e,t){let{name:r,marketplace:n}=bo(e),o;return n?(o=`${r}@${n}`,t[o]||(o=void 0)):o=Object.keys(t).filter(i=>bo(i).name===r)[0],o?{key:o,name:r}:null}function Za(e="user"){return nl(e).enabledPlugins??{}}function Qa(e,t="user"){let r=nl(t),n=r.enabledPlugins;if(!n||!(e in n))return;let{[e]:o,...s}=n;r.enabledPlugins=s,fd(r,t);}function vo(e,t,r="user"){let n=nl(r),o=n.enabledPlugins??{};n.enabledPlugins={...o,[e]:t},fd(n,r);}function dw(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 ie(){let e=ot(),t=Za(),r=Za("project"),n=Za("local"),o={project:r,local:n},s=Object.entries(e.plugins).flatMap(([u,c])=>{let{name:d,marketplace:m}=bo(u),p=c.map(h=>h.scope==="managed"?{...h,scope:"user"}:h);return dw(p).map(h=>{let g=lw(h.installPath,d),b=(o[h.scope]??t)[u];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:b===false?"disabled":"enabled"}})}),i=dd(),a=new Set(s.map(u=>`${u.name}@${u.scope}`)),l=i.filter(u=>!a.has(`${u.name}@${u.scope}`));return [...s,...l]}async function Eo(e,t){rt.debug(`[${e}] Acquiring lock to uninstall`);let r=await Pr();try{let n=ot(),o=uw(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`);rt.debug(`[${i}] Resolved key: ${s}, scope: ${t}`),qs(l.installPath);let u=xe__default.dirname(l.installPath);qs(u),rt.debug(`[${i}] Removing directory: ${u}`),Ie__default.rmSync(u,{recursive:!0,force:!0});let c=a.filter(d=>d.scope!==t);if(c.length===0){let{[s]:d,...m}=n.plugins;nt({...n,plugins:m}),Qa(s,t),Xa(i);}else n.plugins[s]=c,nt(n),Qa(s,t);}else {rt.debug(`[${i}] Resolved key: ${s}`);for(let c of a){qs(c.installPath);let d=xe__default.dirname(c.installPath);qs(d),rt.debug(`[${i}] Removing directory: ${d}`),Ie__default.rmSync(d,{recursive:!0,force:!0}),Qa(s,c.scope);}Xa(i);let{[s]:l,...u}=n.plugins;nt({...n,plugins:u});}await ow(i,a[0].origin??"internal",a[0].type??"skill"),rt.debug(`[${i}] Uninstalled successfully`);}finally{await r();}}async function Po(e,t,r){rt.debug(`[${e}] Acquiring lock to set status \u2192 ${t}`);let n=await Pr();try{let o=ot(),{key:s,name:i}=cw(e,o.plugins),a=o.plugins[s],l=r??a[0].scope,u=a[0].origin??"internal";rt.debug(`[${i}] Resolved key: ${s}, scope: ${l}`),vo(s,t==="enabled",l),sw(i,t,u),rt.debug(`[${i}] Status updated to ${t}`);}finally{await n();}}K();L();var pw=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,mw=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function St(e){if(!pw.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function fw(e){if(!mw.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 Tr=x("installer");function gw(e,t){let r=`${e}@${ee}`,o=ot().plugins[r];if(o&&!t)throw new Je(e,o[0].version??"unknown");return {pluginKey:r,alreadyInstalled:o}}async function hw(e,t,r){r&&await Wa(t);try{Tr.debug(`[${t}] Extracting archive...`),await nd(e,t);}catch(n){throw await Wa(t),n}}function yw(e,t,r,n,o,s="claude-code",i){let a=ot(),l={scope:n,installPath:t,version:r,installedAt:new Date().toISOString(),origin:o,providerId:s,type:i},u=a.plugins[e]??[];a.plugins[e]=[...u.filter(c=>c.scope!==n),l],nt(a),vo(e,true,n);}async function ww(e,t,r,n,o,s){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:s,source:o,scope:n,version:t,duration_ms:r,interface:Y().interfaceType});}catch(i){Tr.warn(`Failed to send install metrics: ${String(i)}`);}}async function Sw(e,t,r,n){try{await v(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:Y().interfaceType});}catch(o){Tr.warn(`Failed to send install-failed metrics: ${String(o)}`);}}async function Re(e,t={}){let r=Date.now(),n=null;try{Tr.debug(`[${e}] Acquiring lock...`),n=await Pr();let{pluginKey:o,alreadyInstalled:s}=gw(e,t.force),{source:i}=t;Tr.debug(`[${e}] Fetching manifest...`);let a=await _n(e,i);St(a.name),fw(a.version),Tr.debug(`[${e}] Downloading archive...`);let l=await rd(e,t.onDownloadProgress,i),u=t.scope??"user",c=t.type??"skill",d=oc(a.name,a.version);await hw(l,d,!!s&&!!t.force),yw(o,d,a.version,u,"internal",t.providerId,c),ad(a,d);let m=Date.now()-r;Tr.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:a.name,version:a.version,path:d,duration_ms:m};return t.skipMetrics||await ww(a.name,a.version,m,Hs(u),"internal",c),p}catch(o){throw await Sw(e,o,"internal",t.type??"skill"),Tr.error(`[${e}] Installation failed: ${o instanceof Error?o.message:String(o)}`),o}finally{n&&await n();}}L();V();Ee();Sn();L();var xw=x("commands:helpers");async function de(){let e=await re();if(!e)return E("Not authenticated. Run: flow auth login"),false;e.customUrl&&Tt(e.customUrl);try{await Ct();}catch(t){return xw.debug(`Token validation failed: ${String(t)}`),E("Session expired. Run: flow auth login"),false}return true}async function Rt(e){let t=ol.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 gd(e){let t=ol.createInterface({input:process.stdin,output:process.stdout});return new Promise(r=>{t.question(y(e),n=>{t.close(),r(n.trim());});})}Er();var On=x("claudeProxy"),ll="claude ",hd="flow ",sl=class extends Error{constructor(t){super(`Invalid install command: "${t}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},Dn=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";}},Iw=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,bw=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,vw={"--scope":/^(local|user|global|project)$/,"--transport":/^(sse|stdio|http)$/,"--env":/^[A-Za-z_][A-Za-z0-9_]*=/,"--header":/^[A-Za-z0-9][A-Za-z0-9-]*:/,"--timeout":/^\d{1,10}$/,"--timeout-ms":/^\d{1,10}$/,"--prefix-args":/^[\x20-\x7e]{1,500}$/},Ew=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Pw=/^(flow|claude)\s+auth\s+login(\s|$)/,yd=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function wd(e){return yd.test(e.trim())}function Tw(e){return yd.exec(e.trim())?.[2]??""}async function Sd(e){let t=Tw(e);Ja(t);let r=Date.now();On.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 cl(n)?new il:n}}function Cw(e){xd(e);let t=e.slice(ll.length);if(!Iw.test(t))throw new Dn(e)}var Ys=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},il=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function xd(e){if(!e||!/^claude /.test(e))throw new sl(e)}function kw(e){for(let t=0;t<e.length;t++){let r=e[t];if(r==="--")return;if(!r.startsWith("-"))continue;if(!bw.test(r))throw new Dn(`Unexpected flag: ${r}`);let n=vw[r];if(n!==void 0){let o=e[t+1];if(o===void 0||o.startsWith("-"))throw new Dn(`Flag ${r} requires a value`);if(!n.test(o))throw new Dn(`Unsafe value for flag ${r}`);t++;}}}async function Ce(e){xd(e);let t=e.slice(ll.length).split(/\s+/).filter(Boolean);kw(t);let r=Aw(t);On.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 On.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 cl(o)?new Ys:o}}function Aw(e){return e.length>=3?e[2]:e.join(" ")}function cl(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function $w(e){return e.startsWith(hd)?ll+e.slice(hd.length):e}function Lw(e){return Ew.test(e)||Pw.test(e)}function Mw(e){let t=0;for(;t<e.length&&Lw(e[t]);)t++;return e.slice(t)}var Rw=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function _w(e,t){return !t||e.includes("--scope")||!Rw.test(e)?e:`${e} --scope ${t}`}async function To(e,t){let r=e.split("&&").map(i=>i.trim()).filter(Boolean),o=Mw(r).map(i=>$w(i)).map(i=>_w(i,t));if(o.length===0)throw new Error("Empty install command");for(let i of o)Cw(i);On.debug(`[installCommand] Executing ${o.length} command(s)`);let s=await Ce(o[0]);if(s.exitCode!==0)return s;for(let i=1;i<o.length;i++)if(s=await Ce(o[i]),s.exitCode!==0)return s;return s}async function Zs(e,t,r){let n=$n(e),o=t?.trim();if(!o&&(o=(await gd(`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=zs(o),r?.(),On.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"}`);On.debug(`[${n}] Marketplace added successfully`);}catch(s){throw cl(s)?new Ys:s}}Er();K();qe();L();var Nw=6e4,Cr=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 _t(e,t){let r=await mkdtemp(join(tmpdir(),"flow-skills-")),n=simpleGit({timeout:{block:Nw}}).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 Cr("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):l?new Cr(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Cr(`Failed to clone ${e}: ${i}`,e,false,false)}}async function Dt(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 Qr(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 jw(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function Kw(e){return typeof e=="object"&&e!==null&&e.source==="url"}function Vw(e){return typeof e=="object"&&e!==null&&e.source==="github"}function Un(e,t){let r=e.source;if(jw(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(Kw(r))return {cloneUrl:r.url,subPath:"."};if(Vw(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 st(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var Ot=x("claude-code.adapter");function Gw(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=Zo();if(!Ie__default.existsSync(s))return r;try{let i=JSON.parse(Ie__default.readFileSync(s,"utf-8"));for(let[a,l]of Object.entries(i))if(l.source?.repo===o)return a}catch{}return r}async function Cd(e,t){let r=e.catalogId?ue.getAdapter(e.catalogId):void 0,n=Un(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=Gw(e.catalogId,r?.source),i=t.scope??"user",a;o?a=zi(s,e.name,"external"):a=join(Or(i==="user"?"global":"project"),e.name);let l=null;try{St(e.name),l=await _t(n.cloneUrl,n.ref);let u=n.subPath==="."?l:join(l,n.subPath);if(Ie__default.existsSync(a)&&Ie__default.rmSync(a,{recursive:!0,force:!0}),Ie__default.mkdirSync(dirname(a),{recursive:!0}),Ie__default.cpSync(u,a,{recursive:!0}),o){let c=`${e.name}@${s}`,d=await rl(),m={scope:i,installPath:a,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=d.plugins[c]??[];d.plugins[c]=[...p.filter(f=>f.scope!==i),m],nt(d),vo(c,!0,i);}return {success:!0,message:`Installed ${e.name} from ${n.cloneUrl}`}}catch(u){return Ot.debug(`[${e.name}] External catalog install failed: ${String(u)}`),{success:false,message:u instanceof Error?u.message:String(u)}}finally{l&&await Dt(l).catch(()=>{});}}async function ul(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:r,source:"external",scope:Hs(n),version:"unknown",duration_ms:t,interface:Y().interfaceType});}catch(o){Ot.warn(`Failed to send external install metrics: ${String(o)}`);}}async function Pd(e,t,r){try{await v(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:Y().interfaceType});}catch(n){Ot.warn(`Failed to send external install-failed metrics: ${String(n)}`);}}var Ww={async install(e,t){if(e.origin===sn&&!e.installCommand&&!An(e.name))return Cd(e,t);if(e.origin===sn&&e.installCommand){let r=e.type??"skill",n=await To(e.installCommand,t.scope);return n.exitCode===0?(await ul(e.name,n.duration_ms,r,t.scope),{success:true,message:`Installed ${e.name}`}):(await Pd(e.name,new Error(n.stderr||"Install failed"),r),{success:false,message:n.stderr||`Install failed with exit code ${n.exitCode}`})}if(An(e.name)){let r=e.type??"skill",n=Ln(e.name,t.scope);Ot.debug(`[${e.name}] Attempting install: ${n}`);let o=await Ce(n);if(o.exitCode===0)return await ul(e.name,o.duration_ms,r,t.scope),{success:true};Ot.debug(`[${e.name}] First attempt failed, adding marketplace`),await Zs(e.name,t.marketplaceSource,()=>{});let s=await Ce(n);return s.exitCode===0?(await ul(e.name,s.duration_ms,r,t.scope),{success:true}):(await Pd(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 Re(e.name,{...t,type:e.type});return {success:!0,message:`Installed ${e.name}@${r.version}`}}catch(r){return Ot.debug(`[${e.name}] Plugin install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}},async uninstall(e,t){await Eo(e,t);},getInstallPath(e,t){return ""}};function Td(e){return {async install(t,r){if(t.origin===sn&&!t.installCommand&&!An(t.name))return Cd(t,r);if(!t.installCommand)try{let o=await Re(t.name,{...r,type:e});return {success:!0,message:`Installed ${t.name}@${o.version}`}}catch(o){return Ot.debug(`[${t.name}] ${e} install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}Ot.debug(`[${t.name}] Executing install command: ${t.installCommand}`);let n=await To(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=ot(),o=`${t}@${ee}`;if(n.plugins[o]){await Eo(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 zw(e){for(let t of [join(e,".claude","agents"),join(e,"agents")]){if(!Ie__default.existsSync(t))continue;let r=Ie__default.readdirSync(t).filter(n=>n.endsWith(".md")&&Ie__default.lstatSync(join(t,n)).isFile());if(r.length>0)return r.map(n=>join(t,n))}return []}function dl(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,dl(r)]))}function kd(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(dl(a))));r[n]=[...s,...o.filter(a=>!i.has(JSON.stringify(dl(a))))];}else o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?r[n]=kd(s,o):r[n]=o;}return r}async function Ad(e,t,r,n){let o=await rl(),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],nt(o);}var Xw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ue.getAdapter(e.catalogId):void 0,o=Un(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{St(e.name),s=await _t(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=zw(i);if(a.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let l=es(r);Ie__default.mkdirSync(l,{recursive:!0});let u=st(e.name);if(a.length===1)Ie__default.copyFileSync(a[0],join(l,`${u}.md`));else for(let d of a){let m=st(basename(d,".md"));Ie__default.copyFileSync(d,join(l,`${u}--${m}.md`));}let c=a.length===1?join(l,`${u}.md`):l;return await Ad(e.name,r,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(i){return Ot.debug(`[${e.name}] Agent install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Dt(s).catch(()=>{});}},async uninstall(e,t){let r=es(t),n=st(e);if(Ie__default.existsSync(r))for(let a of Ie__default.readdirSync(r).filter(l=>l===`${n}.md`||l.startsWith(`${n}--`)&&l.endsWith(".md")))Ie__default.rmSync(join(r,a),{force:true});let o=`${e}@claude-code`,s=ot(),i=(s.plugins[o]??[]).filter(a=>a.scope!==t);if(i.length===0){let{[o]:a,...l}=s.plugins;nt({...s,plugins:l});}else nt({...s,plugins:{...s.plugins,[o]:i}});},getInstallPath(e,t){return join(es(t),`${st(e)}.md`)}},qw={async install(e,t){let r=t.scope??"user",n=e.catalogId?ue.getAdapter(e.catalogId):void 0,o=Un(e,n?.source);if(!o)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let s=null;try{St(e.name),s=await _t(o.cloneUrl,o.ref);let i=o.subPath==="."?s:join(s,o.subPath),a=join(i,"settings.json");if(!Ie__default.existsSync(a))return {success:!1,message:`No settings.json found in "${e.name}"`};let l;try{l=JSON.parse(Ie__default.readFileSync(a,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let u=l.hooks;if(!u||typeof u!="object"||Array.isArray(u))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=mo();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let d=c.status==="ok"?c.settings:{},m=d.hooks!==null&&typeof d.hooks=="object"&&!Array.isArray(d.hooks)?d.hooks:{},p=kd(m,u);return vs({...d,hooks:p}),await Ad(e.name,r,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(i){return Ot.debug(`[${e.name}] Hook install failed: ${String(i)}`),{success:false,message:i instanceof Error?i.message:String(i)}}finally{s&&await Dt(s).catch(()=>{});}},async uninstall(e,t){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,t){return ""}},Qs=class{id="claude-code";name="Claude Code";async isAvailable(){return Qr("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:Ww,skill:Td("skill"),mcp:Td("mcp"),agent:Xw,hook:qw}};function ei(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 Zw=new Set(["gh"]),Qw=ei(Zw,"use: gh copilot mcp remove <name>"),ti=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await Qr("gh",["--version"])?Qr("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:Qw}};qe();var eS=new Set(["opencode"]),tS=ei(eS,"use: opencode config remove mcp <name>");function rS(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 $d(){return {async install(e,t){try{St(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let r=e.catalogId?ue.getAdapter(e.catalogId):void 0,n=Un(e,r?.source);if(!n)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let o=null;try{o=await _t(n.cloneUrl,n.ref);let s=n.subPath==="."?o:join(o,n.subPath),i=Qo(t.scope??"user"),a=join(s,".opencode","plugins");if(Ie__default.existsSync(a)){let l=Ie__default.readdirSync(a).filter(u=>u.endsWith(".js")||u.endsWith(".mjs"));if(l.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};Ie__default.mkdirSync(i,{recursive:!0}),Ie__default.copyFileSync(join(a,l[0]),join(i,`${e.name}.js`));}else {let l=join(i,`${e.name}-content`);Ie__default.existsSync(l)&&Ie__default.rmSync(l,{recursive:!0,force:!0}),Ie__default.mkdirSync(l,{recursive:!0}),Ie__default.cpSync(s,l,{recursive:!0}),Ie__default.mkdirSync(i,{recursive:!0}),Ie__default.writeFileSync(join(i,`${e.name}.js`),rS(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 Dt(o).catch(()=>{});}},async uninstall(e,t){St(e);let r=Qo(t),n=join(r,`${e}.js`),o=join(r,`${e}-content`);Ie__default.existsSync(n)&&Ie__default.rmSync(n,{force:true}),Ie__default.existsSync(o)&&Ie__default.rmSync(o,{recursive:true,force:true});},getInstallPath(e,t){return join(Qo(t),`${e}.js`)}}}var ri=class{id="opencode";name="OpenCode";async isAvailable(){return Qr("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:tS,skill:$d(),bundle:$d()}};var Ut=new Js;Ut.register(new Qs);wr()&&(Ut.register(new ti),Ut.register(new ri));function Ld({itemName:e,itemType:t,onInstall:r,onClose:n}){let[o,s]=useState(false),[i,a]=useState(false),[l,u]=useState([]),[c,d]=useState(void 0);useEffect(()=>{Ut.getAvailableProviders(t??"bundle").then(u).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(b=>b.name===g);w?(d(w.id),a(false),s(true)):a(false);},[l]),f=useCallback(g=>{let w=Ku(g);w?r(w,c):s(false);},[r,c]),h=useCallback(()=>{s(false);},[]);if(i){let g=[...l.map(w=>w.name),"Cancel"];return jsx(tt,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>a(false)},"provider")}return o?jsx(tt,{itemName:`${e} \u2014 Choose scope`,actions:Fu,descriptions:ju,onAction:f,onClose:h},"scope"):jsx(tt,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:n},"main")}V();function Rd({itemName:e,bundle:t,onInstall:r,onConfirm:n,onClose:o}){let s=S(f=>f.focus),[i,a]=useState(0),u=(t?.artifact.artifacts??[]).filter(f=>f.available),c=t!==void 0&&u.length===0,d=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{a(0);},[t]);let m=useCallback((f,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:[u.length," artifact",u.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:u.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(tt,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:o})}function si({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")}}V();function Od({itemName:e,itemScope:t,itemStatus:r,updateAvailable:n,catalogVersion:o,onUninstall:s,onToggleStatus:i,onUpdate:a,onClose:l}){let{isConfirming:u,requestConfirm:c}=si({activeFocus:"actionMenu",onConfirm:()=>s(t)});if(u)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let d=r==="enabled"?"Disable":"Enable",m=o&&y(o),p=m?`Update to v${m}`:"Update";return jsx(tt,{itemName:e,actions:n?["Uninstall",d,p,"Cancel"]:["Uninstall",d,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===d?i(t):g.startsWith("Update")?a?.():l();},onClose:l})}function Nd({itemName:e,itemScope:t,onUninstall:r,onClose:n}){let{isConfirming:o,requestConfirm:s}=si({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(tt,{itemName:e,actions:["Uninstall","Cancel"],onAction:l=>{l==="Uninstall"?s():n();},onClose:n})}L();var Fn=x("bundle:installer"),Fd=/already exists/i;async function uS(e){if(!e.installCommand)throw new Error("Missing install command");let t=e.installCommand;if(wd(t)){let r=await Sd(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Fd.test(n))return;throw new Error(n)}}else {let r=await To(t);if(r.exitCode!==0){let n=r.stderr?.trim()||r.stdout?.trim()||`exit code ${r.exitCode}`;if(Fd.test(n))return;throw new Error(n)}}}async function dS(e,t){try{await v(I.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:t});}catch(r){Fn.warn(`Failed to emit bundle install started event: ${String(r)}`);}}async function pS(e,t,r){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:t,artifact_type:r});}catch(n){Fn.warn(`Failed to emit bundle install plugin success event: ${String(n)}`);}}async function jd(e,t,r,n){try{await v(I.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:t,artifact_type:r,error_message:n});}catch(o){Fn.warn(`Failed to emit bundle install plugin failed event: ${String(o)}`);}}async function mS(e,t,r,n,o){try{await v(I.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:t,failed_count:r,unavailable_count:n,duration_ms:o});}catch(s){Fn.warn(`Failed to emit bundle install completed event: ${String(s)}`);}}async function li(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 dS(i,o.length);let l=[],u=0,c=o.length;for(let[p,f]of o.entries()){let h=f.name??f.flowId,g=f.type??"unknown";if(!f.type){Fn.warn(`Artifact "${h}" has no type \u2014 treated as failed`),l.push({name:h,type:g,reason:"unknown artifact type"}),await jd(i,h,g,"unknown artifact type"),r?.({index:p+1,total:c,artifact:f,success:false,error:"unknown artifact type"});continue}try{await uS(f),u++,await pS(i,h,g),r?.({index:p+1,total:c,artifact:f,success:!0});}catch(w){let b=w instanceof Error?w.message:String(w);Fn.error(`Failed to install artifact "${h}": ${b}`),l.push({name:h,type:g,reason:b}),await jd(i,h,g,b),r?.({index:p+1,total:c,artifact:f,success:false,error:b});}}let d=Date.now()-a,m=l.length;return await mS(i,u,m,s,d),{bundleTitle:e.title,total:n.length,installed:u,skipped:s,failed:m,failures:l}}V();function Hd({bundle:e,onComplete:t}){let[r,n]=useState(null),[o,s]=useState(null),i=useRef(false);return useEffect(()=>{i.current||(i.current=true,li(e,{onProgress:n}).then(s).catch(a=>{let l=a instanceof Error?a.message:"Installation failed",u=e.artifact.artifacts,c=u.filter(d=>d.available);s({bundleTitle:e.title,total:u.length,installed:0,skipped:u.length-c.length,failed:c.length,failures:c.map(d=>({name:d.name??d.flowId,type:d.type??"unknown",reason:l}))});}));},[e]),useEffect(()=>{o&&t(o);},[o,t]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),r&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(Jd,{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(Jd,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:t=>e({installedItems:t}),loadFromDisk:()=>e({installedItems:ie()})}));V();function Gd({entries:e,selectedIndex:t,focusPanel:r}){let n=r==="list",o=t===0&&n;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:o,dimColor:!n,children:"+ Add Marketplace"})]}),e.map((s,i)=>{let a=i+1,l=t===a&&n,u=s.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:l?"\u203A ":" "}),jsx(Text,{bold:l,dimColor:!n,children:s.adapter.name}),u&&s.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),s.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Pt(s.stored.lastUpdated)]})})]},s.adapter.id)})]})}V();function Wd({entry:e,detailData:t,installedCount:r,focusPanel:n,actionIndex:o,onBrowse:s,onUpdate:i,onToggleAutoUpdate:a,onRemove:l}){let{adapter:u,stored:c}=e,d=u.removable!==false,m=c?.autoUpdate!==false,p=n==="detail",f=[{label:`Browse plugins${t&&!t.loading?` (${t.items.length})`:""}`,handler:s},{label:"Update marketplace",handler:i},...d?[{label:"Toggle auto-update",handler:a},{label:"Remove marketplace",handler:l,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:t?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):t?.error?jsx(Text,{color:"red",children:t.error}):jsxs(Text,{dimColor:true,children:[t?`${t.items.length} available`:"\u2014 available",r>0?` \xB7 ${r} installed`:"",c?.lastUpdated?` \xB7 Updated ${Pt(c.lastUpdated)}`:""]})}),c&&jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Auto-update: "}),m?jsx(Text,{color:"green",children:"enabled \u2605"}):jsx(Text,{dimColor:true,children:"disabled"})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:f.map((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:u.name}),jsx(Text,{dimColor:true,children:u.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function zd(e){return e.adapter.removable!==false?4:2}K();V();function Xd({item:e,adapterName:t,isInstalled:r,onBack:n,onInstall:o,onUninstall:s}){let i=[...r&&s?[{label:"Uninstall",handler:()=>s(e),danger:true}]:!r&&o?[{label:"Install",handler:()=>o(e)}]:[],{label:"Back",handler:n}],[a,l]=useState(0);return useInput((u,c)=>{if(c.escape){n();return}if(c.upArrow){l(d=>Math.max(0,d-1));return}if(c.downArrow){l(d=>Math.min(i.length-1,d+1));return}c.return&&i[a].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",t," \u203A Browse plugins \u203A ",y(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:y(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",y(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",y(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:y(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",y(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",y(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",y(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:i.map((u,c)=>jsxs(Box,{children:[jsx(Text,{color:c===a?"cyan":void 0,children:c===a?"\u203A ":" "}),jsx(Text,{bold:c===a,color:u.danger?"yellow":void 0,dimColor:c!==a,children:u.label})]},u.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Yd({item:e,isSelected:t,isInstalled:r}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:t?"\u203A ":" "}),jsx(Text,{color:r?"green":void 0,bold:t,children:e.name}),r&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Zd({entry:e,items:t,installedKeys:r,onBack:n}){let o=e.adapter.id??"default",s=t.filter(P=>r.has(`${P.name}@${o}`)),i=t.filter(P=>!r.has(`${P.name}@${o}`)),a=[...s,...i],[l,u]=useState(0),[c,d]=useState(null);if(useInput((P,$)=>{if($.escape){n();return}if($.return){d(a[l]??null);return}if($.upArrow){u(_=>Math.max(0,_-1));return}$.downArrow&&u(_=>Math.min(a.length-1,_+1));},{isActive:c===null}),c!==null)return jsx(Xd,{item:c,adapterName:e.adapter.name,isInstalled:r.has(`${c.name}@${o}`),onBack:()=>d(null)});if(t.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,l-Math.floor(Xe/2)),p=Math.min(a.length,m+Xe);p===a.length&&(m=Math.max(0,p-Xe));let f=a.slice(m,p),h=m,g=a.length-p,w=s.length>0&&m<s.length,b=p>s.length,D=f.filter(P=>r.has(`${P.name}@${o}`)),R=f.filter(P=>!r.has(`${P.name}@${o}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children: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"]}),D.map(P=>jsx(Yd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:true},P.name))]}),b&&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"]}),R.map(P=>jsx(Yd,{item:P,isSelected:a.indexOf(P)===l,isInstalled:false},P.name))]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children: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"})})]})}Ga();var xS=/^https?:\/\/.+/;function IS(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function bS(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function rp(e){let t=S(g=>g.showNotification),r=S(g=>g.incrementCatalogVersion),[n,o]=useState("idle"),[s,i]=useState(""),[a,l]=useState(""),[u,c]=useState(null),d=useRef(""),m=useRef("");useEffect(()=>{d.current=s;},[s]),useEffect(()=>{m.current=a;},[a]);let p=useCallback(()=>{d.current="",m.current="",i(""),l(""),c(null),o("add-name");},[]),f=useCallback(()=>{o("idle");},[]),h=useCallback(async()=>{let g=m.current,w=d.current;if(!xS.test(g)){c("URL must start with http:// or https://");return}c(null),o("adding");let b=randomUUID(),D=new Rn(b,w,g);try{await D.fetchItems(),await Wt.add({id:b,name:w,source:g}),ue.register(new Rn(b,w,g)),r(),e(),t(`Catalog "${w}" added`,"success"),i(""),l(""),d.current="",m.current="",o("idle");}catch(R){let P=IS(R)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":bS(R)?R.message:R instanceof Error?`Could not reach catalog URL: ${R.message}`:"Failed to validate catalog URL";t(P,"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),c(null);return}g&&!w.ctrl&&!w.meta&&(m.current=m.current+g,l(m.current),c(null));},{isActive:n==="add-url"}),{phase:n,inputName:s,inputUrl:a,urlError:u,setInputName:i,setInputUrl:l,startAdd:p,cancelAdd:f}}function np(e){let t=S(o=>o.showNotification),r=S(o=>o.incrementCatalogVersion);return {handleRemove:useCallback(async o=>{try{await Wt.remove(o),ue.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 sp(){let e=S(A=>A.focus),t=S(A=>A.setFocus),r=S(A=>A.showNotification),n=fe(A=>A.installedItems),[o,s]=useState(()=>ue.listAdapters().map(A=>({adapter:A,stored:null}))),[i,a]=useState(0),[l,u]=useState("list"),[c,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 A=ue.listAdapters(),B=await Wt.read(),G=new Map(B.map(Ae=>[Ae.id,Ae]));s(A.map(Ae=>({adapter:Ae,stored:G.get(Ae.id)??null})));})();},[]);useEffect(()=>{t("marketplaces"),w();},[t,w]),useEffect(()=>{if(i===0){p(null);return}let A=g.current[i-1];if(!A)return;let B=false;return p({items:[],loading:true,error:null}),A.adapter.fetchItems().then(G=>{B||p({items:G,loading:false,error:null});}).catch(G=>{B||p({items:[],loading:false,error:G instanceof Error?G.message:"Failed to load catalog"});}),()=>{B=true;}},[i]);let b=rp(w),D=useCallback(()=>{w(),a(0),u("list"),p(null),h("main");},[w]),{handleRemove:R}=np(D),P=useCallback(async A=>{h("removing"),await R(A);},[R]),$=useCallback(async A=>{try{let B=await A.adapter.fetchItems();if(p({items:B,loading:!1,error:null}),A.stored){let G=new Date().toISOString();await Wt.updateField(A.stored.id,{lastUpdated:G}),w();}r("Marketplace updated","success");}catch(B){r(B instanceof Error?B.message:"Update failed","error");}},[w,r]),_=useCallback(async A=>{if(!A.stored)return;let B=A.stored.autoUpdate!==false;await Wt.updateField(A.stored.id,{autoUpdate:!B}),w();},[w]),O=useCallback(()=>h("browse"),[]),Q=useCallback(A=>{let B=o[i-1];if(!B)return;let G=B.adapter.removable!==false;[O,()=>{$(B);},...G?[()=>{_(B);},()=>{P(B.adapter.id);}]:[]][A]?.();},[o,i,O,$,_,P]),k=useCallback(()=>h("main"),[]),J=useCallback(()=>{let A=o[i-1];A&&$(A);},[o,i,$]),Z=useCallback(()=>{let A=o[i-1];A&&_(A);},[o,i,_]),N=useCallback(()=>{let A=o[i-1];A&&P(A.adapter.id);},[o,i,P]);if(useInput((A,B)=>{if(B.upArrow){a(G=>Math.max(0,G-1));return}if(B.downArrow){a(G=>Math.min(o.length,G+1));return}(B.return||B.tab)&&(i===0?b.startAdd():(u("detail"),d(0)));},{isActive:f==="main"&&b.phase==="idle"&&l==="list"&&e==="marketplaces"}),useInput((A,B)=>{if(B.escape||B.tab){u("list");return}if(B.upArrow){d(G=>Math.max(0,G-1));return}if(B.downArrow){let G=o[i-1],Ae=G?zd(G)-1:0;d(Wo=>Math.min(Wo+1,Ae));return}B.return&&Q(c);},{isActive:f==="main"&&b.phase==="idle"&&l==="detail"&&e==="marketplaces"}),b.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:b.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.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(b.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:b.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:b.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),b.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:b.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(b.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",G=new Set(n.filter(Ae=>Ae.marketplace===A.adapter.name).map(Ae=>`${Ae.name}@${B}`));return jsx(Zd,{entry:A,items:m?.items??[],installedKeys:G,onBack:k})}if(o.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let j=o[i-1]??null,z=j?n.filter(A=>A.marketplace===j.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Gd,{entries:o,selectedIndex:i,focusPanel:l})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:l==="detail"&&j?jsx(Wd,{entry:j,detailData:m,installedCount:z,focusPanel:l,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:Z,onRemove:N}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:j?"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 ip(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=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o-1+ne.length)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.rightArrow){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.length];return [{type:"setTab",tab:s.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:s.focus}]}if(t.tab){let o=ne.findIndex(i=>i.id===r.activeTab),s=ne[(o+1)%ne.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 ap(e,t){return t.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function lp(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 CS=new Set(ne.filter(e=>e.focus!=="list").map(e=>e.focus));function Oo(e){let{setActiveTab:t,setFocus:r,setSelectedIndex:n,setActionMenuOpen:o}=S.getState();for(let s of e)if(s.type==="setTab")t(s.tab);else if(s.type==="setFocus")r(s.focus);else if(s.type==="setSelectedIndex")n(s.index);else if(s.type==="setActionMenuOpen")o(s.open);else if(s.type==="searchAppend"){let{setQuery:i,query:a,setCursorPosition:l,cursorPosition:u}=Ve.getState();i(a.slice(0,u)+s.char+a.slice(u)),l(u+s.char.length);}else s.type==="toggleTypeFilter"?S.getState().toggleTypeFilter(s.catalogType):s.type==="selectAllTypes"?S.getState().selectAllTypes():s.type==="toggleOriginFilter"?S.getState().toggleOriginFilter(s.origin):s.type==="selectAllOrigins"&&S.getState().selectAllOrigins();}function cp({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=Ve(h=>h.query),a=Ve(h=>h.setQuery),l=Ve(h=>h.resetQuery),u=useRef(e);useEffect(()=>{u.current=e;},[e]),useEffect(()=>{if(t==="search"){let{query:h,setCursorPosition:g}=Ve.getState();g(h.length);}},[t]);let[c,d]=useState("");useEffect(()=>{let h=setTimeout(()=>d(i),300);return ()=>clearTimeout(h)},[i]),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo($a(h,g,{activeTab:w}));},{isActive:t==="tabs"}),useInput((h,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo($a("",g,{activeTab:w}));},{isActive:CS.has(t)}),useInput((h,g)=>{let{activeTab:w,selectedIndex:b,actionMenuOpen:D}=S.getState();Oo(ip(h,g,{activeTab:w,selectedIndex:b},u.current));},{isActive:t==="list"}),useInput((h,g)=>{Oo(ap(h,g));},{isActive:t==="actionMenu"}),useInput((h,g)=>{let w=lp(h,g,Ve.getState().query),b=w.queryUpdate;if(Oo(w.actions),b==="reset")l(),d("");else if(b!==null){let{query:D,cursorPosition:R,setCursorPosition:P}=Ve.getState();if("backspace"in b)R>0&&(a(D.slice(0,R-1)+D.slice(R)),P(R-1));else if("append"in b)a(D.slice(0,R)+b.append+D.slice(R)),P(R+b.append.length);else if("cursorMove"in b){let $=R+b.cursorMove;$>=0&&$<=D.length&&P($);}}},{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(!c)return u.current=h.length,h;let g=c.toLowerCase(),w=h.filter(b=>b.name.toLowerCase().includes(g)||b.description?.toLowerCase().includes(g));return u.current=w.length,w},[c]);return {actionMenuOpen:n,closeMenu:m,selectedIndex:r,clampIndex:p,filteredItems:f}}function dp(){let e=S(a=>a.notification),t=S(a=>a.showNotification),r=S(a=>a.clearNotification),n=Qe(a=>a.justAuthenticated),o=Qe(a=>a.credentials),s=Qe(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 Oe(e,t,r=false){return r?true:!hl.valid(e)||!hl.valid(t)?false:hl.gt(t,e)}K();L();var Yt=x("updater");async function kS(e,t,r,n,o,s){try{await v(I.CLI_TOOL_UPDATED,{tool_id:e,tool_type:s,source:o,from_version:t,to_version:r,duration_ms:n,interface:Y().interfaceType});}catch(i){Yt.warn(`Failed to send update metrics: ${String(i)}`);}}function AS(e){let t=ot(),r=`${e}@${ee}`,n=t.plugins[r];return !n||n.length===0?null:{pluginKey:r,entry:n[0]}}async function pi(e,t={}){let r=Date.now(),n=null;try{Yt.debug(`[${e}] Acquiring lock...`),n=await Pr();let o=AS(e);if(!o)throw Yt.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:s}=o,i=s.version,a=s.installPath;Yt.debug(`[${e}] Fetching manifest...`);let u=(await _n(e,t.source)).version;if(!i||!Oe(i,u,t.force))throw Yt.debug(`[${e}] Already up to date (v${i??"n/a"})`),new vr(e,i??"unknown");Yt.info(`[${e}] Updating v${i} \u2192 v${u}...`),await n(),n=null;try{let c=await Re(e,{force:!0,skipMetrics:!0,source:t.source}),d=Date.now()-r;return await kS(c.name,i,c.version,d,s.origin??"internal",s.type??"skill"),Yt.debug(`[${e}] Updated successfully in ${d}ms`),{name:c.name,previousVersion:i,newVersion:c.version,path:c.path,duration_ms:d}}catch(c){Yt.warn(`[${e}] Install failed, rolling back to v${i}...`),n=await Pr();let d=ot(),m=`${e}@${ee}`;throw d.plugins[m]&&(d.plugins[m][0].version=i,d.plugins[m][0].installPath=a,nt(d),Yt.info(`[${e}] Rollback completed, restored to v${i}`)),c}}finally{n&&await n();}}Er();L();var mi=x("dispatcher");async function $S(e,t,r,n,o){let s=$n(e);return mi.debug(`[${e}] Install failed (exit code), attempting marketplace add`),o?.onError?.(r),n?o?.onStatus?.(`Adding marketplace for ${s}...`):o?.onPause?.(),await Zs(e,n,()=>{}),o?.onResume?.(`Retrying install for ${s}...`),mi.debug(`[${e}] Retrying install after marketplace add`),Ce(t)}async function pp(e,t,r,n){let o=Ln(e,n),s=$n(e);r?.onStatus?.(`Installing ${s}...`),mi.debug(`[${e}] Attempting install: ${o}`);let i=await Ce(o);if(i.exitCode===0)return i;mi.debug(`[${e}] Install failed (exit ${i.exitCode}), attempting marketplace add`);let a=i.stderr||`Install failed with exit code ${i.exitCode}`;return $S(e,o,a,t,r)}async function mp(e,t,r){let n=e.type??"bundle",o=await Ut.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 fp(){let e=fe(i=>i.installedItems),t=fe(i=>i.loadFromDisk),r=useCallback(async(i,a)=>{let l=await mp(i,a);if(!l.success)throw new Error(l.message||"Installation failed");t();},[t]),n=useCallback(async(i,a)=>{let l=ie().find(p=>p.name===i),u=l?.providerId??"claude-code",c=Ut.getAdapter(u);if(!c)throw new Error(`Provider "${u}" not found`);let d=l?.type??"bundle",m=c.installers[d];if(!m)throw new Error(`Provider "${u}" does not support type "${d}"`);await m.uninstall(i,a??"user"),t();},[t]),o=useCallback(async(i,a)=>{let u=e.find(c=>c.name===i)?.status==="enabled"?"disabled":"enabled";await Po(i,u,a),t();},[e,t]),s=useCallback(async i=>{await pi(i),t();},[t]);return {install:r,uninstall:n,toggle:o,update:s}}V();L();var gi=x("mcp");function Uo(e,t){e.silent?Ze({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 hp(e,t){e.silent?je({status:"success",mcp:t.name,command:t.command,duration_ms:t.durationMs}):(ce(`MCP "${t.name}" ${t.actionPastTense} successfully`),e.verbose&&t.stdout&&C(t.stdout));}function LS(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 yl(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 yp(e,t,r){if(!await de())return 1;if(t.length===0){let s=r.transport==="http"?"a URL":"a command";return Uo(r,{name:e,action:"add",message:`${r.transport} transport requires ${s}`}),1}gi.debug(`[${e}] Starting MCP add with args: ${t.join(" ")}`);let n=LS(e,t,r.transport,r.scope);if(!r.force){let s=y(e),i=y(n);if(!await Rt(`Install external MCP "${s}"?
|
|
113
113
|
This will run: ${i}
|
|
114
|
-
[y/N] `))return
|
|
114
|
+
[y/N] `))return gi.debug(`[${e}] Installation cancelled by user`),C("Operation cancelled."),0}let o=r.silent?void 0:Jl({text:`Adding MCP "${y(e)}"...`}).start();try{let s=await Ce(n);return o?.stop(),s.exitCode!==0?(Uo(r,{name:e,action:"add",message:s.stderr||"Command failed",exitCode:s.exitCode}),!r.silent&&r.verbose&&s.stdout&&C(`stdout: ${s.stdout}`),1):(hp(r,{name:e,actionPastTense:"added",command:n,durationMs:s.duration_ms,stdout:s.stdout}),0)}catch(s){return o?.stop(),Uo(r,{name:e,action:"add",message:q(s)}),1}}async function wp(e,t){if(!await de())return 1;gi.debug(`[${e}] Starting MCP remove`);let r=yl(e,t.scope);if(!t.force){let o=y(e),s=y(r);if(!await Rt(`Remove MCP "${o}"?
|
|
115
115
|
This will run: ${s}
|
|
116
|
-
[y/N] `))return ti.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:Il({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await be(r);return n?.stop(),o.exitCode!==0?(Eo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(Nd(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Eo(t,{name:e,action:"remove",message:G(o)}),1}}function Kd({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(P=>P.setLoading),u=S(P=>P.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=Ud(),f=async(P,$,R)=>{l(true,P),n();try{await $(),o(r.length),s(R,"success");}catch(D){let X=D instanceof Error?D.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${X}`),s(X,"error");}finally{l(false);}};return {handleInstall:(P,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:P,...$!==void 0?{providerId:$}:{},onDownloadProgress:(R,D)=>{let X=Date.now();(X-a.current>100||R>=D)&&(a.current=X,u(R,D));}}),"\u2713 Installed successfully"));},handleUninstall:P=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,P),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${P}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(R){if(R instanceof hr)s(R.message,"info");else {let D=R instanceof Error?R.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${D}`),s(D,"error");}}finally{l(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let $=P.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let D=[];for(let j of P)D.push(await p(j.name).then(()=>({status:"fulfilled",value:void 0}),z=>({status:"rejected",reason:z})));let X=D.filter(j=>j.status==="fulfilled").length,k=D.map((j,z)=>j.status==="rejected"?P[z].name:null).filter(j=>j!==null);o(r.length),k.length===0?s(`\u2713 Updated ${X}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${X}/${$}; failed: ${k.join(", ")}`,X>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:P=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=za(e.name,P),R=await be($);if(R.exitCode!==0)throw new Error(R.stderr||"MCP removal failed");ue.getState().loadFromDisk();},"\u2713 MCP removed");}}}var Po=x("api:bundle"),_n=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},To=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},tS=/^[a-zA-Z0-9_-]{1,128}$/;async function Jd(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Po.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new _n(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new To:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Po.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function Hd(e){if(!tS.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Po.debug(`Fetching bundle by flowId "${e}"`);try{return await mt().get(`v1/use-cases/${t}`).json()}catch(r){return Jd(r,e)}}async function ri(e){let t=encodeURIComponent(e);Po.debug(`Fetching bundle by name "${e}"`);let r;try{r=await mt().get(`v1/use-cases/by-name/${t}`).json(),Po.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Jd(n,e)}if(r.length===0)throw new _n(e);return r[0]}var rS=x("tui:bundle-flow");function Gd({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();rS.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?Hd(d):ri(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),ue.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}var Co=["local","project","user"],nS=new Set(["--transport","--scope","-s"]);function Wd(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(nS.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function zr(e,t){return t?`${e}::${t}`:e}function Xa(e){return e===q?Fn:Zr}function zd(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??Fn,flowId:e.flowId}}function qa(e,t){let r=Xa(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 Xd(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:jn[r].label,pathHint:jn[r].pathHint,items:t.get(r)??[]}))}function qd(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 Yd({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>zr(f.name,f.author?.name))),[t]),i=useMemo(()=>new Set(t.filter(f=>f.type==="mcp").map(f=>f.name.toLowerCase())),[t]),a=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(zr(g.name,g.author?.name))??h.get(g.name),b=w?.version,_=!!b&&!!g.version&&Le(g.version,b);return {...g,updateAvailable:_,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(zr(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Wd(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>zd(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>qa(f,f.catalogItem)):a.map(f=>qa(f,f.catalogItem)),[r,e,s,i,a]),u=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]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[zr(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(zr(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function Ya(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await Eu();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,v(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(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Zd(){return {items:ue(t=>t.installedItems)}}var lS=x("catalog");function ep(){let e=S(H=>H.bundleInstallFlow),t=S(H=>H.activeTab),r=S(H=>H.notification),n=S(H=>H.loading),o=S(H=>H.loadingMessage),s=S(H=>H.downloadProgress),i=S(H=>H.downloadTotal),a=S(H=>H.catalogError),l=S(H=>H.setCatalogError),u=S(H=>H.catalogFilters),c=Be(H=>H.query),{catalog:d,isLoading:m,error:p,refetch:f}=Ya(),{items:h}=Zd(),g=ue(H=>H.loadFromDisk),{items:w,emptyMessage:b,getSelectedCatalogItem:_,outdatedCount:M}=Yd({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:P,closeMenu:$,selectedIndex:R,clampIndex:D,filteredItems:X}=Md({listLength:w.length}),k=X(w),j=useMemo(()=>t!=="installed"&&t!=="updates"?k:qd(k),[t,k]),z=useMemo(()=>t==="installed"||t==="updates"?Xd(j):[],[t,j]),B=j[R]??null,F=useMemo(()=>_(B),[_,B]),{notify:J}=_d(),{handleInstall:A,handleUninstall:U,handleToggleStatus:K,handleUpdate:Ee,handleBatchUpdate:_o,handleMcpConfigUninstall:df}=Kd({selectedItem:B,selectedCatalogItem:F,items:w,closeMenu:$,clampIndex:D,notify:J}),{handleBundleInstallStart:pf,handleBundleDetailConfirm:mf,handleBundleDetailBack:ff,handleBundleInstallComplete:gf}=Gd({closeMenu:$,notify:J}),hf=useCallback(()=>_o(j),[_o,j]);return useEffect(()=>{g();},[]),useEffect(()=>{D(j.length);},[j.length,D]),useEffect(()=>{p&&(lS.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(hn,{}),jsx(Nc,{outdatedCount:M}),t==="marketplaces"&&dr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(kd,{})}):jsx(tu,{filteredItems:j,groups:z,emptyMessage:b,onBatchUpdate:hf}),(n||m)&&jsxs(Fragment,{children:[jsx(Es,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(Ts,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Cs,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(ru,{message:r.message,type:r.type}),P&&B&&(t==="discover"?F?.type==="bundle"?e?.phase==="installing"?jsx(fd,{bundle:e.bundle,onComplete:gf}):jsx(rd,{itemName:B.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>pf(B.name,B.flowId),onConfirm:mf,onClose:e?.phase==="detail"?ff:$}):jsx(ed,{itemName:B.name,itemType:F?.type,onInstall:A,onClose:$}):B.type==="mcp"?jsx(ld,{itemName:B.name,itemScope:B.scope??"user",onUninstall:df,onClose:$}):jsx(sd,{itemName:B.name,itemScope:B.scope??"user",itemStatus:B.status??"enabled",updateAvailable:B.updateAvailable??false,catalogVersion:F?.version,onUninstall:U,onToggleStatus:H=>K(H),onUpdate:Ee,onClose:$})),jsx(vs,{})]})}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(ue.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 mS=3;function rp(){let e=L(c=>c.setStarterKits),t=L(c=>c.setIsLoadingStarterKits),r=L(c=>c.setStarterKitsError),n=L(c=>c.setPluginStatus),o=L(c=>c.setPluginDownloadProgress),s=L(c=>c.setStep),i=L(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await Ds();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{ue.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=L.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=mS;h++)try{await ke(m.name,{onDownloadProgress:(g,w)=>{let b=Date.now();(b-l.current>100||g>=w)&&(l.current=b,o(m.name,g,w));}}),n(m.name,"success"),f=!0;break}catch(g){if(g instanceof Ne){n(m.name,"success"),f=true;break}p=g instanceof Error?g.message:"Unknown error";}f||(n(m.name,"failed",p),v(I.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:W().interfaceType}).catch(()=>{}));}let d=_r();Rr("summary_review"),v(I.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),ue.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var ko={cursorDelta:0,confirm:false,back:false};function np(e,t){return t.upArrow?{...ko,cursorDelta:-1}:t.downArrow?{...ko,cursorDelta:1}:t.escape?{...ko,back:true}:t.return?{...ko,confirm:true}:ko}var fS={cursorDelta:0,select:false};function op(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:fS}var sp=hh.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 ol=5;function ip({onRetry:e}){let t=L(c=>c.starterKits),r=L(c=>c.selectedStarterKitIndex),n=L(c=>c.isLoadingStarterKits),o=L(c=>c.starterKitsError);if(n)return jsx(Es,{message:"Loading Starter Kits..."});if(o)return jsx(Cs,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(yn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(ol/2)),i=Math.min(t.length,s+ol);i===t.length&&(s=Math.max(0,i-ol));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(sp,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var lp=hh.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 al=8;function cp(){let e=L(c=>c.selectedStarterKit),t=L(c=>c.plugins),r=L(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,v(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(c=>c.installed).length,s=Math.max(0,r-Math.floor(al/2)),i=Math.min(t.length,s+al);i===t.length&&(s=Math.max(0,i-al));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(lp,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}var vS=["Retry failed","Continue anyway"];function up({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(md,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(Ts,{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 dp({onComplete:e,onRetry:t}){let r=L(u=>u.plugins),n=L(u=>u.step),o=L(u=>u.successCount),s=L(u=>u.failedCount),i=L(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(up,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(up,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:vS.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function pp(){let e=L(k=>k.step),t=L(k=>k.starterKits),r=L(k=>k.selectedStarterKitIndex),n=L(k=>k.setSelectedStarterKitIndex),o=L(k=>k.selectStarterKit),s=L(k=>k.plugins),i=L(k=>k.pluginCursorIndex),a=L(k=>k.setPluginCursorIndex),l=L(k=>k.setStep),u=L(k=>k.summaryActionIndex),c=L(k=>k.setSummaryActionIndex),d=L(k=>k.failedCount),m=L(k=>k.resetForRetry),p=L(k=>k.goBackToList),f=S(k=>k.setScreen),h=S(k=>k.setFocus),g=S(k=>k.focus),w=We(k=>k.setJustAuthenticated),b=We(k=>k.justAuthenticated),{loadStarterKits:_,installSelected:M}=rp(),P=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),P.current||(P.current=true,Rr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let $=useCallback(async()=>{let k=L.getState().selectedStarterKit;if(k){let z=await Z();z&&await sr({...z,starterKit:k.slug});}v(I.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:_r()}).catch(()=>{});let{successCount:j}=L.getState();v(I.CLI_ONBOARDING_COMPLETED,{duration_ms:lr(),tools_installed_count:j}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),R=useCallback(()=>{m(),M();},[m,M]),D=useCallback(()=>{_();},[_]),X=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((k,j)=>{if(j.escape)is("esc"),X();else if(j.upArrow&&r>0)n(r-1);else if(j.downArrow&&r<t.length-1)n(r+1);else if(j.return&&t.length>0){let z=_r();o(t[r]),Rr("kit_display"),v(I.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:z}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,j)=>{let z=np(k,j);if(z.cursorDelta!==0){let B=i+z.cursorDelta;B>=0&&B<s.length&&a(B);}if(z.confirm){let B=L.getState().selectedStarterKit;B&&(async()=>(await Z())?.starterKit!==B.slug&&v(I.CLI_KIT_ACCEPTED,{bundle_slug:B.slug}).catch(()=>{}))();let F=_r();Rr("kit_confirmation"),v(I.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:F}).catch(()=>{});let J=_r();Rr("tool_installation"),v(I.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:J}).catch(()=>{}),l("installing"),M();}if(z.back){let B=L.getState().selectedStarterKit;B&&v(I.CLI_KIT_REJECTED,{bundle_slug:B.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,j)=>{if(d===0)return;let z=op(k,j);if(z.cursorDelta!==0){let B=u+z.cursorDelta;B>=0&&B<=1&&c(B);}z.select&&(u===0?R():$());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(hn,{}),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."}),!b&&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(ip,{onRetry:D}),e==="starterKitDetail"&&jsx(cp,{}),(e==="installing"||e==="summary")&&jsx(dp,{onComplete:$,onRetry:R})]}),jsx(vs,{})]})}var gp=null;function hp(){return gp}async function ui(){let t=Nr().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 yp(n);(o||s)&&await ct({...r,installedVersion:o,installMethod:s});}}async function yp(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 Tt(r.type).getInstalledVersion(e);if(o)return {installedVersion:o,installMethod:r.type}}catch{}return {installedVersion:null,installMethod:null}}async function On(e){let t=await Promise.all(e.map(r=>TS(r)));return gp=t,t}async function TS(e){let t=mp(e.versionCommand);t==="permission-denied"&&(CS(e.versionCommand[0]),t=mp(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 Tt(l.type).isAvailable()?l.type:null}catch{return null}}))).filter(l=>l!==null);if(n&&!ze(e.alias)){let{installedVersion:l,installMethod:u}=await yp(e);await ct({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function mp(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 CS(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=ye__default.realpathSync(r),{mode:o}=ye__default.statSync(n);ye__default.chmodSync(n,o|73);}catch{}}function $S(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 bp(e,t){let[r,n]=useState(()=>$S(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,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 b=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),_=w.availableStrategies[(b+1)%w.availableStrategies.length];n(M=>M.map(P=>P.module.alias===w.module.alias?{...P,selectedStrategy:_}:P));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}function Ep({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}=bp(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let 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(Xe,{itemName:m,actions:d,onAction:c,onClose:u})]})}var DS=/^https?:\/\/.+/;function Pp({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&DS.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function US(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 kp(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=US(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 fr(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}function Ap({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(md,{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:u}=kp(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Fr().catch(()=>{}),n("list");let w=re().some(b=>b.name===oe);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,b)=>{b.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")),u>0&&g.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(Ap,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,b,_)=>(_>0&&w.push(jsx(Text,{children:" | "},`sep-${_}`)),w.push(b),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Dp(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(xc(p)){Fr().catch(()=>{}),l("list");let h=re().some(g=>g.name===oe);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=hp();if(p){c(p);return}On(te).then(c).catch(()=>{n([]),t("selection");});},[c]);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(Ep,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(Pp,{onConfirm:m}),e==="installation"&&jsx(Rp,{confirmedItems:o,customUrl:i})]})}var WS=x("ClaudeMdSuggestion"),zS=[`Install ${oe}`,"Skip for now"],XS=["Retry","Skip for now"];function Bp(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=L(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{v(I.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await ke(oe),o("installed");}catch(m){if(m instanceof Ne){o("installed");return}WS.warn(`Failed to install ${oe}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?XS:zS;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(hn,{}),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(Up,{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(md,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",oe,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",oe," 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:["/",oe]})]}),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 ",oe]}),jsx(Up,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Up({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 QS=promisify(execFile),gi="@ciandt-flow/cli";async function Np(){let e=le;if(Wa.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:gi};try{let t=await fetch(`https://registry.npmjs.org/${gi}/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:gi}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:gi}}}async function hi(e){try{return await QS(Nt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function ex(e){let t=ze(e.alias);if(!t?.installMethod)return t?.installedVersion??null;try{let n=await Tt(t.installMethod).getInstalledVersion(e);return n&&n!==t.installedVersion&&await ct({...t,installedVersion:n,lastChecked:new Date().toISOString()}),n??t.installedVersion}catch{return t.installedVersion}}async function Fp(e){let t=await ex(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 jp(e,t){let r=ze(e.alias);if(!r?.installMethod)return {success:false,error:"Unknown install method"};let o=await Tt(r.installMethod).update(e,t.currentVersion??"");return o.success?(await ct({...r,installedVersion:o.version??r.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:o.version}):{success:false,error:o.error?.message}}function Kp(e){let r=ze(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function Vp(){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([Np(),On(te),Promise.all(te.map(l=>Fp(l)))]);if(ui(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await hi(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=te.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await jp(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:Kp(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Fr(),t(l=>({...l,outcome:"done"}));}catch{await Fr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}function ix({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(md,{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 ax({outcome:e}){return e==="done"?jsx(Text,{color:"green",children:"All good!"}):e==="cli-updated"||e==="cli-update-failed"?jsx(Text,{color:"yellow",children:"Restart the CLI to use the new version."}):null}function Jp(){let{outcome:e,items:t}=Vp(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=re().some(i=>i.name===oe);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(ix,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(ax,{outcome:e})})]})}var dx={debug:"gray",info:"cyan",warn:"yellow",error:"red"},Hp=10;function Gp(){let[e,t]=useState(Di());useEffect(()=>Fl(()=>{t([...Di()]);}),[]);let r=e.slice(-Hp);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",Hp,") \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:dx[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var gx=x("app"),hx={auth:Lc,starterKitSetup:pp,moduleSetup:Dp,claudeMdSuggestion:Bp,verify:Jp,main:ep};function Xp(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function xs(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function qp(){v(I.CLI_SESSION_STARTED,{cli_version:le,os:process.platform,node_version:process.version,duration_ms:lr(),interface:"tui"}).catch(()=>{});}async function Zp(){let e=await Z();if(e&&wc()&&await ir()){e.customUrl&&It(e.customUrl);let{clientSecret:n,...o}=e;We.getState().setCredentials(o),qp(),xs(e);return}if(!e){Xp();return}try{e.customUrl&&It(e.customUrl),await bt();}catch(n){gx.debug(`Token validation failed: ${String(n)}`),Xp();return}qp();let{clientSecret:t,...r}=e;We.getState().setCredentials(r),xs(e);}function Qp(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=hx[r],{pendingExit:o}=cc(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(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 Sl(e,t={}){let r=cs({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return us(r),await sr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var wt=x("auth");function tm(){Ue.clearFallbackFile(),ts();}var yx=3,em=3,rm=` \u2139 The data collected during setup is used solely to improve
|
|
116
|
+
[y/N] `))return gi.debug(`[${e}] Removal cancelled by user`),C("Operation cancelled."),0}let n=t.silent?void 0:Jl({text:`Removing MCP "${y(e)}"...`}).start();try{let o=await Ce(r);return n?.stop(),o.exitCode!==0?(Uo(t,{name:e,action:"remove",message:o.stderr||"Command failed",exitCode:o.exitCode}),!t.silent&&t.verbose&&o.stdout&&C(`stdout: ${o.stdout}`),1):(hp(t,{name:e,actionPastTense:"removed",command:r,durationMs:o.duration_ms,stdout:o.stdout}),0)}catch(o){return n?.stop(),Uo(t,{name:e,action:"remove",message:q(o)}),1}}L();function Sp({selectedItem:e,selectedCatalogItem:t,items:r,closeMenu:n,clampIndex:o,notify:s}){let i=x("pluginHandlers"),a=useRef(0),l=S(P=>P.setLoading),u=S(P=>P.setDownloadProgress),{install:c,uninstall:d,toggle:m,update:p}=fp(),f=async(P,$,_)=>{l(true,P),n();try{await $(),o(r.length),s(_,"success");}catch(O){let Q=O instanceof Error?O.message:"Something went wrong";i.error(`[withLoading] ${P} failed: ${Q}`),s(Q,"error");}finally{l(false);}};return {handleInstall:(P,$)=>{e&&t&&(a.current=0,f(`Installing ${e.name}...`,()=>c(t,{scope:P,...$!==void 0?{providerId:$}:{},onDownloadProgress:(_,O)=>{let Q=Date.now();(Q-a.current>100||_>=O)&&(a.current=Q,u(_,O));}}),"\u2713 Installed successfully"));},handleUninstall:P=>{e&&f(`Uninstalling ${e.name}...`,()=>d(e.name,P),"\u2713 Uninstalled");},handleToggleStatus:P=>{if(!e)return;let $=e.status==="enabled";f($?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,P),$?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let P=t?` to v${t.version}`:"";(async()=>{l(true,`Updating ${e.name}${P}...`),n();try{await p(e.name),o(r.length),s(`\u2713 Updated ${e.name}${P}`,"success");}catch(_){if(_ instanceof vr)s(_.message,"info");else {let O=_ instanceof Error?_.message:"Something went wrong";i.error(`[handleUpdate] ${e.name} failed: ${O}`),s(O,"error");}}finally{l(false);}})();},handleBatchUpdate:P=>{if(P.length===0)return;let $=P.length;(async()=>{l(true,`Updating ${$} plugin${$>1?"s":""}...`),n();try{let O=[];for(let J of P)O.push(await p(J.name).then(()=>({status:"fulfilled",value:void 0}),Z=>({status:"rejected",reason:Z})));let Q=O.filter(J=>J.status==="fulfilled").length,k=O.map((J,Z)=>J.status==="rejected"?P[Z].name:null).filter(J=>J!==null);o(r.length),k.length===0?s(`\u2713 Updated ${Q}/${$} plugin${$>1?"s":""}`,"success"):(i.error(`[handleBatchUpdate] failed: ${k.join(", ")}`),s(`Updated ${Q}/${$}; failed: ${k.join(", ")}`,Q>0?"info":"error"));}finally{l(false);}})();},handleMcpConfigUninstall:P=>{e&&f(`Removing MCP ${e.name}...`,async()=>{let $=yl(e.name,P),_=await Ce($);if(_.exitCode!==0)throw new Error(_.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}So();L();var Bo=x("api:bundle"),Hn=class extends Error{constructor(t){super(`Bundle '${t}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},No=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},_S=/^[a-zA-Z0-9_-]{1,128}$/;async function Ip(e,t){if(e instanceof HTTPError){let r=e.response.status;throw Bo.error(`HTTP error fetching bundle '${t}' [status=${r}]`),r===StatusCodes.NOT_FOUND?new Hn(t):r===StatusCodes.INTERNAL_SERVER_ERROR?new No:new Error(`Server error (${r}) \u2014 please try again later.`)}throw Bo.error(`Unexpected error fetching bundle '${t}': ${e instanceof Error?e.message:String(e)}`),e}async function bp(e){if(!_S.test(e))throw new Error("Invalid bundle identifier format.");let t=encodeURIComponent(e);Bo.debug(`Fetching bundle by flowId "${e}"`);try{return await Gt().get(`v1/use-cases/${t}`).json()}catch(r){return Ip(r,e)}}async function hi(e){let t=encodeURIComponent(e);Bo.debug(`Fetching bundle by name "${e}"`);let r;try{r=await Gt().get(`v1/use-cases/by-name/${t}`).json(),Bo.debug(`API returned ${r.length} result(s) for "${e}"`);}catch(n){return Ip(n,e)}if(r.length===0)throw new Hn(e);return r[0]}L();var DS=x("tui:bundle-flow");function vp({closeMenu:e,notify:t}){let r=S(a=>a.bundleInstallFlow);return {handleBundleInstallStart:(a,l)=>{let{setLoading:u,setBundleInstallFlow:c}=S.getState(),d=l?.trim();DS.debug(`Starting bundle install: itemName="${a}" flowId="${d??"none"}"`),u(true,"Loading bundle..."),(d?bp(d):hi(a)).then(p=>{u(false),S.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{u(false),t(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!r||r.phase!=="detail")return;let{setBundleInstallFlow:a,setFocus:l}=S.getState();a({phase:"installing",bundle:r.bundle}),l("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:a}=S.getState();a(null),e();},handleBundleInstallComplete:a=>{S.getState().setBundleInstallFlow(null),e(),fe.getState().loadFromDisk(),t(`\u2713 Installed ${a.installed} of ${a.total} artifacts`,"success");}}}V();K();var Fo=["local","project","user"],OS=new Set(["--transport","--scope","-s"]);function Ep(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(OS.has(o))n+=2;else if(o.startsWith("-"))n+=1;else return o.replace(/^["']|["']$/g,"")}return null}function tn(e,t){return t?`${e}::${t}`:e}function wl(e){return e===ee?Yn:sn}function Pp(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??Yn,flowId:e.flowId}}function Sl(e,t){let r=wl(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 Tp(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 Fo.filter(r=>t.has(r)).map(r=>({scope:r,label:Zn[r].label,pathHint:Zn[r].pathHint,items:t.get(r)??[]}))}function Cp(e){let t=r=>{if(!r)return 1/0;let n=Fo.indexOf(r);return n===-1?1/0:n};return [...e].sort((r,n)=>t(r.scope)-t(n.scope))}function kp({catalog:e,installedItems:t,activeTab:r,catalogFilters:n,searchQuery:o}){let s=useMemo(()=>new Set(t.map(f=>tn(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=>[tn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return t.map(g=>{let w=f.get(tn(g.name,g.author?.name))??h.get(g.name),b=w?.version,D=!!b&&!!g.version&&Oe(g.version,b);return {...g,updateAvailable:D,catalogItem:w}})},[t,e]),l=useMemo(()=>r==="discover"?e.filter(f=>{if(s.has(tn(f.name,f.author?.name)))return false;if(f.type==="mcp"){let h=f.installCommand?Ep(f.installCommand)?.toLowerCase():null;if(i.has(f.name.toLowerCase())||h&&i.has(h))return false}return true}).map(f=>Pp(f)):r==="updates"?a.filter(f=>f.updateAvailable).map(f=>Sl(f,f.catalogItem)):a.map(f=>Sl(f,f.catalogItem)),[r,e,s,i,a]),u=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]),c=useMemo(()=>{let{types:f}=n;if(f.size===1){if(f.has("skill"))return "skills";if(f.has("mcp"))return "MCPs";if(f.has("bundle"))return "bundles"}return "items"},[n]),d=useMemo(()=>r==="installed"?o?`No ${c} found for '${o}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:r==="updates"?o?`No ${c} found for '${o}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":o?`No ${c} found for '${o}'`:`No ${c} available in the catalog`,[r,o,c]),m=useMemo(()=>{let f=new Map(e.map(g=>[tn(g.name,g.author?.name),g])),h=new Map(e.map(g=>[g.name,g]));return g=>g?f.get(tn(g.name,g.authorName))??h.get(g.name)??null:null},[e]),p=useMemo(()=>a.filter(f=>f.updateAvailable).length,[a]);return {items:u,emptyMessage:d,getSelectedCatalogItem:m,outdatedCount:p}}function xl(){let[e,t]=useState([]),[r,n]=useState(true),[o,s]=useState(null),[i,a]=useState(null),l=useRef(false),u=S(d=>d.catalogVersion),c=useCallback(async()=>{n(true),s(null),a(null);try{let{items:d,failures:m}=await td();if(t(d),m.length>0){let p=m.map(f=>f.adapterName).join(", ");a(`Some catalogs failed to load: ${p}`);}l.current||(l.current=!0,v(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(()=>{c();},[c,u]),{catalog:e,isLoading:r,error:o,partialError:i,refetch:c}}function Ap(){return {items:fe(t=>t.installedItems)}}L();var jS=x("catalog");function Lp(){let e=S(X=>X.bundleInstallFlow),t=S(X=>X.activeTab),r=S(X=>X.notification),n=S(X=>X.loading),o=S(X=>X.loadingMessage),s=S(X=>X.downloadProgress),i=S(X=>X.downloadTotal),a=S(X=>X.catalogError),l=S(X=>X.setCatalogError),u=S(X=>X.catalogFilters),c=Ve(X=>X.query),{catalog:d,isLoading:m,error:p,refetch:f}=xl(),{items:h}=Ap(),g=fe(X=>X.loadFromDisk),{items:w,emptyMessage:b,getSelectedCatalogItem:D,outdatedCount:R}=kp({catalog:d,installedItems:h,activeTab:t,catalogFilters:u,searchQuery:c}),{actionMenuOpen:P,closeMenu:$,selectedIndex:_,clampIndex:O,filteredItems:Q}=cp({listLength:w.length}),k=Q(w),J=useMemo(()=>t!=="installed"&&t!=="updates"?k:Cp(k),[t,k]),Z=useMemo(()=>t==="installed"||t==="updates"?Tp(J):[],[t,J]),N=J[_]??null,j=useMemo(()=>D(N),[D,N]),{notify:z}=dp(),{handleInstall:A,handleUninstall:B,handleToggleStatus:G,handleUpdate:Ae,handleBatchUpdate:Wo,handleMcpConfigUninstall:Kf}=Sp({selectedItem:N,selectedCatalogItem:j,items:w,closeMenu:$,clampIndex:O,notify:z}),{handleBundleInstallStart:Vf,handleBundleDetailConfirm:Jf,handleBundleDetailBack:Hf,handleBundleInstallComplete:Gf}=vp({closeMenu:$,notify:z}),Wf=useCallback(()=>Wo(J),[Wo,J]);return useEffect(()=>{g();},[]),useEffect(()=>{O(J.length);},[J.length,O]),useEffect(()=>{p&&(jS.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(En,{}),jsx(gu,{outdatedCount:R}),t==="marketplaces"&&wr()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(sp,{})}):jsx(Lu,{filteredItems:J,groups:Z,emptyMessage:b,onBatchUpdate:Wf}),(n||m)&&jsxs(Fragment,{children:[jsx(Ns,{message:n?o:"Loading catalog..."}),n&&i>0&&s>0&&jsx(Box,{paddingLeft:2,children:jsx(js,{received:s,total:i})})]}),a&&!m&&t==="discover"&&jsx(Ks,{message:a,onRetry:()=>{l(null),f();},onBack:()=>l(null)}),r&&jsx(Mu,{message:r.message,type:r.type}),P&&N&&(t==="discover"?j?.type==="bundle"?e?.phase==="installing"?jsx(Hd,{bundle:e.bundle,onComplete:Gf}):jsx(Rd,{itemName:N.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>Vf(N.name,N.flowId),onConfirm:Jf,onClose:e?.phase==="detail"?Hf:$}):jsx(Ld,{itemName:N.name,itemType:j?.type,onInstall:A,onClose:$}):N.type==="mcp"?jsx(Nd,{itemName:N.name,itemScope:N.scope??"user",onUninstall:Kf,onClose:$}):jsx(Od,{itemName:N.name,itemScope:N.scope??"user",itemStatus:N.status??"enabled",updateAvailable:N.updateAvailable??false,catalogVersion:j?.version,onUninstall:B,onToggleStatus:X=>G(X),onUpdate:Ae,onClose:$})),jsx(Bs,{})]})}var M=create((e,t)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:r=>e({starterKits:r}),setSelectedStarterKitIndex:r=>e({selectedStarterKitIndex:r}),selectStarterKit:r=>{let n=new Set(fe.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"})}));Ee();var GS=3;function Rp(){let e=M(c=>c.setStarterKits),t=M(c=>c.setIsLoadingStarterKits),r=M(c=>c.setStarterKitsError),n=M(c=>c.setPluginStatus),o=M(c=>c.setPluginDownloadProgress),s=M(c=>c.setStep),i=M(c=>c.computeSummary),a=useCallback(async()=>{t(true),r(null);try{let c=await Xs();e(c);}catch(c){r(c instanceof Error?c.message:String(c));}finally{t(false);}},[t,r,e]);useEffect(()=>{fe.getState().loadFromDisk(),a();},[a]);let l=useRef(0),u=useCallback(async()=>{let c=M.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){n(m.name,"installing"),l.current=0;let p="",f=false;for(let h=1;h<=GS;h++)try{await Re(m.name,{onDownloadProgress:(g,w)=>{let b=Date.now();(b-l.current>100||g>=w)&&(l.current=b,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),v(I.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Y().interfaceType}).catch(()=>{}));}let d=jr();Fr("summary_review"),v(I.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:d}).catch(()=>{}),fe.getState().loadFromDisk(),i(),s("summary");},[n,o,i,s]);return {loadStarterKits:a,installSelected:u}}var jo={cursorDelta:0,confirm:false,back:false};function _p(e,t){return t.upArrow?{...jo,cursorDelta:-1}:t.downArrow?{...jo,cursorDelta:1}:t.escape?{...jo,back:true}:t.return?{...jo,confirm:true}:jo}var WS={cursorDelta:0,select:false};function Dp(e,t){return t.upArrow?{cursorDelta:-1,select:false}:t.downArrow?{cursorDelta:1,select:false}:t.return?{cursorDelta:0,select:true}:WS}V();var Op=Gh.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 Cl=5;function Up({onRetry:e}){let t=M(c=>c.starterKits),r=M(c=>c.selectedStarterKitIndex),n=M(c=>c.isLoadingStarterKits),o=M(c=>c.starterKitsError);if(n)return jsx(Ns,{message:"Loading Starter Kits..."});if(o)return jsx(Ks,{message:o,onRetry:e,onBack:e});if(t.length===0)return jsx(Pn,{message:"No Starter Kits available."});let s=Math.max(0,r-Math.floor(Cl/2)),i=Math.min(t.length,s+Cl);i===t.length&&(s=Math.max(0,i-Cl));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Op,{starterKit:c,isSelected:s+d===r},c.slug)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}V();var Np=Gh.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)"})]})});V();var $l=8;function Fp(){let e=M(c=>c.selectedStarterKit),t=M(c=>c.plugins),r=M(c=>c.pluginCursorIndex),n=useRef(false);if(useEffect(()=>{e&&!n.current&&(n.current=true,v(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(c=>c.installed).length,s=Math.max(0,r-Math.floor($l/2)),i=Math.min(t.length,s+$l);i===t.length&&(s=Math.max(0,i-$l));let a=t.slice(s,i),l=s,u=t.length-i;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:y(e.name)}),jsx(Text,{dimColor:true,children:y(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[t.length," plugins to install",o>0&&` \xB7 ${o} already installed`]})}),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",l," more above"]})}),a.map((c,d)=>jsx(Np,{plugin:c,isCursor:s+d===r},c.name)),u>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",u," more below"]})})]})}V();var rx=["Retry failed","Continue anyway"];function jp({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(Jd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",s]})]}),o!==void 0&&o>0&&n!==void 0&&n>0&&jsx(Box,{paddingLeft:2,children:jsx(js,{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 Kp({onComplete:e,onRetry:t}){let r=M(u=>u.plugins),n=M(u=>u.step),o=M(u=>u.successCount),s=M(u=>u.failedCount),i=M(u=>u.summaryActionIndex),a=r.filter(u=>u.selected),l=useRef(false);return useEffect(()=>{if(n==="summary"&&s===0&&!l.current){l.current=true;let u=setTimeout(e,1500);return ()=>clearTimeout(u)}},[n,s,e]),n==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:a.map(u=>jsx(jp,{name:u.name,status:u.status,error:u.error,downloadProgress:u.downloadProgress,downloadTotal:u.downloadTotal},u.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[o>0&&jsxs(Text,{color:"green",children:["\u2713 ",o," ",o===1?"plugin":"plugins"," installed successfully"]}),s>0&&jsxs(Text,{color:"red",children:["\u2717 ",s," ",s===1?"plugin":"plugins"," failed"]})]}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:a.filter(u=>u.status==="failed").map(u=>jsx(jp,{name:u.name,status:u.status,error:u.error},u.name))}),s>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:rx.map((u,c)=>jsx(Box,{children:jsxs(Text,{bold:c===i,color:c===i?"cyan":void 0,children:[c===i?"\u203A ":" ",u]})},u))}),s===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Vp(){let e=M(k=>k.step),t=M(k=>k.starterKits),r=M(k=>k.selectedStarterKitIndex),n=M(k=>k.setSelectedStarterKitIndex),o=M(k=>k.selectStarterKit),s=M(k=>k.plugins),i=M(k=>k.pluginCursorIndex),a=M(k=>k.setPluginCursorIndex),l=M(k=>k.setStep),u=M(k=>k.summaryActionIndex),c=M(k=>k.setSummaryActionIndex),d=M(k=>k.failedCount),m=M(k=>k.resetForRetry),p=M(k=>k.goBackToList),f=S(k=>k.setScreen),h=S(k=>k.setFocus),g=S(k=>k.focus),w=Qe(k=>k.setJustAuthenticated),b=Qe(k=>k.justAuthenticated),{loadStarterKits:D,installSelected:R}=Rp(),P=useRef(false);useEffect(()=>{e==="starterKitList"?(h("starterKitList"),P.current||(P.current=true,Fr("bundle_selection"))):h(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,h]);let $=useCallback(async()=>{let k=M.getState().selectedStarterKit;if(k){let Z=await re();Z&&await pr({...Z,starterKit:k.slug});}v(I.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:jr()}).catch(()=>{});let{successCount:J}=M.getState();v(I.CLI_ONBOARDING_COMPLETED,{duration_ms:gr(),tools_installed_count:J}).catch(()=>{}),w(false),h("verify"),f("verify");},[w,h,f]),_=useCallback(()=>{m(),R();},[m,R]),O=useCallback(()=>{D();},[D]),Q=useCallback(()=>{h("verify"),f("verify");},[h,f]);return useInput((k,J)=>{if(J.escape)Is("esc"),Q();else if(J.upArrow&&r>0)n(r-1);else if(J.downArrow&&r<t.length-1)n(r+1);else if(J.return&&t.length>0){let Z=jr();o(t[r]),Fr("kit_display"),v(I.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:Z}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((k,J)=>{let Z=_p(k,J);if(Z.cursorDelta!==0){let N=i+Z.cursorDelta;N>=0&&N<s.length&&a(N);}if(Z.confirm){let N=M.getState().selectedStarterKit;N&&(async()=>(await re())?.starterKit!==N.slug&&v(I.CLI_KIT_ACCEPTED,{bundle_slug:N.slug}).catch(()=>{}))();let j=jr();Fr("kit_confirmation"),v(I.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:j}).catch(()=>{});let z=jr();Fr("tool_installation"),v(I.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:z}).catch(()=>{}),l("installing"),R();}if(Z.back){let N=M.getState().selectedStarterKit;N&&v(I.CLI_KIT_REJECTED,{bundle_slug:N.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((k,J)=>{if(d===0)return;let Z=Dp(k,J);if(Z.cursorDelta!==0){let N=u+Z.cursorDelta;N>=0&&N<=1&&c(N);}Z.select&&(u===0?_():$());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(En,{}),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."}),!b&&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(Up,{onRetry:O}),e==="starterKitDetail"&&jsx(Fp,{}),(e==="installing"||e==="summary")&&jsx(Kp,{onComplete:$,onRetry:_})]}),jsx(Bs,{})]})}K();var Gp=null;function Wp(){return Gp}async function Ei(){let t=Gr().filter(r=>r.installedVersion===null&&r.installMethod===null);for(let r of t){let n=se.find(i=>i.alias===r.alias);if(!n)continue;let{installedVersion:o,installMethod:s}=await zp(n);(o||s)&&await gt({...r,installedVersion:o,installMethod:s});}}async function zp(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 Wn(e){let t=await Promise.all(e.map(r=>sx(r)));return Gp=t,t}async function sx(e){let t=Jp(e.versionCommand);t==="permission-denied"&&(ix(e.versionCommand[0]),t=Jp(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&&!et(e.alias)){let{installedVersion:l,installMethod:u}=await zp(e);await gt({alias:e.alias,name:e.name,installedVersion:l,installMethod:u,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:n,availableStrategies:a}}function Jp(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 ix(e){if(process.platform!=="win32")try{let t=spawnSync("which",[e],{stdio:"pipe"});if(t.status!==0)return;let r=t.stdout.toString().trim(),n=Ie__default.realpathSync(r),{mode:o}=Ie__default.statSync(n);Ie__default.chmodSync(n,o|73);}catch{}}function cx(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 Qp(e,t){let[r,n]=useState(()=>cx(e)),[o,s]=useState(0),i=useRef(o);useEffect(()=>{i.current=o;},[o]);let a=useRef(r);useEffect(()=>{a.current=r;},[r]);let l=useCallback(d=>{n(m=>m.map(p=>p.module.alias!==d||p.module.required?p:{...p,checked:!p.checked}));},[]),u=useCallback((d,m)=>{n(p=>p.map(f=>f.module.alias===d?{...f,selectedStrategy:m}:f));},[]);useInput((d,m)=>{let p=i.current,f=a.current,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 b=w.availableStrategies.indexOf(w.selectedStrategy??w.availableStrategies[0]),D=w.availableStrategies[(b+1)%w.availableStrategies.length];n(R=>R.map(P=>P.module.alias===w.module.alias?{...P,selectedStrategy:D}:P));}}},{isActive:t});let c=useMemo(()=>r.filter(d=>d.checked),[r]);return {items:r,focusedIndex:o,toggle:l,setStrategy:u,confirmedItems:c}}V();function tm({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}=Qp(e,r==="moduleSetup"),u=useCallback(()=>{o(false),s("moduleSetup");},[o,s]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&t(l),u();},[l,t,u]);useInput((p,f)=>{f.return&&(o(true),s("actionMenu"));},{isActive:r==="moduleSetup"});let d=l.length>0?["Install","Cancel"]:["Skip","Cancel"],m=l.length>0?`Install ${l.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:i.map((p,f)=>{let 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(tt,{itemName:m,actions:d,onAction:c,onClose:u})]})}var fx=/^https?:\/\/.+/;function rm({onConfirm:e}){let[t,r]=useState("confirm"),[n,o]=useState(""),[s,i]=useState(false),a=useRef("");return useInput((l,u)=>{if(t==="confirm"){if(l==="y"||l==="Y"){r("input");return}if(l==="n"||l==="N"||u.return){e(null);return}}if(t==="input"){if(u.escape){a.current="",o(""),r("confirm");return}if(u.return){let c=a.current.trim();c.length>0&&fx.test(c)?(i(false),e(c)):c.length>0&&i(true);return}if(u.backspace||u.delete){a.current=a.current.slice(0,-1),o(a.current);return}l&&!u.ctrl&&!u.meta&&(a.current=a.current+l,o(a.current),i(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[t==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),t==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:n}),jsx(Text,{color:"cyan",children:"\u2588"})]}),s&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function hx(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 sm(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=hx(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 Ir(d.module,"onboarding",d.selectedStrategy,t);p.success?i(d.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):i(d.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){i(d.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}s(true);},[e,i,t]),l=useMemo(()=>r.filter(d=>d.status==="installed").length,[r]),u=useMemo(()=>r.filter(d=>d.status==="failed").length,[r]),c=useMemo(()=>r.filter(d=>d.status==="skipped").length,[r]);return {modules:r,install:a,isComplete:o,installedCount:l,failedCount:u,skippedCount:c}}K();V();function im({module:e}){let t=y(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jd,{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 um({confirmedItems:e,customUrl:t}){let r=S(w=>w.setScreen),n=S(w=>w.setFocus),{modules:o,install:s,isComplete:i,installedCount:a,failedCount:l,skippedCount:u}=sm(e,t),c=o.some(w=>w.pendingSetupCommand),d=useRef(false),m=useRef(false);useEffect(()=>{d.current||(d.current=true,s());},[s]);let p=useCallback(()=>{Wr().catch(()=>{}),n("list");let w=ie().some(b=>b.name===le);r(w?"main":"claudeMdSuggestion");},[n,r]);useEffect(()=>{if(i&&l===0&&!c&&!m.current){m.current=true;let w=setTimeout(p,1500);return ()=>clearTimeout(w)}},[i,l,c,p]),useInput((w,b)=>{b.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")),u>0&&g.push(jsxs(Text,{dimColor:true,children:[u," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:i?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:o.map(w=>jsx(im,{module:w},w.alias))}),i&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((w,b,D)=>(D>0&&w.push(jsx(Text,{children:" | "},`sep-${D}`)),w.push(b),w),[])}),jsx(Box,{paddingX:1,children:l>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function pm(){let[e,t]=useState("loading"),[r,n]=useState([]),[o,s]=useState([]),[i,a]=useState(null),l=S(p=>p.setFocus),u=S(p=>p.setScreen),c=useCallback(p=>{if(qc(p)){Wr().catch(()=>{}),l("list");let h=ie().some(g=>g.name===le);u(h?"main":"claudeMdSuggestion");}else n(p),t("selection");},[l,u]);useEffect(()=>{let p=Wp();if(p){c(p);return}Wn(se).then(c).catch(()=>{n([]),t("selection");});},[c]);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(tm,{probeResults:r,onConfirm:d}),e==="customUrl"&&jsx(rm,{onConfirm:m}),e==="installation"&&jsx(um,{confirmedItems:o,customUrl:i})]})}K();L();var Tx=x("ClaudeMdSuggestion"),Cx=[`Install ${le}`,"Skip for now"],kx=["Retry","Skip for now"];function gm(){let e=S(m=>m.setScreen),t=S(m=>m.setFocus),r=M(m=>m.successCount),[n,o]=useState("prompt"),[s,i]=useState(0),a=useRef(0),l=useCallback(()=>{t("list"),e("main");},[t,e]),u=useCallback(()=>{v(I.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),l();},[l]),c=useCallback(async()=>{a.current+=1,v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:a.current}).catch(()=>{}),o("installing");try{await Re(le),o("installed");}catch(m){if(m instanceof Je){o("installed");return}Tx.warn(`Failed to install ${le}: ${m instanceof Error?m.message:m}`),o("error");}},[]),d=n==="error"?kx:Cx;return useInput((m,p)=>{if(p.escape){n==="prompt"||n==="error"?u():n==="installed"&&l();return}if(n==="prompt"||n==="error"){p.upArrow&&s>0?i(s-1):p.downArrow&&s<d.length-1?i(s+1):p.return&&(s===0?(i(0),c()):u());return}n==="installed"&&p.return&&l();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(En,{}),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(fm,{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(Jd,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",le,"..."]})]}),n==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",le," 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:["/",le]})]}),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 ",le]}),jsx(fm,{options:d,cursorIndex:s}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function fm({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 Mx=promisify(execFile),Ai="@ciandt-flow/cli";async function hm(){let e=me;if(hl.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ai};try{let t=await fetch(`https://registry.npmjs.org/${Ai}/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:Ai}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Ai}}}async function $i(e){try{return await Mx(Jt(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(t){return {success:false,error:String(t)}}}async function Rx(e){let t=et(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 ym(e){let t=await Rx(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 wm(e,t){let r=et(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 Sm(e){let r=et(e.alias)?.installMethod,n=e.platforms[process.platform];if(n?.status==="supported"){if(r==="npm"){let o=n.strategies.find(s=>s.type==="npm");if(o?.type==="npm")return `npm install -g ${o.package}`}if(r==="homebrew"){let o=n.strategies.find(s=>s.type==="homebrew");if(o?.type==="homebrew")return `brew upgrade ${o.formula}`}}}function xm(){let[e,t]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...se.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([hm(),Wn(se),Promise.all(se.map(l=>ym(l)))]);if(Ei(),o.isOutdated){r("cli",{status:"updating",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),(await $i(o)).success?(r("cli",{status:"updated",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`}),t(u=>({...u,outcome:"cli-updated"}))):(r("cli",{status:"error",detail:`v${o.currentVersion} \u2192 v${o.latestVersion}`,manualCommand:`npm install -g ${o.packageName}`}),t(u=>({...u,outcome:"cli-update-failed"})));return}r("cli",{status:"ok",detail:`v${o.currentVersion}`});let a=s.some(l=>!l.alreadyInstalled);for(let l of s)l.alreadyInstalled||r(l.module.alias,{status:"missing"});if(a){t(l=>({...l,outcome:"module-missing"}));return}for(let l of i){let u=se.find(d=>d.alias===l.moduleAlias);if(!u)continue;if(!l.isOutdated){r(l.moduleAlias,{status:"ok",detail:l.currentVersion?`v${l.currentVersion}`:void 0});continue}r(l.moduleAlias,{status:"updating",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`});let c=await wm(u,l);c.success?r(l.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):r(l.moduleAlias,{status:"error",detail:`v${l.currentVersion} \u2192 v${l.latestVersion}`,manualCommand:Sm(u)});}t(l=>({...l,items:l.items.map(u=>u.status==="pending"?{...u,status:"ok"}:u)})),await Wr(),t(l=>({...l,outcome:"done"}));}catch{await Wr(),t(o=>({...o,outcome:"done"}));}}n();},[r]),e}K();function Nx({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(Jd,{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 Fx({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 Im(){let{outcome:e,items:t}=xm(),r=S(o=>o.setScreen),n=S(o=>o.setFocus);return useEffect(()=>{if(e==="done"){let o=setTimeout(()=>{let s=ie().some(i=>i.name===le);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(Nx,{item:o},o.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(Fx,{outcome:e})})]})}Ee();Sn();L();Yi();var Jx={debug:"gray",info:"cyan",warn:"yellow",error:"red"},bm=10;function vm(){let[e,t]=useState(qi());useEffect(()=>mc(()=>{t([...qi()]);}),[]);let r=e.slice(-bm);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",bm,") \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:Jx[n.level],children:["[",n.level.toUpperCase(),"] [",n.module,"] ",n.message]},o))]})}var zx=x("app"),Xx={auth:au,starterKitSetup:Vp,moduleSetup:pm,claudeMdSuggestion:gm,verify:Im,main:Lp};function Tm(){let{setScreen:e,setFocus:t}=S.getState();e("auth"),t("auth");}function Ds(e){let{setScreen:t,setFocus:r}=S.getState();!e.starterKit||e.starterKit.trim()===""?(t("starterKitSetup"),r("starterKitList")):(t("verify"),r("verify"));}function Cm(){v(I.CLI_SESSION_STARTED,{cli_version:me,os:process.platform,node_version:process.version,duration_ms:gr(),interface:"tui"}).catch(()=>{});}async function Am(){let e=await re();if(e&&zc()&&await mr()){e.customUrl&&Tt(e.customUrl);let{clientSecret:n,...o}=e;Qe.getState().setCredentials(o),Cm(),Ds(e);return}if(!e){Tm();return}try{e.customUrl&&Tt(e.customUrl),await Ct();}catch(n){zx.debug(`Token validation failed: ${String(n)}`),Tm();return}Cm();let{clientSecret:t,...r}=e;Qe.getState().setCredentials(r),Ds(e);}function $m(){let{columns:e,rows:t}=useWindowSize(),r=S(a=>a.screen),n=Xx[r],{pendingExit:o}=Nc(),s=S(a=>a.debugPanelOpen),i=!!process.env.DEBUG;return useInput((a,l)=>{if(i&&l.ctrl&&a==="d"){let u=S.getState().debugPanelOpen;S.getState().setDebugPanelOpen(!u);}}),n?jsxs(Box,{flexDirection:"column",width:e,height:t,children:[jsx(n,{}),i&&s&&jsx(vm,{}),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]})}Ee();Ss();V();K();L();no();Ee();async function Kl(e,t={}){let r=Es({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},t);return Ps(r),await pr(e),{jwt:r.jwt,anthropicBaseUrl:r.anthropicBaseUrl,previousToken:r.previousToken,previousBaseUrl:r.previousBaseUrl,hadExistingFile:r.hadExistingFile}}var vt=x("auth");function Mm(){Ke.clearFallbackFile(),fs();}var qx=3,Lm=3,Rm=` \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 sr(e,t={}){return new Promise((r,n)=>{let{masked:o=false,defaultValue:s=""}=t;process.stdout.write(e+s);let i=s,a=c=>{if(c===""){l(),n(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
119
119
|
`){l(),process.stdout.write(`
|
|
120
|
-
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function
|
|
120
|
+
`),r(i);return}if(c==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(i+=c,process.stdout.write(o?"*".repeat(c.length):c));};function l(){process.stdin.setRawMode(false),process.stdin.removeListener("data",a),process.removeListener("uncaughtException",u),process.removeListener("unhandledRejection",u),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u);}function u(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",u),process.on("unhandledRejection",u),process.on("SIGINT",u),process.on("SIGTERM",u),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",a);})}async function Yx(){let e=Jr();return process.stdout.write(`
|
|
121
121
|
`+T.yellow(" \u26A0 ")+`${y(e)} contains invalid JSON.
|
|
122
|
-
`),(await
|
|
123
|
-
`));}}async function
|
|
124
|
-
`));}}async function
|
|
122
|
+
`),(await sr(T.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function _m(e,t,r){try{await Kl(e,{jwtOverride:r});return}catch(n){if(!(n instanceof Hr))throw n;if(!t)throw new Error(`${n.message}. Fix or remove ${Jr()} and retry.`);if(!await Yx())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await Kl(e,{allowOverwriteMalformed:true,jwtOverride:r});}}async function Zx(){if((await sr(T.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let t=(await sr(T.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(ln.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${cn}. Try again.
|
|
123
|
+
`));}}async function Qx(){let e=(await sr(T.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let t=(await sr(T.cyan(" ? ")+"Enter your email address: ")).trim();if(un.test(t))return t;process.stderr.write(T.yellow(` \u26A0 ${dn}. Try again.
|
|
124
|
+
`));}}async function Dm(e,t){process.stdout.write(T.dim(" Installing flow-ai-obs..."));let{npmFailed:r,initFailed:n,unexpectedError:o}=await _s(e,t);return r?process.stdout.write(T.yellow(` \u26A0 npm install failed. Please contact Flow support.
|
|
125
125
|
`)):o?process.stdout.write(T.yellow(` \u26A0 Unexpected error. Please contact Flow support.
|
|
126
126
|
`)):n?process.stdout.write(T.yellow(`
|
|
127
127
|
\u26A0 flow-ai-obs could not be initialized \u2014 domain authentication failure. Please contact support.
|
|
128
128
|
`)):process.stdout.write(T.green(` done
|
|
129
|
-
`)),{initFailed:n}}async function
|
|
129
|
+
`)),{initFailed:n}}async function Om(){for(let e=1;e<=Lm;e++)try{return await Xs()}catch{if(e===Lm)throw new Error("Failed to fetch starter kits after 3 attempts")}return []}async function Um(){let e=await Om();if(e.length===0)throw new Error("No starter kits available. Please contact your administrator.");for(process.stdout.write(`
|
|
130
130
|
`+T.cyan(" ? ")+`Starter Kit:
|
|
131
131
|
`),e.forEach((t,r)=>{process.stdout.write(` ${T.cyan(`${r+1})`)} ${y(t.name)}
|
|
132
132
|
`);}),process.stdout.write(`
|
|
133
|
-
`);;){let t=(await
|
|
134
|
-
`));}}async function
|
|
133
|
+
`);;){let t=(await sr(T.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(T.yellow(` \u26A0 Invalid selection. Please try again.
|
|
134
|
+
`));}}async function Bm(e){if(e.plugins.length===0)return process.stdout.write(T.dim(`
|
|
135
135
|
Starter kit '${y(e.name)}' has no plugins to install.
|
|
136
136
|
`)),true;process.stdout.write(`
|
|
137
137
|
Installing ${e.plugins.length} plugins from '${y(e.name)}'...
|
|
138
|
-
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=
|
|
138
|
+
`);let t=0,r=0,n=e.plugins.length;for(let o of e.plugins){let s=t+r+1;process.stdout.write(T.dim(` [${s}/${n}] Installing ${y(o)}...`));let i=false;for(let a=1;a<=qx;a++)try{await Re(o),t++,i=!0;break}catch(l){if(l instanceof Je){t++,i=true;break}}i?process.stdout.write(T.green(` done
|
|
139
139
|
`)):(r++,process.stdout.write(T.red(` failed
|
|
140
140
|
`)));}return r===0?process.stdout.write(T.green(` \u2713 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed successfully.
|
|
141
141
|
`)):process.stdout.write(T.yellow(` \u26A0 Starter kit '${y(e.name)}' selected. ${t}/${n} plugins installed. ${r} failed.
|
|
142
|
-
`)),r===0}async function
|
|
142
|
+
`)),r===0}async function Nm(){process.stdout.write(`
|
|
143
143
|
`),process.stdout.write(T.bold(` Personalize your Claude Code
|
|
144
144
|
`)),process.stdout.write(T.dim(` This plugin helps Claude understand your preferences and work style.
|
|
145
145
|
|
|
146
|
-
`));let e=(await
|
|
146
|
+
`));let e=(await sr(T.cyan(" ? ")+`Install ${le}? (Y/n): `)).trim();if(e!==""&&e.toLowerCase()!=="y"){v(I.CLI_CLAUDE_MD_SKIPPED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(`
|
|
147
147
|
You can always install it later from the catalog.
|
|
148
|
-
`));return}v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${
|
|
149
|
-
`));}catch(t){if(t instanceof
|
|
150
|
-
`));else {
|
|
148
|
+
`));return}v(I.CLI_CLAUDE_MD_ACCEPTED,{interface:"cli"}).catch(()=>{}),process.stdout.write(T.dim(` Installing ${le}...`));try{await Re(le),process.stdout.write(T.green(` done
|
|
149
|
+
`));}catch(t){if(t instanceof Je)process.stdout.write(T.green(` already installed
|
|
150
|
+
`));else {vt.warn(`Failed to install ${le}: ${t instanceof Error?t.message:t}`),process.stdout.write(T.red(` failed
|
|
151
151
|
`)),process.stdout.write(T.dim(` You can install it later from the catalog.
|
|
152
152
|
`));return}}process.stdout.write(`
|
|
153
153
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
154
|
-
`),process.stdout.write(T.cyan.bold(` /${
|
|
154
|
+
`),process.stdout.write(T.cyan.bold(` /${le}
|
|
155
155
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
156
|
-
`);}async function
|
|
157
|
-
`+
|
|
158
|
-
`),e.customUrl!==void 0&&!
|
|
159
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
160
|
-
`)),1;let t=e.jwt.trim(),r;try{r=
|
|
161
|
-
`)),1}e.customUrl&&
|
|
162
|
-
`)),1}let{initFailed:n}=await
|
|
156
|
+
`);}async function eI(e){if(Mm(),process.stdout.write(`
|
|
157
|
+
`+Rm+`
|
|
158
|
+
`),e.customUrl!==void 0&&!ln.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${cn}.
|
|
159
|
+
`)),1;if(e.customEmail!==void 0&&!un.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${dn}.
|
|
160
|
+
`)),1;let t=e.jwt.trim(),r;try{r=fo(t);}catch(o){let s=y(o instanceof Error?o.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${s}
|
|
161
|
+
`)),1}e.customUrl&&Tt(e.customUrl),vt.debug(`[${r.tenant}] Authenticating tenant via JWT`);try{await Nr(r);}catch(o){let s=y(o instanceof Error?o.message:"unknown error");return vt.error(`[${r.tenant}] Authentication failed: ${s}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${s}
|
|
162
|
+
`)),1}let{initFailed:n}=await Dm(e.customUrl??null,e.customEmail??null);try{let o;if(e.starterKit){let s=await Om(),i=s.find(a=>a.slug===e.starterKit);if(!i){process.stderr.write(T.red(` \u2717 Starter kit '${y(e.starterKit)}' not found.
|
|
163
163
|
`)),process.stderr.write(` Available starter kits:
|
|
164
164
|
`);for(let a of s)process.stderr.write(` - ${y(a.slug)} (${y(a.name)})
|
|
165
|
-
`);return 1}o=i;}else o=await
|
|
166
|
-
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${
|
|
165
|
+
`);return 1}o=i;}else o=await Um();return await _m({...r,starterKit:o.slug,customUrl:e.customUrl},!1,t),await Bm(o),await Nm(),vt.info(`[${r.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
166
|
+
\u2713 Setup complete. Tenant: ${y(r.tenant)}. JWT written to ${Jr()}.
|
|
167
167
|
|
|
168
168
|
`)),n&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
169
|
-
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return
|
|
170
|
-
`)),1}}async function
|
|
171
|
-
`),process.stdout.write(
|
|
172
|
-
`);let r=(await
|
|
173
|
-
`)),1;let n;try{n=
|
|
174
|
-
`)),1}let o=e??await
|
|
175
|
-
`)),1}let{initFailed:i}=await
|
|
176
|
-
\u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${
|
|
169
|
+
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let s=y(o instanceof Error?o.message:"unknown error");return vt.error(`[${r.tenant}] Starter kit setup failed: ${s}`),process.stderr.write(T.red(` \u2717 Starter kit setup failed: ${s}
|
|
170
|
+
`)),1}}async function tI(e,t){Mm(),vt.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
171
|
+
`),process.stdout.write(Rm+`
|
|
172
|
+
`);let r=(await sr(T.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!r)return vt.error("[auth] Validation failed: JWT is required"),process.stderr.write(T.red(` \u2717 JWT is required
|
|
173
|
+
`)),1;let n;try{n=fo(r);}catch(l){let u=y(l instanceof Error?l.message:"Invalid JWT");return process.stderr.write(T.red(` \u2717 ${u}
|
|
174
|
+
`)),1}let o=e??await Zx(),s=t??await Qx();o&&Tt(o),vt.debug(`[${n.tenant}] Authenticating tenant`);try{await Nr(n);}catch(l){let u=y(l instanceof Error?l.message:"unknown error");return vt.error(`[${n.tenant}] Authentication failed: ${u}`),process.stderr.write(T.red(` \u2717 Authentication failed: ${u}
|
|
175
|
+
`)),1}let{initFailed:i}=await Dm(o,s),a=await Um();return await _m({...n,starterKit:a.slug,customUrl:o??void 0},!0,r),await Bm(a),await Nm(),vt.info(`[${n.tenant}] Authentication successful`),process.stdout.write(T.green(`
|
|
176
|
+
\u2713 Setup complete. Tenant: ${y(n.tenant)}. JWT written to ${Jr()}.
|
|
177
177
|
|
|
178
178
|
`)),i&&process.stdout.write(T.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
179
|
-
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return
|
|
180
|
-
`)),1}}async function
|
|
181
|
-
`)),1;if(e.customEmail!==void 0&&!
|
|
182
|
-
`)),1;try{return await
|
|
183
|
-
`),130;throw t}}async function
|
|
184
|
-
`),(await
|
|
179
|
+
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let n=y(r instanceof Error?r.message:"unknown error");return vt.error(`[auth] Unexpected error: ${n}`),process.stderr.write(T.red(` \u2717 Unexpected error: ${n}
|
|
180
|
+
`)),1}}async function Vl(e={}){if(e.jwt)return eI({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!ln.test(e.customUrl))return process.stderr.write(T.red(` \u2717 ${cn}.
|
|
181
|
+
`)),1;if(e.customEmail!==void 0&&!un.test(e.customEmail))return process.stderr.write(T.red(` \u2717 ${dn}.
|
|
182
|
+
`)),1;try{return await tI(e.customUrl,e.customEmail)}catch(t){if(t instanceof Error&&t.message==="SIGINT")return process.stdout.write(`
|
|
183
|
+
`),130;throw t}}async function rI(){try{return process.stdout.write(`
|
|
184
|
+
`),(await sr(T.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(T.yellow(` \u26A0 Logout cancelled
|
|
185
185
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
186
|
-
`),130;throw e}}async function
|
|
187
|
-
`)),0;if(!e){let t=await
|
|
186
|
+
`),130;throw e}}async function Fm(e){if(!await re())return process.stdout.write(T.yellow(` \u26A0 You are not authenticated
|
|
187
|
+
`)),0;if(!e){let t=await rI();if(t!==null)return t}try{return await Pc(),process.stdout.write(T.green(` \u2713 Credentials removed successfully
|
|
188
188
|
`)),0}catch{return process.stderr.write(T.red(` \u2717 Error removing credentials
|
|
189
|
-
`)),1}}async function
|
|
189
|
+
`)),1}}async function jm(){let e=await re();return e?await mr()?(process.stdout.write(`
|
|
190
190
|
`+T.bold(` Authenticated
|
|
191
191
|
`)),process.stdout.write(T.dim(" Tenant: ")+y(e.tenant)+`
|
|
192
192
|
`),process.stdout.write(T.dim(" Client ID: ")+y(e.clientId)+`
|
|
193
193
|
`),process.stdout.write(T.dim(" Starter Kit: ")+y(e.starterKit??"not set")+`
|
|
194
|
-
`),process.stdout.write(T.dim(" Config: ")+y(await
|
|
194
|
+
`),process.stdout.write(T.dim(" Config: ")+y(await Tc())+`
|
|
195
195
|
`),process.stdout.write(`
|
|
196
|
-
`),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}async function
|
|
196
|
+
`),0):(process.stdout.write(T.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(T.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}V();K();async function nI(e){let t=ie(),r;try{r=await zt(e.source);}catch(o){if(e.source)throw o;r=[];}let n=new Set(t.map(o=>o.name));return v(I.CLI_CATALOG_VIEWED,{interface:Y().interfaceType,filter_type:"available",result_count:r.length}).catch(()=>{}),e.json?(cr(r.map(o=>({...o,installed:n.has(o.name)}))),0):(gn(["","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 oI(e){let t=ie(),r=await zt(e.source),n=new Map(r.map(s=>[s.name,s])),o=t.map(s=>{let i=n.get(s.name);return i&&s.version&&i.version&&Oe(s.version,i.version)?{...s,availableVersion:i.version}:null}).filter(s=>s!==null);return v(I.CLI_CATALOG_VIEWED,{interface:Y().interfaceType,filter_type:"outdated",result_count:o.length}).catch(()=>{}),o.length===0?(C("All plugins are up to date."),0):e.json?(cr(o),0):(gn(["Name","Installed","Available"],o.map(s=>[s.name??"",s.version??"n/a",s.availableVersion??"n/a"])),process.stdout.write(`
|
|
197
197
|
${o.length} plugin(s) outdated.
|
|
198
|
-
`),0)}async function
|
|
198
|
+
`),0)}async function sI(e){let t=ie();if(v(I.CLI_CATALOG_VIEWED,{interface:Y().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 cr(t),0;let r=[];try{r=await zt(e.source);}catch{r=[];}let n=new Map(r.map(s=>[s.name,s])),o=[...t].sort((s,i)=>{let a=Fo.indexOf(s.scope??"user"),l=Fo.indexOf(i.scope??"user");return (a===-1?1/0:a)-(l===-1?1/0:l)});return gn(["Name","Version","Type","Origin","Scope","Status","Installed at"],o.map(s=>{let i=n.get(s.name),a=i?.type??"bundle",l=i?.origin??wl(s.marketplace);return [s.name??"",s.version??"n/a",an[a]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",Pt(s.installedAt??"")]})),process.stdout.write(`
|
|
199
199
|
${t.length} plugin(s) installed.
|
|
200
|
-
`),0}async function
|
|
200
|
+
`),0}async function Km(e){if(!await de())return 1;try{return e.available?await nI(e):e.outdated?await oI(e):await sI(e)}catch(t){return E(t instanceof Error?t.message:"Failed to list plugins."),1}}Er();V();K();L();var pe=x("manage");function Mi(e,t){return t?ie().find(r=>r.name===e&&r.scope===t):ie().find(r=>r.name===e)}function iI(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=Jl({text:`${e}${o}`}).start();}},stopSpinner:()=>{r?.stop(),r=void 0;}}}async function aI(e,t,r,n){let o=n;if(!r.force){o?.stop();let i=y(e),a=y(Ln(e,r.scope));if(!await Rt(`${t}Install external plugin "${i}"?
|
|
201
201
|
This will run: ${a}
|
|
202
|
-
[y/N] `))return
|
|
203
|
-
Installation summary: ${t} succeeded, ${r} failed`);}async function
|
|
204
|
-
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function
|
|
202
|
+
[y/N] `))return pe.debug(`[${e}] Installation cancelled by user`),r.silent||C(`${t}Skipped ${e} (cancelled).`),{name:e,success:true};r.silent||(o=Jl({text:`${t}Installing ${e}...`}).start());}let s=o?iI(t,o):void 0;try{let i=await pp(e,r.marketplaceSource,s?.callbacks,r.scope);if(s?.stopSpinner(),i.exitCode!==0){let a=i.stderr||"Command failed";return r.silent?Ze({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:!1,error:a}}return r.silent?je({status:"success",plugin:e,command:i.command,duration_ms:i.duration_ms}):ce(`${t}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:i.duration_ms}}catch(i){s?.stopSpinner();let a=q(i);return r.silent?Ze({status:"error",plugin:e,message:a}):E(`${t}Failed to install "${e}": ${a}`),{name:e,success:false,error:a}}}async function lI(e,t,r){let n=r.silent?void 0:Jl({text:`${t}Installing ${e}...`}).start();if(An(e))return aI(e,t,r,n);try{let o=await Re(e,{...r,onDownloadProgress:r.silent?void 0:(s,i)=>{if(!n||i===0)return;let{bar:a,percent:l,label:u}=Fs(s,i);n.text=`${t}Downloading ${e}... ${a} ${l}% (${u})`;}});return n?.stop(),r.silent?je({status:"success",plugin:e,version:o.version,duration_ms:o.duration_ms}):ce(`${t}${e} v${o.version} installed successfully`),{name:e,success:!0,version:o.version,duration_ms:o.duration_ms}}catch(o){if(n?.stop(),o instanceof Je)return r.silent?je({status:"already_installed",plugin:e,message:o.message}):C(`${t}${o.message}`),{name:e,success:true};let s=q(o);return r.silent?Ze({status:"error",plugin:e,message:s}):E(`${t}Failed to install "${e}": ${s}`),{name:e,success:false,error:s}}}function cI(e){let t=e.filter(n=>n.success).length,r=e.filter(n=>!n.success).length;C(`
|
|
203
|
+
Installation summary: ${t} succeeded, ${r} failed`);}async function uI(e,t){let r=new Map;if(t.source){for(let n of e)r.set(n,t.source);return r}try{let n=await zt();for(let o of e){let i=n.filter(a=>a.name===o).find(a=>a.contentSource);i?.contentSource&&r.set(o,i.contentSource);}}catch{}return r}async function Ri(e,t={}){if(!await de())return 1;let r=[],n=await uI(e,t);for(let o=0;o<e.length;o++){let s=e.length>1?`[${o+1}/${e.length}] `:"",i=e[o],a=n.get(i)??t.source,l=await lI(i,s,{...t,source:a});r.push(l);}return e.length>1&&(t.silent?je({status:"summary",succeeded:r.filter(o=>o.success).length,failed:r.filter(o=>!o.success).length,results:r.map(o=>({plugin:o.name,success:o.success,...o.error?{error:o.error}:{}}))}):cI(r)),r.some(o=>!o.success)?1:0}async function Vm(e,t){if(!await de())return 1;if(pe.debug(`[${e}] Looking up installed plugin`),!t.force){let r=Mi(e,t.scope);if(!r)return pe.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 Rt(`Remove ${n} ${o?`v${o}`:"(n/a)"}${s}? [y/N] `))return pe.debug(`[${e}] Uninstall cancelled by user`),C("Operation cancelled."),0}try{return pe.debug(`[${e}] Uninstalling plugin${t.scope?` (scope: ${t.scope})`:""}`),await Eo(e,t.scope),pe.info(`[${e}] Uninstalled successfully`),ce("Plugin removed successfully"),0}catch(r){return pe.error(`[${e}] Failed to uninstall: ${q(r)}`),E(q(r)),1}}async function Jm(e,t={}){if(!await de())return 1;pe.debug(`[${e}] Looking up installed plugin`);let r=Mi(e,t.scope);if(!r)return pe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="enabled")return pe.debug(`[${e}] Already enabled, skipping`),C(`${r.name} is already enabled`),0;try{return pe.debug(`[${e}] Enabling plugin (current status: ${r.status})`),await Po(e,"enabled",t.scope),pe.info(`[${e}] Enabled successfully`),ce(`${r.name} enabled successfully`),0}catch(n){return pe.error(`[${e}] Failed to enable: ${q(n)}`),E(q(n)),1}}async function Hm(e,t={}){if(!await de())return 1;pe.debug(`[${e}] Looking up installed plugin`);let r=Mi(e,t.scope);if(!r)return pe.error(`[${e}] Plugin is not installed`),E(`Plugin "${e}" is not installed`),1;if(r.status==="disabled")return pe.debug(`[${e}] Already disabled, skipping`),C(`${r.name} is already disabled`),0;try{return pe.debug(`[${e}] Disabling plugin (current status: ${r.status})`),await Po(e,"disabled",t.scope),pe.info(`[${e}] Disabled successfully`),ce(`${r.name} disabled successfully`),0}catch(n){return pe.error(`[${e}] Failed to disable: ${q(n)}`),E(q(n)),1}}async function Gm(e,t,r){r.silent||C(`${t}Updating ${e}...`);try{let n=await pi(e,r);return r.silent?je({status:"updated",plugin:n.name,previousVersion:n.previousVersion,newVersion:n.newVersion,duration_ms:n.duration_ms}):ce(`${t}${n.name} v${n.previousVersion} \u2192 v${n.newVersion}`),{name:e,success:!0}}catch(n){if(n instanceof vr)return r.silent?je({status:"up_to_date",plugin:e,message:n.message}):C(`${t}${n.message}`),{name:e,success:true,skipped:true};let o=q(n);return r.silent?Ze({status:"error",plugin:e,message:o}):E(`${t}Failed to update ${e}: ${o}`),{name:e,success:false,error:o}}}function dI(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(`
|
|
204
|
+
Update summary: ${t} updated, ${r} already up to date, ${n} failed`);}async function pI(e,t,r){try{let n=await _n(e,r.source);Oe(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(q(n)),1}return 0}function mI(e){return new Map(e.filter(t=>!!t.version).map(t=>[t.name,t.version]))}function fI(e,t,r){let n=t.get(e.name);return n?e.version&&Oe(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 gI(e,t){try{let r=await zt(t.source),n=mI(r),o=0;for(let s of e)fI(s,n,t.force)&&o++;o===0&&C("All plugins are up to date");}catch(r){return E(q(r)),1}return 0}async function hI(e,t){let r=[];for(let n=0;n<e.length;n++){let o=`[${n+1}/${e.length}] `,s=await Gm(e[n].name,o,t);r.push(s);}return t.silent?je({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}:{}}))}):dI(r),r.some(n=>!n.success)?1:0}async function Wm(e,t={}){if(!await de())return 1;if(e){let o=Mi(e,t.scope);return o?t.dryRun?pI(e,o.version??"",t):(await Gm(e,"",t)).success?0:1:(t.silent?Ze({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):E(`Plugin "${e}" is not installed`),1)}let n=ie().filter(o=>o.marketplace===ee);return n.length===0?(t.silent?je({status:"empty",message:"No plugins installed"}):C("No plugins installed"),0):t.dryRun?gI(n,t):hI(n,t)}V();L();var Ho=x("cli:bundle");function yI(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 wI(e,t){let r=t.filter(o=>o.available).length,n=t.length-r;process.stdout.write(`
|
|
205
205
|
Bundle: ${y(e)} (${t.length} artifacts)
|
|
206
|
-
`);for(let o of t)process.stdout.write(`${
|
|
206
|
+
`);for(let o of t)process.stdout.write(`${yI(o)}
|
|
207
207
|
`);process.stdout.write(`
|
|
208
208
|
${r} available for installation`),n>0&&process.stdout.write(` | ${n} unavailable`),process.stdout.write(`
|
|
209
209
|
|
|
210
|
-
`);}async function
|
|
210
|
+
`);}async function zm(e){if(!e.trim())return E("Bundle name cannot be empty."),1;if(!await de())return 1;Ho.debug(`Fetching bundle "${e}"`);let r;try{r=await hi(e);}catch(a){return a instanceof Hn||a instanceof No?(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`),wI(r.title,n),o.length===0)return E("No artifacts available for installation in this bundle."),1;if(!await Rt(`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 li(r,{onProgress:({index:a,total:l,artifact:u,success:c,error:d})=>{let m=y(u.name??u.flowId),p=y(u.type??"unknown"),f=c?"\u2713":`\u2717 (${y(d??"failed")})`;a===1&&process.stdout.write(`
|
|
211
211
|
`),process.stdout.write(`[${a}/${l}] Installing ${m} (${p})... ${f}
|
|
212
212
|
`),a===l&&process.stdout.write(`
|
|
213
|
-
`);}});if(
|
|
213
|
+
`);}});if(Ho.debug(`Installation complete \u2014 ${i.installed} installed, ${i.failed} failed, ${i.skipped} skipped`),i.installed>0&&ce(`${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}Er();V();L();var Xm=x("marketplace");function xI(e){return `claude plugin marketplace add ${e}`}async function qm(e,t){if(!await de())return 1;let r;try{r=zs(e);}catch(s){let i=q(s);return t.silent?Ze({status:"error",source:e,message:i}):E(i),1}Xm.debug(`[marketplace] Adding marketplace source: ${r}`);let n=xI(r);if(!t.force){let s=y(r),i=y(n);if(!await Rt(`Add marketplace "${s}"?
|
|
214
214
|
This will run: ${i}
|
|
215
|
-
[y/N] `))return
|
|
215
|
+
[y/N] `))return Xm.debug("[marketplace] Operation cancelled by user"),C("Operation cancelled."),0}let o=t.silent?void 0:Jl({text:`Adding marketplace "${y(r)}"...`}).start();try{let s=await Ce(n);return o?.stop(),s.exitCode!==0?(t.silent?Ze({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?je({status:"success",source:r,command:n,duration_ms:s.duration_ms}):(ce(`Marketplace "${r}" added successfully`),t.verbose&&s.stdout&&C(s.stdout)),0)}catch(s){o?.stop();let i=q(s);return t.silent?Ze({status:"error",source:r,message:i}):E(`Failed to add marketplace "${r}": ${i}`),1}}Ee();V();async function EI(){return await re()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function PI(){let e=Date.now();try{await zt();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 TI(){return await mr()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function CI(){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 Ym(){process.stdout.write(`
|
|
216
216
|
`+T.bold(` FlowSetup CLI Diagnostics
|
|
217
217
|
|
|
218
|
-
`));let e=[{name:"Credentials",fn:
|
|
218
|
+
`));let e=[{name:"Credentials",fn:EI},{name:"Prompt Manager",fn:PI},{name:"Valid Token",fn:TI},{name:"Claude Code",fn:CI}],t=true;for(let r of e){let n=await r.fn(),o="",s=T.green;n.passed?o=T.green("[OK] "):(o=T.red("[FAIL]"),s=T.red,t=false);let i=` ${o} ${s(r.name.padEnd(18))} ${y(n.message)}`;process.stdout.write(i+`
|
|
219
219
|
`);}return process.stdout.write(`
|
|
220
220
|
`),t?(process.stdout.write(T.green(` \u2713 All checks passed!
|
|
221
221
|
|
|
222
222
|
`)),0):(process.stdout.write(T.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
223
223
|
|
|
224
|
-
`)),1)}
|
|
224
|
+
`)),1)}Ee();wn();K();async function Zm(e){let t=await re(),r=fr("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),n={Authorization:`Bearer ${e}`,accept:"application/json"};if(t?.tenant){if(!Kt.test(t.tenant))throw new Error(`Invalid tenant value: "${t.tenant}"`);n.FlowTenant=t.tenant;}let o=await Xu.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}Sn();ws();Ee();V();L();var AI=x("commands:usage"),_i=20,Qm="EMAIL",ef="MONTHLY CONSUMPTION (USD)",tf="STATUS";function $I(e){let t=Math.min(100,Math.max(0,e)),r=Math.round(t/100*_i),n=_i-r,o=T.green;return t>=90?o=T.red:t>=70&&(o=T.yellow),o("\u2588".repeat(r))+T.dim("\u2591".repeat(n))}function rf(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function LI(e){let t=e.toLowerCase(),r=y(e),n=r.charAt(0).toUpperCase()+r.slice(1).toLowerCase();return t==="ok"||t==="unblocked"?T.green(`\u2299 ${n}`):t==="warning"?T.yellow(`\u26A0 ${n}`):t==="blocked"?T.red("\u2717 Budget limit reached"):T.red(`\u2717 ${n}`)}function MI(e){let t=Pt(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 RI(e){try{let t=await ys();if(t?.email)return y(t.email);let r=yn(e);return y(r.email??"")}catch(t){return AI.debug(`JWT email decode failed: ${String(t)}`),""}}async function nf(e){if(!await de())return 1;let r;try{r=await Ct();}catch(g){return E(`Authentication error: ${q(g)}`),1}let n;try{n=await Zm(r);}catch(g){return E(`Failed to fetch usage data: ${q(g)}`),1}if(e.json)return cr(n),0;let o=await RI(r)||y(n.user_id),s=rf(n.consumed_usd),i=rf(n.budget_limit),a=`${n.percentage.toFixed(1)}%`,l=`${s} / ${i} (${a})`,u=Math.max(Qm.length,o.length+2),c=Math.max(ef.length,_i+2+l.length),d=` ${Qm.padEnd(u)} ${ef.padEnd(c)} ${tf}`,m=` ${"\u2500".repeat(u)} ${"\u2500".repeat(c)} ${"\u2500".repeat(tf.length)}`,p=`${T.cyan("\u2022")} ${o.padEnd(u-2)}`,f=`${$I(n.percentage)} ${l.padEnd(c-_i-2)}`,h=` ${T.dim("Resets")} ${MI(n.renewal_date)}`;return process.stdout.write(`
|
|
225
225
|
`),process.stdout.write(T.dim(d)+`
|
|
226
226
|
`),process.stdout.write(T.dim(m)+`
|
|
227
|
-
`),process.stdout.write(` ${p} ${f} ${
|
|
227
|
+
`),process.stdout.write(` ${p} ${f} ${LI(n.status)}
|
|
228
228
|
`),process.stdout.write(h+`
|
|
229
229
|
`),process.stdout.write(`
|
|
230
|
-
`),0}var
|
|
231
|
-
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function
|
|
230
|
+
`),0}var OI=["github.com","www.github.com"],UI=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,BI=/^([^@]+)@(.+)$/;function NI(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function Hl(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 FI(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=Hl(s);}}else if(t.length>2){let s=t.slice(2).join("/");o.subpath=Hl(s);}return e.hash&&e.hash.length>1&&(o.ref=decodeURIComponent(e.hash.slice(1))),o}function Di(e){let t=e.trim();if(!t)throw new Error("Skill source cannot be empty.");if(NI(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:")&&OI.includes(r.hostname))return FI(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(UI);if(s){let i=s[1],a=s[2],l=s[3],u,c=a.match(BI);c&&(a=c[1],u=c[2]),a.endsWith(".git")&&(a=a.slice(0,-4));let d={type:"github",url:`https://github.com/${i}/${a}.git`};if(n&&(d.ref=n),u&&(d.skillFilter=u),l){let m=l.replace(/^\//,"");m&&(d.subpath=Hl(m));}return d}}return {type:"git",url:t}}function Oi(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 of(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 Wl=new Set(["node_modules",".git","dist","build","__pycache__"]);function lf(e,t){let r=normalize(resolve(e)),n=normalize(resolve(t));return n.startsWith(r+sep)||n===r}function HI(e,t){let r=normalize(resolve(e)),n=normalize(resolve(join(e,t)));return n.startsWith(r+sep)||n===r}async function Gl(e){try{let t=join(e,"SKILL.md");return (await stat(t)).isFile()}catch{return false}}async function Go(e){try{let t=await readFile(e,"utf-8"),{data:r}=of(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 cf(e,t=0,r=5){if(t>r)return [];try{let[n,o]=await Promise.all([Gl(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),s=n?[e]:[],i=await Promise.all(o.filter(a=>a.isDirectory()&&!Wl.has(a.name)).map(a=>cf(join(e,a.name),t+1,r)));return [...s,...i.flat()]}catch{return []}}async function Ni(e,t){let r=[],n=new Set;if(t&&!HI(e,t))throw new Error(`Invalid subpath: "${t}" resolves outside the repository directory.`);let o=t?join(e,t):e;if(await Gl(o)){let i=await Go(join(o,"SKILL.md"));if(i)return r.push(i),n.add(i.name),r}let s=[o,join(o,"skills"),join(o,".claude/skills"),join(o,".agents/skills")];for(let i of s)try{let a=await readdir(i,{withFileTypes:!0});for(let l of a){if(!l.isDirectory())continue;let u=join(i,l.name);if(await Gl(u)){let c=await Go(join(u,"SKILL.md"));c&&!n.has(c.name)&&(r.push(c),n.add(c.name));}}}catch{}if(r.length===0){let i=await cf(o);for(let a of i){let l=await Go(join(a,"SKILL.md"));l&&!n.has(l.name)&&(r.push(l),n.add(l.name));}}return r}function uf(e,t){let r=t.map(n=>n.toLowerCase());return e.filter(n=>{let o=n.name.toLowerCase();return r.some(s=>s===o)})}qe();var ff=1,YI={retries:5,minTimeout:50};async function gf(e,t){mkdirSync(dirname(e),{recursive:true});let r=await fh.lock(e+".lock",{realpath:false,retries:YI});try{return await t()}finally{await r();}}function df(){return {version:ff,skills:{}}}async function Fi(e){let t=eo(e);try{let r=await readFile(t,"utf-8"),n=JSON.parse(r);return !n.version||n.version<ff?df():n}catch{return df()}}function ZI(e){let t={};for(let r of Object.keys(e).sort())t[r]=e[r];return t}async function hf(e,t){let r=eo(t);mkdirSync(dirname(r),{recursive:true});let n={version:e.version,skills:ZI(e.skills)},o=`${r}.${randomUUID()}.tmp`;writeFileSync(o,JSON.stringify(n,null,2)+`
|
|
231
|
+
`,{encoding:"utf-8",mode:384}),renameSync(o,r);}async function yf(e,t,r){let n=eo(r);await gf(n,async()=>{let o=await Fi(r),s=new Date().toISOString(),i=o.skills[e];o.skills[e]={...t,installedAt:i?.installedAt??s,updatedAt:s},await hf(o,r);});}async function wf(e,t){let r=eo(t);await gf(r,async()=>{let n=await Fi(t);e in n.skills&&(delete n.skills[e],await hf(n,t));});}qe();L();var Sf=x("skillInstaller");async function ib(e,t,r,n){try{await v(I.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:t,version:r,duration_ms:n,interface:Y().interfaceType});}catch(o){Sf.warn(`Failed to send skill install metrics: ${String(o)}`);}}async function ab(e,t){try{await v(I.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:t instanceof Error?t.name:"UNKNOWN",error_message:(t instanceof Error?t.message:String(t)).slice(0,500),interface:Y().interfaceType});}catch(r){Sf.warn(`Failed to send skill install-failed metrics: ${String(r)}`);}}async function lb(e,t){await cp$1(e,t,{recursive:true,dereference:false,filter:r=>{if(Wl.has(basename(r)))return false;try{return !lstatSync(r).isSymbolicLink()}catch{return false}}});}async function cb(e,t,r){let n=st(e.name),o=Or(t),s=join(o,n);if(!lf(o,s))return {skill:e.name,success:false,path:s,error:`Unsafe install path: "${s}" escapes skills directory`};try{await rm$1(s,{recursive:!0,force:!0}),await mkdir(s,{recursive:!0}),await lb(e.path,s);let a=Oi(r)??r.url;return await yf(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 xf(e,t){let r=Di(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 _t(r.url,r.ref),o=n;let s=await Ni(o,r.subpath),i=[...t.skillFilter??[]];r.skillFilter&&i.push(r.skillFilter);let a=i.length>0?uf(s,i):s,l=[],u=r.ref??"latest";for(let c of a){let d=Date.now(),m=await cb(c,t.scope,r);l.push(m);let p=Date.now()-d;m.success?await ib(c.name,t.scope,u,p):await ab(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:l,discovered:s.length,installed:l.filter(c=>c.success).length,failed:l.filter(c=>!c.success).length}}finally{n&&await Dt(n).catch(()=>{});}}qe();V();L();var fb=x("skills");async function gb(e){try{await v(I.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Y().interfaceType});}catch(t){fb.warn(`Failed to send skill uninstall metrics: ${String(t)}`);}}async function hb(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 yb(e){let t=Di(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 _t(t.url,t.ref),n=r;let o=await Ni(n,t.subpath);if(o.length===0)return C("No skills found in this source."),0;let i=Oi(t)??y(e);C(`Found ${o.length} skill(s) in ${i}:
|
|
232
232
|
`);for(let a of o){let l=y(a.name),u=y(a.description);process.stdout.write(` ${T.bold(l)} ${T.dim(u)}
|
|
233
233
|
`);}return process.stdout.write(`
|
|
234
|
-
`),0}catch(n){return n instanceof
|
|
235
|
-
`);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
|
|
236
|
-
`);for(let s of r){let i=n.skills[
|
|
234
|
+
`),0}catch(n){return n instanceof Cr?E(n.message):E(n instanceof Error?n.message:String(n)),1}finally{r&&await Dt(r).catch(()=>{});}}function wb(e){for(let r of e.results){let n=y(r.skill);if(r.success){let o=relative(process.cwd(),r.path);ce(`${n} installed ${T.dim(`\u2192 ${o}/`)}`);}else E(`${n}: ${y(r.error??"unknown error")}`);}process.stdout.write(`
|
|
235
|
+
`);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 bf(e,t){if(t.list)return yb(e);let r=t.global?"global":"project";try{let n=await xf(e,{scope:r,skillFilter:t.skill,yes:t.yes});return wb(n),n.failed>0?1:0}catch(n){return n instanceof Cr?E(n.message):E(n instanceof Error?n.message:String(n)),1}}async function vf(e){let t=Or(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 Go(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 Ef(e){let t=e.global?"global":"project",r=await vf(t),n=await Fi(t);if(e.json){let s=r.map(i=>({name:i.name,description:i.description,path:i.path,source:n.skills[st(i.name)]?.source}));return cr(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}):
|
|
236
|
+
`);for(let s of r){let i=n.skills[st(s.name)]?.source,a=y(s.name),l=y(s.description),u=l.length>80?l.slice(0,77)+"...":l,c=i?T.dim(` (${i})`):"";process.stdout.write(` ${T.bold(a)}${c}
|
|
237
237
|
`),process.stdout.write(` ${T.dim(u)}
|
|
238
238
|
|
|
239
|
-
`);}return 0}async function
|
|
239
|
+
`);}return 0}async function Pf(e,t){let r=t.global?"global":"project";if(!e){let i=await vf(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)}
|
|
240
240
|
`);return process.stdout.write(`
|
|
241
|
-
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=
|
|
242
|
-
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",u=
|
|
243
|
-
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}function
|
|
241
|
+
`),C("Specify a skill name to remove: flow skills remove <name>"),1}let n=st(e),o=Or(r),s=join(o,n);try{await stat(s);}catch{return E(`Skill "${y(e)}" is not installed.`),1}if(!t.force&&!await hb(`Remove skill "${y(n)}"?`))return C("Cancelled."),0;try{return await rm$1(s,{recursive:!0,force:!0}),await wf(n,r),await gb(n),ce(`Skill "${y(n)}" removed.`),0}catch(i){return E(`Failed to remove skill: ${i instanceof Error?i.message:String(i)}`),1}}V();L();K();var ji=x("transfer"),Xl=1;function Sb(e){return e.marketplace&&e.marketplace!==ee?`${e.name}@${e.marketplace}`:e.name}function xb(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 kf(e){let t=xe__default.resolve(e.output);try{let r=ie(),n={version:Xl,exportedAt:new Date().toISOString(),plugins:r.map(o=>({name:o.name,marketplace:o.marketplace,scope:o.scope,...o.type!==void 0?{type:o.type}:{}}))};return Ie__default.writeFileSync(t,JSON.stringify(n,null,2),"utf-8"),ce(`Exported ${r.length} plugin(s) to ${t}`),0}catch(r){let n=q(r);return ji.error(`Export failed: ${n}`),E(`Failed to export plugins: ${n}`),1}}async function Af(e,t={}){if(!await de())return 1;let r;try{let a=Ie__default.readFileSync(xe__default.resolve(e),"utf-8");r=JSON.parse(a);}catch(a){return E(`Failed to read import file "${e}": ${q(a)}`),1}if(r.version!==Xl)return E(`Unsupported export format version ${r.version??"(none)"} \u2014 expected ${Xl}`),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 u=`entry[${a}]`;ji.warn(`Skipping ${u}: missing or invalid name`),o.push({name:u,error:"missing or invalid name"});}else l.type==="mcp"?(ji.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(ie().map(l=>l.name));xb(n,a);}if(t.dryRun)return C("Dry-run mode: no plugins were installed"),0;if(n.length===0){C(`
|
|
242
|
+
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",u=Sb(a);ji.debug(`[${a.name}] Installing as "${u}" in scope "${l}"`),await Ri([u],{scope:l,force:t.force})===0?i++:o.push({name:a.name,error:"installation failed"});}C(`
|
|
243
|
+
Import summary: ${i} installed, ${o.length} failed`);for(let a of o)E(` ${a.name}: ${a.error}`);return o.length>0?1:0}L();V();function F(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}V();L();var bb=x("moduleProxy");function vb(e){if(!process.stdin.isTTY)return Promise.resolve(false);let t=ol.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 $f(e,t){let r=Date.now(),o=spawnSync(e.binaryName,t,{stdio:"inherit",env:process.env}).status??1;await v(I.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:o,duration_ms:Date.now()-r,subcommand:t[0]??null}).catch(s=>{bb.warn(`Failed to emit proxy executed event: ${String(s)}`);}),F(o);}async function Mf(e,t){let r=se.find(o=>o.alias===e);if(!r){E(`Unknown module alias: '${e}'`),F(1);return}if(!await At(r.binaryName)){E(`Module '${e}' (${r.binaryName}) is not installed.`);let o=r.platforms[process.platform];if(!o||o.status!=="supported"){await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),F(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.`),F(1);return}if(await vb("Would you like to install it now? [Y/n] ")){await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let a=await Ir(r,"inline",s);if(!a.success){E(`Failed to install '${e}': ${a.error?.message??"unknown error"}`),F(1);return}await $f(r,t);}else C(`To install manually, run: flow modules install ${e}`),await v(I.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),F(1);return}await $f(r,t);}V();var Cb=promisify(execFile);async function kb(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:n}=await Cb(Jt(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(n).trim()||null}let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);try{let n={"User-Agent":`flow-plugins-cli/${me}`,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 Ab(e,t,r,n){return n?.status==="experimental"?"experimental":!n||n.status!=="supported"||!e?"not_installed":t&&r&&Oe(t,r)?"outdated":"installed"}async function ql(){let e=await Promise.all(se.map(async t=>{let[r,n]=await Promise.all([At(t.binaryName),kb(t)]),s=et(t.alias)?.installedVersion??null,i=t.platforms[process.platform],a=Ab(r,s,n,i),l=s??"\u2014";return [t.name,t.alias,l,a,process.platform]}));return gn(["Name","Alias","Version","Status","Platform"],e),0}async function Df(e){let t=se.find(i=>i.alias===e);if(!t)return E(`Unknown module alias: '${e}'`),1;let[r]=await Wn([t]);if(r.alreadyInstalled){let i=et(t.alias),a=i?.installedVersion?` (v${i.installedVersion})`:"";return C(`Module ${t.name} already installed${a}. Use: flow modules update ${e}`),0}if(r.availableStrategies.length===0){let i=t.platforms[process.platform],a=t.docs?` See: ${t.docs}`:"";return !i||i.status!=="supported"?E(`Module ${t.name} is not supported on ${process.platform}.${a}`):E(`No installation method available for ${t.name} on ${process.platform}.${a}`),1}let n=r.availableStrategies[0],o=Jl({text:`Installing ${t.name}...`}).start(),s;try{s=await Ir(t,"on_demand",n);}finally{o.stop();}return s.success?(ce(`${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 Rf(e,t){let r=Jl({text:`Updating ${e.name}...`}).start(),n;try{n=await Ms(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 Of(e){if(e!==null){let n=se.find(i=>i.alias===e);if(!n)return E(`Unknown module alias: '${e}'`),1;let o=et(n.alias);return o?.installMethod?await Rf(n,o.installedVersion??"unknown")==="error"?1:0:(E(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let t=Gr().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=se.find(i=>i.alias===n.alias);if(!o)continue;await Rf(o,n.installedVersion??"unknown")==="error"&&(r=1);}return r}function Uf(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${me}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
244
244
|
Without arguments, opens the interactive interface (TUI).
|
|
245
245
|
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",`
|
|
246
246
|
Examples:
|
|
247
|
-
$ flow setup init`).action(async()=>{let c=await
|
|
247
|
+
$ flow setup init`).action(async()=>{let c=await Vl();F(c);}),t.addCommand(r);let n=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");n.command("list").description("List available or installed plugins").option("--available","show full catalog with installation status",false).option("--outdated","show only plugins with updates available",false).option("--json","output as JSON",false).option("--source <name>","Named content source to list from (e.g. flow-harness); defaults to the standard catalog").addHelpText("after",`
|
|
248
248
|
Examples:
|
|
249
249
|
$ flow plugin list
|
|
250
250
|
$ flow plugin list --available
|
|
251
251
|
$ flow plugin list --outdated
|
|
252
|
-
$ flow plugin list --json
|
|
252
|
+
$ flow plugin list --json
|
|
253
|
+
$ flow plugin list --available --source flow-harness`).action(async c=>{let d=await Km(c);F(d);}),n.command("install").description("Install one or more plugins from the Findr catalog into Claude Code").argument("<name...>","Name(s) of the plugin(s) to install (space-separated)").option("--force","Reinstall even if the version is already installed").option("--verbose","Display each step of the installation process").option("--silent","Output in JSON only").option("--marketplace-source <source>","GitHub source (owner/repo) for marketplace auto-add when installing external plugins").option("--source <name>","Named content source to install from (e.g. flow-harness); defaults to the standard catalog").addOption(new Option("--scope <scope>","Scope to install into: user, project, or local").choices(["user","project","local"])).addHelpText("after",`
|
|
253
254
|
Examples:
|
|
254
255
|
$ flow plugin install flow-adr-writer
|
|
255
256
|
$ flow plugin install flow-adr-writer --scope project
|
|
@@ -257,11 +258,12 @@ Examples:
|
|
|
257
258
|
$ flow plugin install flow-adr-writer --force
|
|
258
259
|
$ flow plugin install flow-adr-writer --silent
|
|
259
260
|
$ flow plugin install superpowers@claude-plugins-official
|
|
260
|
-
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
|
|
261
|
+
$ flow plugin install agent-sdk-dev@claude-code-plugins --marketplace-source anthropics/claude-code
|
|
262
|
+
$ flow plugin install runbook-design --source flow-harness`).action(async(c,d)=>{let m=c.filter(f=>f.trim());if(m.length===0){E("No valid plugin names provided"),F(1);return}Fe("cli",{verbose:d.verbose,silent:d.silent});let p=await Ri(m,d);F(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",`
|
|
261
263
|
Examples:
|
|
262
264
|
$ flow plugin uninstall flow-adr-writer
|
|
263
265
|
$ flow plugin uninstall flow-adr-writer --scope project
|
|
264
|
-
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await
|
|
266
|
+
$ flow plugin uninstall startup-pack-ai --force`).action(async(c,d)=>{let m=await Vm(c,d);F(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",`
|
|
265
267
|
Examples:
|
|
266
268
|
$ flow plugin update flow-adr-writer
|
|
267
269
|
$ flow plugin update flow-adr-writer --scope project
|
|
@@ -270,78 +272,78 @@ Examples:
|
|
|
270
272
|
$ flow plugin update flow-adr-writer --verbose
|
|
271
273
|
$ flow plugin update flow-adr-writer --silent
|
|
272
274
|
$ flow plugin update
|
|
273
|
-
$ flow plugin update --dry-run`).action(async(c,d)=>{
|
|
275
|
+
$ flow plugin update --dry-run`).action(async(c,d)=>{Fe("cli",{verbose:d.verbose,silent:d.silent});let m=await Wm(c??null,d);F(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",`
|
|
274
276
|
Examples:
|
|
275
277
|
$ flow plugin enable flow-adr-writer
|
|
276
|
-
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
278
|
+
$ flow plugin enable flow-adr-writer --scope project`).action(async(c,d)=>{Fe("cli");let m=await Jm(c,d);F(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",`
|
|
277
279
|
Examples:
|
|
278
280
|
$ flow plugin disable flow-adr-writer
|
|
279
|
-
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{
|
|
281
|
+
$ flow plugin disable flow-adr-writer --scope project`).action(async(c,d)=>{Fe("cli");let m=await Hm(c,d);F(m);}),n.command("export").description("Export installed plugins to a JSON file").option("--output <file>","Output file path","flow-plugins.json").addHelpText("after",`
|
|
280
282
|
Examples:
|
|
281
283
|
$ flow plugin export
|
|
282
|
-
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await
|
|
284
|
+
$ flow plugin export --output my-plugins.json`).action(async c=>{let d=await kf(c);F(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",`
|
|
283
285
|
Examples:
|
|
284
286
|
$ flow plugin import flow-plugins.json
|
|
285
287
|
$ flow plugin import flow-plugins.json --scope user
|
|
286
288
|
$ flow plugin import flow-plugins.json --force
|
|
287
289
|
$ flow plugin import flow-plugins.json --dry-run
|
|
288
|
-
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await
|
|
290
|
+
$ flow plugin import flow-plugins.json --diff`).action(async(c,d)=>{let m=await Af(c,d);F(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",`
|
|
289
291
|
Examples:
|
|
290
292
|
$ flow plugin marketplace add anthropics/claude-code
|
|
291
293
|
$ flow plugin marketplace add https://github.com/owner/repo
|
|
292
294
|
$ flow plugin marketplace add anthropics/claude-code --force
|
|
293
|
-
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{
|
|
295
|
+
$ flow plugin marketplace add anthropics/claude-code --silent`).action(async(c,d)=>{Fe("cli",{verbose:d.verbose,silent:d.silent});let m=await qm(c,d);F(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",`
|
|
294
296
|
Examples:
|
|
295
297
|
$ flow mcp add notion --transport http https://mcp.notion.com/mcp
|
|
296
298
|
$ flow mcp add mcp-chrome --transport stdio uvx mcp-chrome
|
|
297
299
|
$ flow mcp add playwright-mcp --transport stdio uvx playwright-mcp --force
|
|
298
|
-
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{
|
|
300
|
+
$ flow mcp add notion --transport http https://mcp.notion.com/mcp --scope project`).action(async(c,d,m)=>{Fe("cli",{verbose:m.verbose,silent:m.silent});let p=await yp(c,d,m);F(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",`
|
|
299
301
|
Examples:
|
|
300
302
|
$ flow mcp remove notion
|
|
301
303
|
$ flow mcp remove notion --scope project
|
|
302
|
-
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{
|
|
304
|
+
$ flow mcp remove playwright-mcp --force`).action(async(c,d)=>{Fe("cli",{verbose:d.verbose,silent:d.silent});let m=await wp(c,d);F(m);}),t.addCommand(s);let i=new Command("auth").description("Manage authentication credentials");i.command("login").description("Authenticate and save credentials locally").option("--jwt <token>","JWT token for non-interactive authentication").option("--starter-kit <slug>","Starter kit slug for non-interactive setup").option("--custom-url <url>","Custom Flow base URL for flow-ai-obs configuration").option("--custom-email <email>","Custom email for flow-ai-obs configuration").option("--verbose","Display each step of the authentication process").addHelpText("after",`
|
|
303
305
|
Examples:
|
|
304
306
|
$ flow auth login
|
|
305
307
|
$ flow auth login --jwt <token>
|
|
306
308
|
$ flow auth login --jwt <token> --starter-kit dev
|
|
307
309
|
$ flow auth login --jwt <token> --custom-email name@example.com
|
|
308
|
-
$ flow auth login --verbose`).action(async c=>{
|
|
310
|
+
$ flow auth login --verbose`).action(async c=>{Fe("cli",{verbose:c.verbose});let d=await Vl(c);F(d);}),i.command("logout").description("Remove locally saved credentials").option("--force","Skip interactive confirmation").addHelpText("after",`
|
|
309
311
|
Examples:
|
|
310
312
|
$ flow auth logout
|
|
311
|
-
$ flow auth logout --force`).action(async c=>{let d=await
|
|
313
|
+
$ flow auth logout --force`).action(async c=>{let d=await Fm(c.force);F(d);}),i.command("status").description("Display the current authentication status").addHelpText("after",`
|
|
312
314
|
Examples:
|
|
313
|
-
$ flow auth status`).action(async()=>{let c=await
|
|
315
|
+
$ flow auth status`).action(async()=>{let c=await jm();F(c);}),t.addCommand(i);let a=new Command("skills").description("Manage skills for Claude Code from GitHub repositories or local paths");a.command("add").description("Install skills from a GitHub repo or local path into Claude Code").argument("<source>","GitHub repo (owner/repo), URL, or local path").option("-g, --global","Install globally (~/.claude/skills/)").option("-s, --skill <names...>","Install only specific skills by name").option("-y, --yes","Skip confirmation prompts").option("--list","List available skills without installing").addHelpText("after",`
|
|
314
316
|
Examples:
|
|
315
317
|
$ flow skills add vercel-labs/agent-skills
|
|
316
318
|
$ flow skills add owner/repo -g
|
|
317
319
|
$ flow skills add owner/repo --skill pr-review commit
|
|
318
320
|
$ flow skills add ./local/skills -y
|
|
319
|
-
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await
|
|
321
|
+
$ flow skills add owner/repo --list`).action(async(c,d)=>{let m=await bf(c,d);F(m);}),a.command("list").description("List installed skills").option("-g, --global","List global skills (default: project)").option("--json","Output as JSON").addHelpText("after",`
|
|
320
322
|
Examples:
|
|
321
323
|
$ flow skills list
|
|
322
324
|
$ flow skills list -g
|
|
323
|
-
$ flow skills list --json`).action(async c=>{let d=await
|
|
325
|
+
$ flow skills list --json`).action(async c=>{let d=await Ef(c);F(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",`
|
|
324
326
|
Examples:
|
|
325
327
|
$ flow skills remove pr-review
|
|
326
|
-
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await
|
|
328
|
+
$ flow skills remove pr-review -g --force`).action(async(c,d)=>{let m=await Pf(c,d);F(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",`
|
|
327
329
|
Examples:
|
|
328
330
|
$ flow bundle install "My React Kit"
|
|
329
331
|
$ flow bundle install "Squad Setup Bundle"
|
|
330
|
-
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{
|
|
332
|
+
$ flow bundle install "My React Kit" --verbose`).action(async(c,d)=>{Fe("cli",{verbose:d.verbose});let m=await zm(c);F(m);}),t.addCommand(l),t.command("health").description("Check the CLI configuration and connectivity").addHelpText("after",`
|
|
331
333
|
Examples:
|
|
332
|
-
$ flow health`).action(async()=>{let c=await
|
|
334
|
+
$ flow health`).action(async()=>{let c=await Ym();F(c);}),t.command("usage").description("Show your current Flow budget usage").option("--json","output as JSON",false).addHelpText("after",`
|
|
333
335
|
Examples:
|
|
334
336
|
$ flow usage
|
|
335
|
-
$ flow usage --json`).action(async c=>{let d=await
|
|
337
|
+
$ flow usage --json`).action(async c=>{let d=await nf(c);F(d);});let u=new Command("modules").description("Manage Flow modules (binary companions for Claude Code)");u.action(async()=>{let c=await ql();F(c);}),u.command("list").description("List available and installed modules").addHelpText("after",`
|
|
336
338
|
Examples:
|
|
337
|
-
$ flow modules list`).action(async()=>{let c=await
|
|
339
|
+
$ flow modules list`).action(async()=>{let c=await ql();F(c);}),u.command("install").description("Install a module by alias").argument("<alias>","Module alias to install (e.g. metrics, dashboard)").addHelpText("after",`
|
|
338
340
|
Examples:
|
|
339
341
|
$ flow modules install metrics
|
|
340
|
-
$ flow modules install dashboard`).action(async c=>{let d=await
|
|
342
|
+
$ flow modules install dashboard`).action(async c=>{let d=await Df(c);F(d);}),u.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
341
343
|
Examples:
|
|
342
344
|
$ flow modules update
|
|
343
|
-
$ flow modules update metrics`).action(async c=>{let d=await
|
|
345
|
+
$ flow modules update metrics`).action(async c=>{let d=await Of(c??null);F(d);}),t.addCommand(u);for(let c of se)t.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async d=>{await Mf(c.alias,d);});return t.hook("preAction",()=>{Ei();}),t}L();function Mb(){return xe__default.join($e__default.homedir(),".claude","settings.json")}function Nf(){let e=Mb();try{if(!Ie__default.existsSync(e))return !0;let r=JSON.parse(Ie__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return r===!1?!1:r==="modules-only"?"modules-only":!0}catch{return true}}L();var Bb=x("updateChecker"),Nb=promisify(execFile),Fb=1440*60*1e3,Ff=3e4;function jb(){let e=process.env.FLOW_HOME??xe__default.join($e__default.homedir(),".flow");return xe__default.join(e,"update.lock")}async function jf(e){try{let{stdout:t}=await Nb(Jt(),["view",e,"version"],{timeout:Ff,shell:process.platform==="win32"});return String(t).trim()||null}catch{return null}}async function Kb(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Ff);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 Vb(e){return e.versionCheck.type==="npm-registry"?jf(e.versionCheck.package):Kb(e.versionCheck.repo)}async function Jb(){let e=await jf("@ciandt-flow/cli");return e&&Oe(me,e)?($i({currentVersion:me,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function Hb(){let e=Gr().filter(t=>t.installMethod!==null);await Promise.all(e.map(async t=>{let r=se.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<Fb)return;let s=await Vb(r);try{await gt({...t,lastChecked:new Date().toISOString()});}catch(i){Bb.warn(`Failed to update lastChecked for ${t.alias}: ${String(i)}`);}s&&t.installedVersion&&Oe(t.installedVersion,s)&&Ms(r,"background").catch(()=>{});}));}async function Zl(){let e=Nf();if(e===false)return;let t=jb();Ie__default.mkdirSync(xe__default.dirname(t),{recursive:true});let r=null;try{r=await fh.lock(t,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let n=await Jb().catch(()=>null);n&&process.stdout.write(`
|
|
344
346
|
\u26A0 @ciandt-flow/cli v${n} installing in background.
|
|
345
347
|
Restart flow to apply the update.
|
|
346
348
|
|
|
347
|
-
`);}await
|
|
349
|
+
`);}await Hb().catch(()=>{});}finally{await r().catch(()=>{});}}var Wb=x("cli"),Ql=Uf(async()=>{Fe("tui"),_c("tui"),Dc(),process.on("SIGINT",()=>{let{activeTab:t,screen:r}=S.getState();so("sigint",t,r).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:t,screen:r}=S.getState();so("sigterm",t,r).finally(()=>process.exit(143));}),await Zl().catch(()=>{}),await Qu().catch(t=>{Wb.error(`Failed to init catalog registry: ${String(t)}`);}),await Am();let{waitUntilExit:e}=render(jsx($m,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Ql.hook("preAction",async(e,t)=>{t!==Ql&&await Zl().catch(()=>{});});Ql.parse();
|