@ciandt-flow/cli 2.9.0-beta.28 → 2.9.0
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 +76 -68
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as bt from'crypto';import {randomUUID,createHash}from'crypto';import*as Le from'os';import Le__default,{tmpdir,homedir}from'os';import*as De from'path';import De__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as we from'fs';import we__default,{readFileSync,mkdirSync,existsSync,writeFileSync,rmSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import R from'chalk';import*as Pd from'readline';import {createInterface}from'readline';import xn from'conf';import Au,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import
|
|
3
|
-
`;try{we.appendFileSync(this.filePath,o,"utf-8");}catch{}}ensureDir(){try{let a=De.dirname(this.filePath);we.mkdirSync(a,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(we.statSync(this.filePath).size>
|
|
2
|
+
import*as bt from'crypto';import {randomUUID,createHash}from'crypto';import*as Le from'os';import Le__default,{tmpdir,homedir}from'os';import*as De from'path';import De__default,{join,dirname,basename,normalize,resolve,sep,relative,isAbsolute}from'path';import*as we from'fs';import we__default,{readFileSync,mkdirSync,existsSync,writeFileSync,rmSync,appendFileSync,readdirSync,realpathSync,lstatSync,renameSync}from'fs';import {execFile,spawnSync,exec,spawn}from'child_process';import {promisify}from'util';import R from'chalk';import*as Pd from'readline';import {createInterface}from'readline';import xn from'conf';import Au,{HTTPError}from'ky';import {StatusCodes}from'http-status-codes';import {execa}from'execa';import {Box,Text,render,useWindowSize,useInput,useApp}from'ink';import iv,{useRef,useCallback,useMemo,useEffect,useState}from'react';import {create}from'zustand';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import fb from'jsonwebtoken';import Ab from'proper-lockfile';import Kb from'ink-big-text';import wp from'ink-spinner';import*as Na from'fs/promises';import {readFile,mkdir,writeFile,rename,stat,rm as rm$1,mkdtemp,readdir,cp as cp$1}from'fs/promises';import ry from'unzipper';import {simpleGit,CheckRepoActions}from'simple-git';import qd from'semver';import nc from'yocto-spinner';import {Command,Option}from'commander';import {parse,stringify}from'yaml';var nh=Object.defineProperty;var H=(e,a,o)=>()=>{if(o)throw o[0];try{return e&&(a=e(e=0)),a}catch(t){throw o=[t],t}};var Mc=(e,a)=>{for(var o in a)nh(e,o,{get:a[o],enumerable:true});};var mo,le,tn,ir,ut,pt,qc,rn,Va,ue,ea,_a,ai,mt,gt,ft,ht,U=H(()=>{"use strict";mo="FLOW",le="flow-skills",tn="flow-cli",ir="internal",ut="external",pt={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"},plugin:{label:"Plugin",color:"magenta"}},qc={internal:{label:"Flow",color:"blue"},external:{label:"External",color:"white"}},rn=new Set(["internal","external"]),Va={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"}},ue="flow-claude-md-setup",ea=5,_a=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,ai="https://flow.ciandt.com",mt=/^https:\/\/[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.ciandt\.com\/?$/,gt="Must be a valid CI&T domain (e.g. https://tenant.ciandt.com)",ft=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ht="Must be a valid email address (e.g. name@example.com)";});var oi,ch,Fc,sr,sn=H(()=>{"use strict";oi="aes-256-gcm",ch=16,Fc=16,sr=class{key;constructor(a){if(a.length!==32)throw new Error(`Invalid key length: expected 32 bytes, got ${a.length}`);this.key=a;}encrypt(a){let o=bt.randomBytes(ch),t=bt.createCipheriv(oi,this.key,o,{authTagLength:Fc}),r=Buffer.concat([t.update(a,"utf8"),t.final()]),i=t.getAuthTag();return {iv:o.toString("hex"),authTag:i.toString("hex"),ciphertext:r.toString("hex"),algorithm:oi}}decrypt(a){if(a.algorithm!==oi)throw new Error(`Unsupported encryption algorithm: ${a.algorithm}`);let o=bt.createDecipheriv(oi,this.key,Buffer.from(a.iv,"hex"),{authTagLength:Fc});return o.setAuthTag(Buffer.from(a.authTag,"hex")),Buffer.concat([o.update(Buffer.from(a.ciphertext,"hex")),o.final()]).toString("utf8")}};});function nn(e){return e.replace(mh,"").replace(gh,"").replace(fh,"").replace(lh,"Bearer ***").replace(uh,"***").replace(ph,"***").replace(/\r\n|\r|\n/g,"\\n")}var lh,uh,ph,mh,gh,fh,dn=H(()=>{"use strict";lh=/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,uh=/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?:\.[A-Za-z0-9_-]*)?/g,ph=/[A-Za-z0-9+/]{40,}={0,2}/g,mh=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|\x1b\x1b)/g,gh=/\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,fh=/\x1b/g;});function ri(e){return e||le}function Oc(e,a,o){return ln(ri(o),e,a)}function cn(e,a){return De.join(Le.homedir(),jo,"plugins","marketplaces",ri(a),"plugins","native",e)}function ii(e){return De.join(Le.homedir(),jo,"plugins","marketplaces",ri(e),".claude-plugin","marketplace.json")}function Uo(){return De.join(Le.homedir(),jo,"plugins","known_marketplaces.json")}function Nc(e){return De.join(Le.homedir(),jo,"plugins","marketplaces",ri(e))}function Gc(){return De.join(Le.homedir(),ti,"cache","install.lock")}function Bc(){return De.join(Le.homedir(),ti,"logs","flowsetup.log")}function ln(e,a,o){return De.join(Le.homedir(),jo,"plugins","cache",e,a,o)}function zo(e){let a=e==="global"?Le.homedir():process.cwd();return De.join(a,".claude","skills")}function nr(e){let a=e==="global"?Le.homedir():process.cwd();return De.join(a,".claude","skills-lock.json")}function si(e="user"){return e==="project"?De.join(process.cwd(),".opencode","plugins"):De.join(Le.homedir(),".config","opencode","plugins")}function jc(){return De.join(Le.homedir(),ti,"flow-catalogs.json")}function Uc(){let e=process.env.FLOW_HOME??De.join(Le.homedir(),ti);return De.join(e,"config.json")}function ni(e="user"){return e==="project"||e==="local"?De.join(process.cwd(),jo,"agents"):De.join(Le.homedir(),jo,"agents")}var jo,ti,He=H(()=>{"use strict";U();jo=".claude",ti=".flow";});var hh,bh,di,zc=H(()=>{"use strict";He();hh=5*1024*1024,bh=3,di=class{filePath;constructor(){this.filePath=Bc(),this.ensureDir(),this.rotateIfNeeded();}write(a){let o=`[${a.timestamp.toISOString()}] [${a.level.toUpperCase()}] [${a.module}] ${a.message}
|
|
3
|
+
`;try{we.appendFileSync(this.filePath,o,"utf-8");}catch{}}ensureDir(){try{let a=De.dirname(this.filePath);we.mkdirSync(a,{recursive:!0});}catch{}}rotateIfNeeded(){try{if(we.statSync(this.filePath).size>hh){let o=new Date().toISOString().replace(/[:.]/g,"-"),t=this.filePath.replace(".log",`-${o}.log`);we.renameSync(this.filePath,t),this.cleanOldBackups();}}catch{}}cleanOldBackups(){try{let a=De.dirname(this.filePath),o=De.basename(this.filePath,".log"),t=we.readdirSync(a).filter(r=>r.startsWith(o+"-")&&r.endsWith(".log")).sort().reverse();for(let r of t.slice(bh))we.unlinkSync(De.join(a,r));}catch{}}};});var ci,Wc=H(()=>{"use strict";ci=class{context;constructor(a){this.context=a;}write(a){let o=this.context==="tui"?this.formatTui(a):this.formatCli(a);process.stderr.write(o+`
|
|
4
4
|
`);}formatTui(a){return `[flow:${a.module}] ${a.message}`}formatCli(a){let o=String(a.timestamp.getHours()).padStart(2,"0"),t=String(a.timestamp.getMinutes()).padStart(2,"0"),r=String(a.timestamp.getSeconds()).padStart(2,"0");return `[${o}:${t}:${r}] [${a.level.toUpperCase()}] ${a.message}`}};});var li,Jc=H(()=>{"use strict";li=class{write(a){process.stdout.write(a.message+`
|
|
5
|
-
`);}};});function pn(){return ui}function Hc(e){return un.add(e),()=>{un.delete(e);}}var ui,un,pi,mn=H(()=>{"use strict";ui=[],un=new Set;pi=class{write(a){ui.push(a),ui.length>100&&ui.shift();for(let o of un)o();}};});function
|
|
5
|
+
`);}};});function pn(){return ui}function Hc(e){return un.add(e),()=>{un.delete(e);}}var ui,un,pi,mn=H(()=>{"use strict";ui=[],un=new Set;pi=class{write(a){ui.push(a),ui.length>100&&ui.shift();for(let o of un)o();}};});function vh(){let e=process.env.DEBUG;if(!e)return null;let a=e.split(",").map(t=>t.trim()).filter(Boolean);for(let t of a)if(t==="flow:*")return "all";let o=new Set;for(let t of a)t.startsWith("flow:")&&o.add(t.slice(5));return o.size>0?o:null}function Qe(e,a){if(e==="tui"){let o=vh();Jo={context:e,transports:[new pi,new di],minLevel:o?"debug":"warn",debugModules:o};}else a?.silent?Jo={context:e,transports:[],minLevel:"error",debugModules:null}:a?.verbose?Jo={context:e,transports:[new ci("cli")],minLevel:"debug",debugModules:null}:Jo={context:e,transports:[new li],minLevel:"info",debugModules:null};}function Qc(){return Jo.transports}function Vc(e,a){let{debugModules:o,minLevel:t}=Jo;return Jo.context==="tui"&&o&&o!=="all"?o.has(a)?vt[e]>=vt.debug:vt[e]>=vt.warn:vt[e]>=vt[t]}var vt,Jo,gn=H(()=>{"use strict";zc();Wc();Jc();mn();vt={debug:0,info:1,warn:2,error:3},Jo={context:"cli",transports:[],minLevel:"warn",debugModules:null};});function mi(e,a,o){if(!Vc(e,a))return;let t={level:e,module:a,message:nn(o),timestamp:new Date};for(let r of Qc())r.write(t);}function P(e){let a=_c.get(e);if(a)return a;let o={debug:t=>mi("debug",e,t),info:t=>mi("info",e,t),warn:t=>mi("warn",e,t),error:t=>mi("error",e,t)};return _c.set(e,o),o}var _c,Xc=H(()=>{"use strict";dn();gn();_c=new Map;});var I=H(()=>{"use strict";Xc();gn();dn();});function yh(e){return typeof e=="object"&&e!==null&&hn in e&&e[hn]===true}function bn(e){return {serialize(a){let o=JSON.stringify(a),t=e.encrypt(o),r={[hn]:true,envelope:t};return JSON.stringify(r,null," ")},deserialize(a){let o;try{o=JSON.parse(a);}catch{return fn.warn("[encryption] Config file contains unparseable data, treating as empty"),{}}if(yh(o))try{let t=e.decrypt(o.envelope);return JSON.parse(t)}catch(t){return fn.error(`[encryption] Decryption failed: ${t instanceof Error?t.message:"unknown error"}. Config will be treated as empty. Re-authentication may be required.`),{}}return fn.info("[encryption] Detected plaintext config \u2014 will encrypt on next write"),o}}}var fn,hn,vn=H(()=>{"use strict";I();fn=P("encryption"),hn="__encrypted__";});var yn,Dh,ha,yt,kn=H(()=>{"use strict";I();yn=promisify(execFile),Dh=promisify(exec),ha=P("encryption:macos-keyvault"),yt=class{static async isAvailable(){try{let{stdout:a}=await Dh("command -v security");return ha.debug(`security binary found at: ${a.trim()}`),!0}catch{return ha.debug("security binary not found in PATH"),!1}}async getSecret(a,o){try{ha.debug(`Looking up secret: service=${a}, account=${o}`);let{stdout:t}=await yn("security",["find-generic-password","-w","-a",o,"-s",a]),r=t.trim();return ha.debug(`security find-generic-password result: ${r?"found":"empty"}`),r||null}catch(t){let r=t;return ha.debug(`security find-generic-password failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),null}}async setSecret(a,o,t){try{ha.debug(`Storing secret: service=${a}, account=${o}`),await yn("security",["add-generic-password","-U","-a",o,"-s",a,"-w",t]),ha.debug("security add-generic-password succeeded");}catch(r){let i=r;throw ha.error(`security add-generic-password failed: code=${i.code}, stderr=${i.stderr?.trim()}, message=${i.message}`),r}}async deleteSecret(a,o){try{return ha.debug(`Deleting secret: service=${a}, account=${o}`),await yn("security",["delete-generic-password","-a",o,"-s",a]),ha.debug("security delete-generic-password succeeded"),!0}catch(t){let r=t;return ha.debug(`security delete-generic-password failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),!1}}getStoragePath(){return "macOS Keychain (security)"}};});function b(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 K(e){process.stdout.write(R.green(` \u2713 ${b(e)}
|
|
6
6
|
`));}function C(e){process.stderr.write(R.red(` \u2717 ${b(e)}
|
|
7
7
|
`));}function D(e){process.stdout.write(R.cyan(` \u2139 ${b(e)}
|
|
8
8
|
`));}function kt(e,a){let o=a.map(n=>n.map(b)),t=[e,...o],r=e.map((n,d)=>Math.max(...t.map(l=>(l[d]??"").length))),i=r.map(n=>"\u2500".repeat(n)).join(" "),s=n=>n.map((d,l)=>d.padEnd(r[l])).join(" ");process.stdout.write(`
|
|
@@ -13,16 +13,16 @@ import*as bt from'crypto';import {randomUUID,createHash}from'crypto';import*as L
|
|
|
13
13
|
`);}function go(e){process.stdout.write(JSON.stringify(e,null,2)+`
|
|
14
14
|
`);}function ye(e){process.stdout.write(JSON.stringify(e)+`
|
|
15
15
|
`);}function Fe(e){process.stderr.write(JSON.stringify(e)+`
|
|
16
|
-
`);}function $(e){return e instanceof Error?e.message:String(e)}function Ea(e){let a=new Date(e);return isNaN(a.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(a)}var j=H(()=>{"use strict";});async function
|
|
16
|
+
`);}function $(e){return e instanceof Error?e.message:String(e)}function Ea(e){let a=new Date(e);return isNaN(a.getTime())?"\u2014":new Intl.DateTimeFormat("en-US",{dateStyle:"short"}).format(a)}var j=H(()=>{"use strict";});async function Ah(e,a){let o=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,r=setInterval(()=>{process.stderr.write(`\r${o[t++%o.length]} ${e}`);},80);try{return await a()}finally{clearInterval(r),process.stderr.write("\r\x1B[2K");}}function xh(e){let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim().toLowerCase());});})}var Pn,Dn,Rh,oe,fo,wn=H(()=>{"use strict";I();j();Pn=promisify(execFile),Dn=promisify(exec),Rh=[{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"}],oe=P("encryption:linux-keyvault");fo=class e{static async isAvailable(){try{let{stdout:a}=await Dn("command -v secret-tool");oe.debug(`secret-tool found at: ${a.trim()}`);}catch{return oe.debug("secret-tool binary not found in PATH"),!1}try{return await Pn("secret-tool",["lookup","service","__flow_connectivity_check__"]),oe.debug("Secret Service D-Bus connectivity check passed"),!0}catch(a){let t=a.stderr?.trim()??"";return t.includes("org.freedesktop.secrets")?(oe.debug(`Secret Service D-Bus not available: ${t}`),!1):(oe.debug("secret-tool is available and D-Bus service is reachable"),!0)}}static async detectPackageManager(){for(let a of Rh)try{return await Dn(`command -v ${a.name}`),a}catch{}return null}static async ensureInstalled(){if(await e.isAvailable())return !0;oe.info("Secure credential storage requires 'secret-tool' (libsecret). This tool allows us to store your encryption key in the OS keyring, so your credentials are protected even if someone copies the config file.");let a=await e.detectPackageManager();if(!a)return oe.warn("Could not detect a supported package manager. Please install libsecret manually."),!1;let o=await xh(" ? Install secret-tool? This requires sudo. (y/N) ");if(o!=="y"&&o!=="yes")return !1;try{return oe.info(`Running: ${a.command}`),await Ah("Installing secret-tool...",()=>Dn(a.command)),e.isAvailable()}catch{return oe.warn("Installation failed. Falling back to derived key."),!1}}async getSecret(a,o){try{oe.debug(`Looking up secret: service=${a}, account=${o}`);let{stdout:t}=await Pn("secret-tool",["lookup","service",a,"account",o]),r=t.trim();return oe.debug(`secret-tool lookup result: ${r?"found":"empty"}`),r||null}catch(t){let r=t;return oe.debug(`secret-tool lookup failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),null}}async setSecret(a,o,t){oe.debug(`Storing secret: service=${a}, account=${o}`),oe.debug(`Environment: DBUS_SESSION_BUS_ADDRESS=${process.env.DBUS_SESSION_BUS_ADDRESS??"NOT SET"}`),oe.debug(`Environment: DISPLAY=${process.env.DISPLAY??"NOT SET"}, WAYLAND_DISPLAY=${process.env.WAYLAND_DISPLAY??"NOT SET"}`),oe.debug(`Environment: WSL_DISTRO_NAME=${process.env.WSL_DISTRO_NAME??"NOT SET"}`),await new Promise((r,i)=>{let s=spawn("secret-tool",["store","--label",a,"service",a,"account",o]),n="";s.stderr.on("data",d=>{n+=d.toString();}),s.stdin.end(t,"utf8"),s.on("close",d=>{d===0?(oe.debug("secret-tool store succeeded"),r()):(oe.error(`secret-tool store failed: code=${d}, stderr=${n.trim()}`),i(new Error(`secret-tool exited with code ${d}${n?`: ${n.trim()}`:""}`)));}),s.on("error",d=>{oe.error(`secret-tool store spawn error: ${d.message}`),i(d);});});}async deleteSecret(a,o){try{return oe.debug(`Deleting secret: service=${a}, account=${o}`),await Pn("secret-tool",["clear","service",a,"account",o]),oe.debug("secret-tool clear succeeded"),!0}catch(t){let r=t;return oe.debug(`secret-tool clear failed: code=${r.code}, stderr=${r.stderr?.trim()}, message=${r.message}`),!1}}getStoragePath(){return "Linux Secret Service (secret-tool)"}};});function Cn(e,a){return `${e}:${a}`}function cr(e){return e.replace(/'/g,"''")}function gi(e){return ["-NoProfile","-NonInteractive","-Command",e]}function Fh(e){return `Add-Type -TypeDefinition @'
|
|
17
17
|
${Rn}
|
|
18
18
|
'@
|
|
19
|
-
[FlowCredManager]::Read('${cr(e)}')`}function
|
|
19
|
+
[FlowCredManager]::Read('${cr(e)}')`}function Oh(e,a,o){return `Add-Type -TypeDefinition @'
|
|
20
20
|
${Rn}
|
|
21
21
|
'@
|
|
22
|
-
[FlowCredManager]::Write('${cr(e)}', '${cr(a)}', '${cr(o)}')`}function
|
|
22
|
+
[FlowCredManager]::Write('${cr(e)}', '${cr(a)}', '${cr(o)}')`}function Nh(e){return `Add-Type -TypeDefinition @'
|
|
23
23
|
${Rn}
|
|
24
24
|
'@
|
|
25
|
-
[FlowCredManager]::Delete('${cr(e)}')`}async function fi(e){return
|
|
25
|
+
[FlowCredManager]::Delete('${cr(e)}')`}async function fi(e){return Th("powershell.exe",e)}var Th,ba,Sn,Mh,qh,Lh,Rn,Pt,An=H(()=>{"use strict";I();Th=promisify(execFile),ba=P("encryption:windows-keyvault"),Sn=1,Mh=1,qh=2,Lh=3;Rn=`
|
|
26
26
|
using System;
|
|
27
27
|
using System.Runtime.InteropServices;
|
|
28
28
|
using System.Text;
|
|
@@ -72,7 +72,7 @@ public class FlowCredManager {
|
|
|
72
72
|
byte[] bytes = Encoding.UTF8.GetBytes(secret);
|
|
73
73
|
IntPtr targetPtr = Marshal.StringToHGlobalUni(target);
|
|
74
74
|
IntPtr userPtr = Marshal.StringToHGlobalUni(userName);
|
|
75
|
-
int[] persistLevels = new int[] { ${
|
|
75
|
+
int[] persistLevels = new int[] { ${qh}, ${Lh}, ${Mh} };
|
|
76
76
|
int lastErr = 0;
|
|
77
77
|
try {
|
|
78
78
|
foreach (int persist in persistLevels) {
|
|
@@ -102,30 +102,30 @@ public class FlowCredManager {
|
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
`;Pt=class{static async isAvailable(){try{let{stdout:a}=await fi(gi('Write-Output "ok"')),o=a.trim()==="ok";return ba.debug(`PowerShell availability check: ${o?"available":"unexpected output"}`),o}catch(a){let o=a instanceof Error?a.message.split(`
|
|
105
|
-
`)[0]:"unknown error";return ba.debug(`PowerShell not available: ${o}`),!1}}async getSecret(a,o){try{let t=Cn(a,o);ba.debug(`Looking up secret: target=${t}`);let r=
|
|
106
|
-
`)[0]:"unknown error";return ba.error(`Failed to read secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),null}}async setSecret(a,o,t){try{let r=Cn(a,o);ba.debug(`Storing secret: target=${r}`);let i=
|
|
107
|
-
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${a}", account="${o}"]: ${i}`;throw ba.error(s),new Error(s)}}async deleteSecret(a,o){try{let t=Cn(a,o);ba.debug(`Deleting secret: target=${t}`);let r=
|
|
108
|
-
`)[0]:"unknown error";return ba.debug(`Failed to delete secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function
|
|
105
|
+
`)[0]:"unknown error";return ba.debug(`PowerShell not available: ${o}`),!1}}async getSecret(a,o){try{let t=Cn(a,o);ba.debug(`Looking up secret: target=${t}`);let r=Fh(t),{stdout:i}=await fi(gi(r)),s=i.trim();return ba.debug(`CredRead result: ${s?"found":"empty"}`),s||null}catch(t){let r=t instanceof Error?t.message.split(`
|
|
106
|
+
`)[0]:"unknown error";return ba.error(`Failed to read secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),null}}async setSecret(a,o,t){try{let r=Cn(a,o);ba.debug(`Storing secret: target=${r}`);let i=Oh(r,t,o),{stdout:s}=await fi(gi(i)),n=s.trim();if(n.startsWith("OK:")){let l=n.split(":")[1];ba.debug(`CredWrite succeeded (persist=${l})`);return}let d=n.startsWith("ERR:")?n.split(":")[1]:"unknown";throw new Error(`CredWrite failed with Win32 error ${d}`)}catch(r){let i=r instanceof Error?r.message.split(`
|
|
107
|
+
`)[0]:"unknown error",s=`Failed to store secret in Windows Credential Manager [service="${a}", account="${o}"]: ${i}`;throw ba.error(s),new Error(s)}}async deleteSecret(a,o){try{let t=Cn(a,o);ba.debug(`Deleting secret: target=${t}`);let r=Nh(t),{stdout:i}=await fi(gi(r)),s=i.trim()==="True";return ba.debug(`CredDelete result: ${s}`),s}catch(t){let r=t instanceof Error?t.message.split(`
|
|
108
|
+
`)[0]:"unknown error";return ba.debug(`Failed to delete secret from Windows Credential Manager [service="${a}", account="${o}"]: ${r}`),!1}}getStoragePath(){return "Windows Credential Manager (PowerShell)"}};});function Uh(){let e=`${Le.hostname()}${Le.userInfo().username}`;return bt.scryptSync(e,Bh,Gh)}function zh(){let e=Uh(),a=new sr(e),o=bn(a);return new xn({projectName:En,serialize:o.serialize,deserialize:o.deserialize,configFileMode:384})}function hi(){return bi||(bi=zh()),bi}var Gh,Bh,En,jh,bi,Ve,lr=H(()=>{"use strict";sn();vn();Gh=32,Bh="flow-plugins-cli-fallback",En="flow-plugins-cli-fallback",jh={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)"};bi=null;Ve=class{warned=!1;async getSecret(a,o){return hi().get(`${a}:${o}`)??null}async setSecret(a,o,t){if(!this.warned){let r=jh[process.platform]??"ensure the OS keyring is available";process.stderr.write(`\u26A0 Secure keyring unavailable. Credentials are stored in an encrypted file
|
|
109
109
|
using a machine-derived key. For stronger security, ${r}.
|
|
110
|
-
`),this.warned=!0;}hi().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=hi(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return hi().path}static hasExistingData(){try{let a=new xn({projectName:En});return we.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new xn({projectName:En});we.rmSync(a.path,{force:!0});}catch{}bi=null;}};});async function In(){if(Ve.hasExistingData())return new Ve;switch(process.platform){case "darwin":return await yt.isAvailable()?new yt:new Ve;case "linux":return await fo.isAvailable()?new fo:await fo.ensureInstalled()?new fo:new Ve;case "win32":return await Pt.isAvailable()?new Pt:new Ve;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var el=H(()=>{"use strict";kn();wn();An();lr();});var al=H(()=>{"use strict";sn();vn();el();kn();wn();An();lr();});async function ho(){return ki||(ki=In()),ki}function Pi(){ki=null;}async function Y(){let a=await(await ho()).getSecret(Xa,Tn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function bo(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw ol.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await ho()).setSecret(Xa,Tn,JSON.stringify(e));}async function tl(){let e=await ho();await e.deleteSecret(Xa,Tn),await e.deleteSecret(Xa,Mn),await e.deleteSecret(Xa,qn);}async function rl(){return (await ho()).getStoragePath()}async function il(e){await(await ho()).setSecret(Xa,Mn,JSON.stringify(e));}async function Di(){let a=await(await ho()).getSecret(Xa,Mn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function wi(e){await(await ho()).setSecret(Xa,qn,JSON.stringify(e));}async function Dt(){let a=await(await ho()).getSecret(Xa,qn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function vo(){let e=await Di();return e?new Date(e.expiresAt)>new Date:false}function Ia(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,ol.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var ol,Xa,Tn,Mn,qn,ki,Se=H(()=>{"use strict";al();I();ol=P("config:credentials"),Xa="flow-plugins-cli",Tn="credentials",Mn="token-cache",qn="user-info",ki=null;});function wt(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Si=H(()=>{"use strict";});function Uh(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Ln(e){if(sl.some(o=>o.test(e)))return true;let a=Uh(e);return !!(a&&sl.some(o=>o.test(a)))}function zh(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Ta(e,a){let o=zh(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Ln(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var sl,Ho=H(()=>{"use strict";sl=[/^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 Hh(e){if(!_a.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function Qh(e){if(e instanceof HTTPError){let a=e.response.status;Fn.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&nl[o]?new Error(nl[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Fn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Fn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qo(e){let a=Ta("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Hh(e.tenant);let o;try{o=await Au.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await Qh(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await bo(e),await il({accessToken:o.access_token,expiresAt:t});let r=wt(o.access_token);await wi({sub:r.sub,name:r.name,email:r.email});}var Fn,nl,Ci=H(()=>{"use strict";Se();Si();Ho();I();U();Fn=P("api:auth");nl={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 Ma(){if(await vo()){let t=await Di();if(t)return t.accessToken}dl.debug("Token expired or missing, re-authenticating...");let a=await Y();if(!a)throw new Error("Not authenticated. Run: flow auth login");Ve.clearFallbackFile(),Pi(),await Qo(a);let o=await Di();if(!o)throw new Error("Authentication succeeded but token was not persisted");return dl.debug("Token refreshed successfully"),o.accessToken}var dl,St=H(()=>{"use strict";Se();Ci();lr();I();dl=P("lib:tokenProvider");});function Ya(){return Au.create({prefix:Ta("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Ma();e.headers.set("Authorization",`Bearer ${a}`);let o=await Y();o?.tenant&&_a.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var Cr=H(()=>{"use strict";Ho();Se();St();U();});function Mt(e,a){let o=Ya();return a?o.get(e,{searchParams:{source:a}}):o.get(e)}async function qt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var rd=H(()=>{"use strict";Cr();});function Rr(e){if(!e||!Jv.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Lt(e){return Hv.test(e)}function Ft(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function sd(e){if(!Qv.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 Ot(e,a){let o=Ft(e);sd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function es(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!Vv.test(a)&&!_v.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var Jv,Hv,Qv,Vv,_v,xo=H(()=>{"use strict";Jv=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;Hv=/^[^@]+@[^@]+$/;Qv=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;Vv=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,_v=/^https:\/\/[\w./:@?&=+#%-]+$/;});var wu={};Mc(wu,{FlowApiAdapter:()=>Nt});var Xv,Nt,nd=H(()=>{"use strict";Cr();rd();I();xo();Xv=P("catalog.flow-api"),Nt=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Mt("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await qt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Rr(a);try{return await Mt(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await qt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await Ya().head("v1/plugins/catalog"),Xv.debug("ping ok"),!0}catch{return !1}}};});function $v(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Cu(){return Su??=$v(),Su}var Su,Ru=H(()=>{"use strict";});var Eu={};Mc(Eu,{GitRepoAdapter:()=>Gt});function xu(e,a){if(!Yv.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var Yv,Gt,dd=H(()=>{"use strict";Ru();Ho();Yv=/^[a-zA-Z0-9_.-]+$/;Gt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Ln(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return xu(n,"owner"),xu(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Au.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Au.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Cu();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var Lc=new Set(["skill","mcp","bundle","plugin"]),y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Lc),origins:new Set(rn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(Lc)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(rn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Se();St();Si();U();Ho();I();var Ri=P("api:metrics");function cl(){return Ta("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ll(e,a,o){return Au.post(e,{json:a,headers:o})}async function _h(e){let a=await Dt();if(a)return a;let o=wt(e),t={sub:o.sub,name:o.name,email:o.email};return await wi(t),t}async function S(e,a){let o=await Ma(),t=await _h(o),r=await Y();if(!_a.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:tn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await ll(cl(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Ri.debug(`Metrics event sent: ${e}`);}catch(s){throw Ri.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function ul(e,a,o){try{let t=o&&_a.test(o)?o:"unknown",r={action:e,booster:tn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ll(cl(),r,{FlowTenant:t}),Ri.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Ri.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var Xh={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},va={...Xh};function pl(e){let a=Date.now();va={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Vo(e){va.currentStep=e,va.stepStart=Date.now();}function Z(){return {...va}}function yo(){return va.sessionStart===0?0:Date.now()-va.sessionStart}function _o(){return va.stepStart===0?0:Date.now()-va.stepStart}function ml(){va.tuiSessionStart=Date.now();}function gl(){return va.tuiSessionStart===0?0:Date.now()-va.tuiSessionStart}I();var Kh=3e3,$h=P("abandonment");async function Ai(e){let{currentStep:a,sessionStart:o}=Z();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:yo()};try{await Promise.race([S(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Kh))]);}catch(r){$h.warn(`Abandonment event failed: ${String(r)}`);}}function fl(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var Yh=3e3,Zh=P("session-end");async function pr(e,a,o){let t=gl(),i=[S(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(Ai(e));try{await fl(Promise.all(i).then(()=>{}),Yh);}catch(s){Zh.warn(`Session end event failed: ${String(s)}`);}}var tb=2e3;function bl(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),pr("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},tb);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var nb=16;function vl({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(nb)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function yl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();ft.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:ht}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function kl({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function Pl(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[mo," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Ci();U();function $o(){return De__default.join(Le__default.homedir(),".claude","settings.json")}function wl(e){return `${(e&&e.trim().length>0?e.trim():ai).replace(/\/+$/,"")}/flow-litellm/`}function yr(){let e=$o();if(!we__default.existsSync(e))return {status:"missing"};let a=we__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function Ei(e){let a=$o();we__default.mkdirSync(De__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;we__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,a);}function Sl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function zn(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Cl(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var gb=3600,Yo=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function kr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function fb(e){return mb.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:gb})}function Ii(e,a={}){let o=yr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new Yo;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?zn(o.settings):null,i=o.status==="ok"?Cl(o.settings):null,s=a.jwtOverride??fb(e),n=wl(e.customUrl),d=Sl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function Ti(e){Ei(e.merged);}function Rl(){let e=yr();return e.status!=="ok"?false:zn(e.settings)!==null}Se();He();function hb(){let e=Uc();if(!we__default.existsSync(e))return {};try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return {}}}var Wn=null;function bb(){return Wn===null&&(Wn=hb()),Wn}function Do(){return !!bb().ENABLE_EXPERIMENTAL_BETAS}U();function Pb(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function xl(e){let a=Pb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Mi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=De__default.join(Le__default.homedir(),".claude","settings.json"),o=we__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??ai),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},Db={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=Do()?[Mi,Db]:[Mi];Se();I();var Rb=P("moduleState");function Li(){let e=process.env.FLOW_HOME??De__default.join(Le__default.homedir(),".flow");return De__default.join(e,"modules.json")}var Ab={retries:5,minTimeout:50};async function El(e,a){we__default.mkdirSync(De__default.dirname(e),{recursive:true});let o=await Cb.lock(e+".lock",{realpath:false,retries:Ab});try{return await a()}finally{await o();}}function Il(){let e=Li();if(!we__default.existsSync(e))return [];try{let a=JSON.parse(we__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(Rb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),we__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return we__default.rmSync(e,{force:true}),[]}}function Zo(){return Il()}function Tl(e){let a=Li();we__default.mkdirSync(De__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};we__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,a);}function ta(e){return Zo().find(a=>a.alias===e)??null}async function ya(e){let a=Li();await El(a,async()=>{let o=Il(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,Tl(o);});}async function et(){let e=Li();we__default.existsSync(e)||await El(e,async()=>{we__default.existsSync(e)||Tl([]);});}var Ib=promisify(execFile);function wo(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function La(e){let a=process.platform==="win32"?"where":"which";try{return await Ib(a,[e]),!0}catch{return false}}function Ka(){return process.platform==="win32"?"npm.cmd":"npm"}var Ml=promisify(execFile),Rt=class{type="npm";async isAvailable(){return La("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=wo(a,"npm");if(!o)return null;try{let{stdout:t}=await Ml(Ka(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=wo(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await Ml(Ka(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Fi=promisify(execFile),Fb=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Oi=class{type="homebrew";async isAvailable(){return La("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=wo(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=wo(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Fi("brew",["tap",r.tap]),await Fi("brew",["trust",r.tap])),await Fi("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Fi("brew",["list","--versions",a]),t=o.trim().match(Fb);return t?t[2]:null}catch{return null}}};var At=promisify(execFile),Ll=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Fl(){let e=process.env.FLOW_HOME??De__default.join(Le__default.homedir(),".flow");return De__default.join(e,"bin")}var Ni=class{type="curl";async isAvailable(){return La("curl")}async install(a){let o=Date.now(),t=wo(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=De__default.join(Fl(),De__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await At(t,["--version"]),i=r.match(Ll);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=De__default.join(Le__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await At("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{we__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return we__default.chmodSync(i,448),await At("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{we__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=Fl(),s=De__default.join(i,De__default.basename(t.binaryName)),n=false;try{if(we__default.mkdirSync(i,{recursive:!0}),n=!0,await At("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return we__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}we__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await At(s,["--version"]),c=l.match(Ll);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{we__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=De__default.join(Le__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await At("curl",["-L","--fail","-o",t,o]);let r=we__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=we__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{we__default.unlinkSync(t);}catch{}}}};I();var Ol="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Ol=e.version);}catch{}var te=Ol;var Ee=P("moduleInstaller");function Oa(e){switch(e){case "npm":return new Rt;case "homebrew":return new Oi;case "curl":return new Ni}}async function Pr(e,a,o){try{await S(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Ee.warn(`Failed to emit install failed event: ${String(t)}`);}}async function Co(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Ee.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=Oa(o),l=false;try{l=await d.isAvailable();}catch(u){Ee.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await S(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:te,trigger:a});}catch(u){Ee.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let m=u instanceof Error?u.message:String(u);Ee.warn(`${o} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-s};}if(c.success){await ya({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await S(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(p){Ee.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:u,failed:m}=await zb(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Pr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function zb(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Y(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Ee.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Ee.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Ee.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Ee.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Gi(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=Oa(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await S(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:te,trigger:"command"});}catch(n){Ee.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Ee.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await ya({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await S(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Ee.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await S(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Ee.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await S(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Ee.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Bi=P("flowAiObsSetup");async function ji(e,a){try{if(!await new Rt().isAvailable().catch(()=>!1))return Bi.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await Co(Mi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Bi.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Bi.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Bi.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function Nl(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var Wb=P("useAuthSetup");function Gl(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,m]=useState("fields"),[p,h]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:v,setJustAuthenticated:k}=oa(),T=()=>{m("fields"),h(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{S(w.CLI_SESSION_STARTED,{cli_version:te,os:process.platform,node_version:process.version,duration_ms:yo(),interface:"tui"}).catch(()=>{});},A=async W=>{g.current=true;let _={...o.current,customUrl:t.current??void 0};try{W&&Ti(W),await bo(_);}catch(Q){d(Q instanceof Error?Q.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:E,...B}=_;v(B),k(true),L(),await ji(t.current,r.current).catch(Q=>Wb.warn(`installFlowAiObs threw unexpectedly: ${String(Q)}`)),Ui({starterKit:B.starterKit});},M=async()=>A(),F=async W=>A(W),O=W=>{try{let _={...o.current,customUrl:t.current??void 0};return Ii(_,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(_){return _ instanceof Yo?(m("malformedConfirm"),null):(d(_ instanceof Error?_.message:"Failed to read settings.json"),m("fields"),null)}},ae=()=>{let W=O(true);W&&(h(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let _;try{_=kr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=_,m("customUrl");},J=W=>{t.current=W,m("email");},ee=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&Ia(W),c(true),d(null),f.current+=1;try{await Qo(o.current);let _=O(!1);_&&(h(_),m("preview"));}catch(_){let E=_ instanceof Error?_.message:"Authentication failed";d(E),ul(w.CLI_AUTH_FAILED,{error_code:Nl(_),attempt:f.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:p,isCommittingRef:g,setJwtValue:a,setJwtError:s,cancelToFields:T,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ee,commitAndProceed:F,skipJwtAndProceed:M,planPersistOverwrite:ae}}U();j();function Bl(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:h,planPersistOverwrite:f}=Gl(),[g,v]=useState("confirm"),[k,T]=useState(""),L=useRef(""),[A,M]=useState(false);return useEffect(()=>{r==="customUrl"&&(v("confirm"),L.current="",T(""),M(false));},[r]),useInput((F,O)=>{if(!(t||s.current)){if(r==="preview"){O.return&&i?p(i):O.escape?h():F==="q"&&l();return}if(r==="malformedConfirm"){O.return?f():O.escape&&l();return}if(r==="customUrl"){if(g==="confirm")F==="y"||F==="Y"?v("input"):(F==="n"||F==="N"||O.return)&&u(null);else if(O.escape)L.current="",T(""),v("confirm");else if(O.return){let ae=L.current.trim();ae.length>0&&mt.test(ae)?(M(false),u(ae)):ae.length>0&&M(true);}else O.backspace||O.delete?(L.current=L.current.slice(0,-1),T(L.current)):F&&!O.ctrl&&!O.meta&&(L.current=L.current+F,T(L.current),M(false));return}r!=="email"&&O.return&&c();}},{isActive:true}),r==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&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:k}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:gt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(yl,{onConfirm:m})]}):r==="preview"&&i?jsx(kl,{plan:i}):r==="malformedConfirm"?jsx(Pl,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \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(vl,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",b(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Et(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(_b,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",te]})})]})}var Wl=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=Do()?Wl:Wl.slice(0,3);function Xb(e){return re.findIndex(a=>a.id===e)}function Qn(e,a,o){let t=Xb(o.activeTab);if(a.rightArrow||a.tab){let r=re[(t+1)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=re[(t-1+re.length)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:re[t]?.focus??"list"}]:[]}var Ql={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Vl({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${Ql[o]} (${e})`:Ql[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Xl(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var Zb=["skill","mcp","bundle"].map((e,a)=>({key:String(a+2),type:e,...pt[e]})),ev=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...qc[e]}));function Kl(){let e=y(t=>t.catalogFilters),a=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),o=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:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),Zb.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),ev.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function $l({type:e}){let{label:a,color:o}=pt[e];return jsx(Text,{color:o,children:a})}U();function eu({origin:e}){return e===ir?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}j();var Wi=tv.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx($l,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(eu,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Ea(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function It({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function tu({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(It,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(Wi,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function su({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function du({groups:e,emptyMessage:a}){let o=y(p=>p.selectedIndex),t=[],r=0;for(let p of e){t.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let h of p.items)t.push({kind:"item",item:h,itemIndex:r,key:`i-${p.scope}-${h.name}-${h.marketplace??""}`}),r++;}if(r===0)return jsx(It,{message:a});let s=t.findIndex(p=>p.kind==="item"&&p.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,m=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(su,{label:p.label,pathHint:p.pathHint},p.key):jsx(Wi,{item:p.item,isSelected:p.itemIndex===o},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var uv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function pv({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(Xl,{}),jsx(Kl,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:uv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(du,{groups:t,emptyMessage:o}):jsx(tu,{items:e,emptyMessage:o})]})}function cu({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(pv,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var fv={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 Ji(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[fv[e],a?" | Ctrl+D: debug log":""]})})}j();function lu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",b(e)]})}):null}function Hi({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Zn(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var gu=20;function Qi(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*gu),i="\u2588".repeat(r)+"\u2591".repeat(gu-r),s=`${Zn(e)} / ${Zn(a)}`;return {bar:i,percent:t,label:s}}function Vi({received:e,total:a}){let{bar:o,percent:t,label:r}=Qi(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function _i({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var td=Object.entries(Va),vu=[...td.map(([,e])=>e.actionLabel),"Cancel"],yu=Object.fromEntries(td.map(([,e])=>[e.actionLabel,e.description]));function ku(e){let a=td.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var Iv=P("provider.registry"),Tv=3e4,Ki=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+Tv}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&Iv.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var Mv={user:"global",project:"project",local:"local"};function $i(e){return e?Mv[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Ao=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};Cr();rd();I();var Fv=P("catalog.registry"),Yi=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);Fv.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};He();var Wv={retries:5,minTimeout:50};async function id(e,a){mkdirSync(dirname(e),{recursive:true});let o=await Cb.lock(e+".lock",{realpath:false,retries:Wv});try{return await a()}finally{await o();}}var Zi=class{filePath;constructor(a){this.filePath=a??jc();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await id(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await id(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await id(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};nd();var pe=new Yi,Za=new Zi,Zv=["flow-harness"];function ey(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?Zv:e.split(",").map(a=>a.trim()).filter(Boolean)}pe.register(new Nt);for(let e of ey())pe.register(new Nt(e));var Iu=false;async function Tu(){if(Iu)return;Iu=true;let e=await Za.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(dd(),Eu));for(let o of e)pe.register(new a(o.id,o.name,o.source));}xo();var Mu=2;async function eo(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(nd(),wu));return new a(e).fetchItems()}return pe.fetchAll()}async function qu(){return pe.fetchAllWithErrors()}async function Bt(e,a){Rr(e);try{return await Mt(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await qt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function Lu(e,a,o){Rr(e);try{let t=await Mt(`v1/plugins/${e}/archive`,o),r=t.headers.get("x-archive-size"),i=r?Number(r):NaN,s=Number.isFinite(i)&&i>0?i:0,n=s>0,d=t.body;if(!d)throw new Error("Failed to download plugin: response has no body");let l=d.getReader(),c=[],u=0;for(;;){let{done:m,value:p}=await l.read();if(m)break;if(u+=p.byteLength,n&&u>s*Mu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*Mu}`);c.push(p),n&&a?.(u,s);}return Buffer.concat(c)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await qt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function as(){try{let{profiles:e}=await Ya().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}}He();He();async function Fu(e,a){let o=De.resolve(a);await Na.mkdir(o,{recursive:true});let t=De.join(De.dirname(o),`${randomUUID()}.zip`);try{await Na.writeFile(t,e);let r=await oy.Open.file(t),i=De.normalize(o+De.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=De.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(De.resolve(De.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await Na.unlink(t);}catch{}}}async function cd(e){await Na.rm(e,{recursive:true,force:true});}async function Eo(){let e=Gc();await Na.mkdir(De.dirname(e),{recursive:true});try{await Na.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await Cb.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}He();U();function iy(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||le,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Gu(e){let a=ii(e);if(!we__default.existsSync(a))return null;try{return JSON.parse(we__default.readFileSync(a,"utf-8"))}catch{return null}}function sy(e){let a=Gu(e);if(a)return a;let o=iy(e),t=ii(e);return we__default.mkdirSync(De__default.dirname(t),{recursive:true}),ld(o,e),o}function ld(e,a){let o=ii(a),t=`${o}.${randomUUID()}.tmp`;we__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(t,o);}function ny(e){let a=e||le,o=Uo(),t={};try{we__default.existsSync(o)&&(t=JSON.parse(we__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:Nc(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;we__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(r,o);}function Bu(e,a,o){wa(e.name),ny(o);let t=cn(e.name,o);we__default.mkdirSync(De__default.dirname(t),{recursive:true});try{we__default.lstatSync(t),we__default.rmSync(t,{recursive:!0,force:!0});}catch{}we__default.cpSync(a,t,{recursive:true,dereference:true});let r=sy(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),ld(r,o));}function ud(e,a){wa(e);let o=cn(e,a);try{we__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=Gu(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&ld(t,a);}j();I();var cy=P("mcpConfigReader"),ly=500,uy=512;function py(){return De__default.join(Le__default.homedir(),".claude.json")}function my(){return De__default.join(process.cwd(),".mcp.json")}function Uu(e){if(!we__default.existsSync(e))return null;try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return cy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pd(e){if(!Ar(e))return {};let a=e.mcpServers;return Ar(a)?a:{}}function md(e,a){return Object.keys(e).slice(0,ly).map(t=>({name:b(t.slice(0,uy)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Wu(){let e=[],a=py(),o=Uu(a);if(Ar(o)){let n=o,d=pd(n);e.push(...md(d,"user"));let l=process.cwd();if(Ar(n.projects)){let c=n.projects[l];if(Ar(c)){let u=pd(c);e.push(...md(u,"local"));}}}let t=my(),r=Uu(t),i=pd(r);e.push(...md(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var ia=P("storage");async function fy(e,a,o){try{await S(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:Z().interfaceType});}catch(t){ia.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function hy(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;S(t,{tool_id:e,source:o,interface:Z().interfaceType}).catch(r=>ia.warn(`Failed to send ${a} metrics: ${String(r)}`));}function bd(){return De__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function by(){return De__default.join(Le__default.homedir(),".claude","plugins")}function os(e){let a;try{a=we__default.realpathSync(e);}catch{a=De__default.resolve(e);}let o=De__default.resolve(by()),t=De__default.resolve(De__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+De__default.sep),i=a.startsWith(t+De__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Hu(e="user"){return e==="local"?De__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?De__default.join(process.cwd(),".claude","settings.json"):De__default.join(Le__default.homedir(),".claude","settings.json")}function Ce(){let e=bd();if(!we__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function vd(){let e=bd();try{let a=await we__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function vy(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function Qu(e,a){try{we__default.mkdirSync(De__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;we__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,e);}catch(o){throw vy(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function sa(e){Qu(bd(),e);}function xr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function yy(e,a){let o=De__default.join(e,".claude-plugin"),t=De__default.join(o,"plugin.json");if(we__default.existsSync(t))try{return JSON.parse(we__default.readFileSync(t,"utf-8"))}catch{return null}let r=De__default.join(o,"marketplace.json");if(we__default.existsSync(r))try{let i=JSON.parse(we__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function yd(e="user"){let a=Hu(e);if(!we__default.existsSync(a))return {};try{return JSON.parse(we__default.readFileSync(a,"utf-8"))}catch{return {}}}function Vu(e,a="user"){Qu(Hu(a),e);}function ky(e,a){let{name:o,marketplace:t}=xr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>xr(s).name===o)[0],!r)throw ia.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function Py(e,a){let{name:o,marketplace:t}=xr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>xr(s).name===o)[0],r?{key:r,name:o}:null}function gd(e="user"){return yd(e).enabledPlugins??{}}function fd(e,a="user"){let o=yd(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,Vu(o,a);}function Er(e,a,o="user"){let t=yd(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},Vu(t,o);}function Dy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function ne(){let e=Ce(),a=gd(),o=gd("project"),t=gd("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:m}=xr(l),p=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return Dy(p).map(f=>{let g=yy(f.installPath,u),k=(r[f.scope]??a)[l];return {name:u,marketplace:m,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:g?.description,author:g?.author,status:k===false?"disabled":"enabled"}})}),s=Wu(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function Ju(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Ir(e,a){ia.debug(`[${e}] Acquiring lock to uninstall`);let o=await Eo();try{let t=Ce(),r=Py(e,t.plugins);if(!r)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);ia.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),os(d.installPath);let l=De__default.dirname(d.installPath);os(l),ia.debug(`[${s}] Removing directory: ${l}`),we__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...m}=t.plugins;sa({...t,plugins:m}),fd(i,a),ud(s,Ju(i));}else t.plugins[i]=c,sa(t),fd(i,a);}else {ia.debug(`[${s}] Resolved key: ${i}`);for(let c of n){os(c.installPath);let u=De__default.dirname(c.installPath);os(u),ia.debug(`[${s}] Removing directory: ${u}`),we__default.rmSync(u,{recursive:!0,force:!0}),fd(i,c.scope);}ud(s,Ju(i));let{[i]:d,...l}=t.plugins;sa({...t,plugins:l});}await fy(s,n[0].origin??"internal",n[0].type??"skill"),ia.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Tr(e,a,o){ia.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Eo();try{let r=Ce(),{key:i,name:s}=ky(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";ia.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),Er(i,a==="enabled",d),hy(s,a,l),ia.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}U();I();var wy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Sy=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function wa(e){if(!wy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Cy(e){if(!Sy.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 Io=P("installer");function Ry(e,a,o){let t=`${e}@${o||le}`,i=Ce().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function Ay(e,a,o){o&&await cd(a);try{Io.debug(`[${a}] Extracting archive...`),await Fu(e,a);}catch(t){throw await cd(a),t}}function xy(e,a,o,t,r,i="claude-code",s){let n=Ce(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],sa(n),Er(e,true,t);}async function Ey(e,a,o,t,r,i){try{await S(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:Z().interfaceType});}catch(s){Io.warn(`Failed to send install metrics: ${String(s)}`);}}async function Iy(e,a,o,t){try{await S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(r){Io.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function Ge(e,a={}){let o=Date.now(),t=null;try{Io.debug(`[${e}] Acquiring lock...`),t=await Eo();let{pluginKey:r,alreadyInstalled:i}=Ry(e,a.force,a.source),{source:s}=a;Io.debug(`[${e}] Fetching manifest...`);let n=await Bt(e,s);wa(n.name),Cy(n.version),Io.debug(`[${e}] Downloading archive...`);let d=await Lu(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=Oc(n.name,n.version,a.source);await Ay(d,u,!!i&&!!a.force),xy(r,u,n.version,l,"internal",a.providerId,c),Bu(n,u,a.source);let m=Date.now()-o;Io.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:n.name,version:n.version,path:u,duration_ms:m};return a.skipMetrics||await Ey(n.name,n.version,m,$i(l),"internal",c),p}catch(r){throw await Iy(e,r,"internal",a.type??"skill"),Io.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();j();Se();St();I();var Ty=P("commands:helpers");async function me(){let e=await Y();if(!e)return C("Not authenticated. Run: flow auth login"),false;e.customUrl&&Ia(e.customUrl);try{await Ma();}catch(a){return Ty.debug(`Token validation failed: ${String(a)}`),C("Session expired. Run: flow auth login"),false}return true}async function de(e){let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function To(e){let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim());});})}var My="\x1B[A",qy="\x1B[B";function _u(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function Ly(e,a){return e.map((o,t)=>_u(o,t===a)).join(`
|
|
110
|
+
`),this.warned=!0;}hi().set(`${a}:${o}`,t);}async deleteSecret(a,o){let t=hi(),r=`${a}:${o}`;return t.has(r)?(t.delete(r),!0):!1}getStoragePath(){return hi().path}static hasExistingData(){try{let a=new xn({projectName:En});return we.existsSync(a.path)}catch{return !1}}static clearFallbackFile(){try{let a=new xn({projectName:En});we.rmSync(a.path,{force:!0});}catch{}bi=null;}};});async function In(){if(Ve.hasExistingData())return new Ve;switch(process.platform){case "darwin":return await yt.isAvailable()?new yt:new Ve;case "linux":return await fo.isAvailable()?new fo:await fo.ensureInstalled()?new fo:new Ve;case "win32":return await Pt.isAvailable()?new Pt:new Ve;default:throw new Error(`Unsupported platform: ${process.platform}`)}}var el=H(()=>{"use strict";kn();wn();An();lr();});var al=H(()=>{"use strict";sn();vn();el();kn();wn();An();lr();});async function ho(){return ki||(ki=In()),ki}function Pi(){ki=null;}async function Y(){let a=await(await ho()).getSecret(Xa,Tn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function bo(e){let{clientId:a,clientSecret:o,tenant:t}=e,r=[!a?.trim()&&"clientId",!o?.trim()&&"clientSecret",!t?.trim()&&"tenant"].filter(Boolean);if(r.length>0)throw ol.error(`missing or empty fields: ${r.join(", ")}`),new Error("Cannot save credentials: clientId, clientSecret, and tenant are required");await(await ho()).setSecret(Xa,Tn,JSON.stringify(e));}async function tl(){let e=await ho();await e.deleteSecret(Xa,Tn),await e.deleteSecret(Xa,Mn),await e.deleteSecret(Xa,qn);}async function rl(){return (await ho()).getStoragePath()}async function il(e){await(await ho()).setSecret(Xa,Mn,JSON.stringify(e));}async function Di(){let a=await(await ho()).getSecret(Xa,Mn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function wi(e){await(await ho()).setSecret(Xa,qn,JSON.stringify(e));}async function Dt(){let a=await(await ho()).getSecret(Xa,qn);if(!a)return null;try{return JSON.parse(a)}catch{return null}}async function vo(){let e=await Di();return e?new Date(e.expiresAt)>new Date:false}function Ia(e){let a=e.replace(/\/$/,"");process.env.AUTH_ENGINE_URL=`${a}/auth-engine-api/v2/api-key/token`,process.env.PROMPT_MANAGER_URL=`${a}/prompt-manager-api/`,process.env.METRICS_COLLECTOR_URL=`${a}/metrics-collector-api/`,ol.debug(`[customUrl] Service URLs overridden to base: ${a}`);}var ol,Xa,Tn,Mn,qn,ki,Se=H(()=>{"use strict";al();I();ol=P("config:credentials"),Xa="flow-plugins-cli",Tn="credentials",Mn="token-cache",qn="user-info",ki=null;});function wt(e){let a=e.split(".");if(a.length!==3)throw new Error(`Invalid JWT: expected 3 segments, got ${a.length}`);let o=a[1].replace(/-/g,"+").replace(/_/g,"/"),t=Buffer.from(o,"base64").toString("utf8");try{return JSON.parse(t)}catch{throw new Error("Invalid JWT: payload segment is not valid JSON")}}var Si=H(()=>{"use strict";});function Wh(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;let o=e.slice(1,-1).match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;let t=parseInt(o[1],16),r=parseInt(o[2],16);return `${t>>8&255}.${t&255}.${r>>8&255}.${r&255}`}function Ln(e){if(sl.some(o=>o.test(e)))return true;let a=Wh(e);return !!(a&&sl.some(o=>o.test(a)))}function Jh(e,a){let o=process.env[e]??a;if(!o)throw new Error(`Missing required environment variable: ${e}`);return o}function Ta(e,a){let o=Jh(e,a),t;try{t=new URL(o);}catch{throw new Error(`${e} must be a valid URL. Got: "${o}"`)}let r=process.env.NODE_ENV==="development";if(!r&&t.protocol!=="https:")throw new Error(`${e} must be an HTTPS URL. Got protocol: "${t.protocol}"`);if(t.username||t.password)throw new Error(`${e} must not contain embedded credentials (user:pass@host is not allowed)`);if(/^169\.254\./i.test(t.hostname)||/^metadata\.(google|azure)\.internal\.?$/i.test(t.hostname)||/^100\.(6[4-9]|[7-9]\d|1[0-2][0-7])\./i.test(t.hostname))throw new Error(`${e} must not point to a cloud metadata endpoint. Got: "${t.hostname}"`);if(!r&&Ln(t.hostname))throw new Error(`${e} must not point to a private/loopback address. Got: "${t.hostname}"`);return o}var sl,Ho=H(()=>{"use strict";sl=[/^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 Vh(e){if(!_a.test(e))throw new Error(`Invalid tenant value: "${e}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}async function _h(e){if(e instanceof HTTPError){let a=e.response.status;Fn.debug(`HTTP error during authentication [status=${a}]`);let o="";try{let t=await e.response.text(),r=JSON.parse(t);typeof r.error=="string"&&(o=r.error);}catch{}return o&&nl[o]?new Error(nl[o]):a===StatusCodes.UNAUTHORIZED||a===StatusCodes.FORBIDDEN||a===StatusCodes.INTERNAL_SERVER_ERROR?new Error("Invalid credentials"):a>=StatusCodes.BAD_REQUEST&&a<StatusCodes.INTERNAL_SERVER_ERROR?new Error("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}return e instanceof Error?(Fn.debug(`Non-HTTP error during authentication: ${e.message}`),e):(Fn.debug("Unknown error during authentication"),new Error("Authentication failed"))}async function Qo(e){let a=Ta("AUTH_ENGINE_URL","https://flow.ciandt.com/auth-engine-api/v2/api-key/token");Vh(e.tenant);let o;try{o=await Au.post(a,{headers:{FlowTenant:e.tenant},json:{clientSecret:e.clientSecret}}).json();}catch(i){throw await _h(i)}let t=o.expires_at??new Date(Date.now()+(o.expires_in??3600)*1e3).toISOString();await bo(e),await il({accessToken:o.access_token,expiresAt:t});let r=wt(o.access_token);await wi({sub:r.sub,name:r.name,email:r.email});}var Fn,nl,Ci=H(()=>{"use strict";Se();Si();Ho();I();U();Fn=P("api:auth");nl={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 Ma(){if(await vo()){let t=await Di();if(t)return t.accessToken}dl.debug("Token expired or missing, re-authenticating...");let a=await Y();if(!a)throw new Error("Not authenticated. Run: flow auth login");Ve.clearFallbackFile(),Pi(),await Qo(a);let o=await Di();if(!o)throw new Error("Authentication succeeded but token was not persisted");return dl.debug("Token refreshed successfully"),o.accessToken}var dl,St=H(()=>{"use strict";Se();Ci();lr();I();dl=P("lib:tokenProvider");});function Ya(){return Au.create({prefix:Ta("PROMPT_MANAGER_URL","https://flow.ciandt.com/prompt-manager-api/"),redirect:"error",hooks:{beforeRequest:[async({request:e})=>{let a=await Ma();e.headers.set("Authorization",`Bearer ${a}`);let o=await Y();o?.tenant&&_a.test(o.tenant)&&e.headers.set("FlowTenant",o.tenant);}]}})}var Cr=H(()=>{"use strict";Ho();Se();St();U();});function Mt(e,a){let o=Ya();return a?o.get(e,{searchParams:{source:a}}):o.get(e)}async function qt(e){if(!(e instanceof HTTPError))return null;try{let a=await e.response.clone().json(),{message:o}=a;return Array.isArray(o)?o.filter(Boolean).join("; ")||null:typeof o=="string"&&o?o:null}catch{return null}}var rd=H(()=>{"use strict";Cr();});function Rr(e){if(!e||!Qv.test(e))throw new Error(`Invalid plugin name: "${e}". Must be 1-64 chars, lowercase alphanumeric and hyphens only.`)}function Lt(e){return Vv.test(e)}function Ft(e){let a=e.indexOf("@");return a>0?e.slice(0,a):e}function sd(e){if(!_v.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 Ot(e,a){let o=Ft(e);sd(o);let t=["claude","plugin","install",o];return a&&t.push("--scope",a),t.join(" ")}function es(e){let a=e.trim();if(!a)throw new Error("No marketplace source provided.");if(!Xv.test(a)&&!Kv.test(a))throw new Error(`Invalid marketplace source: "${a}". Must be owner/repo or an https:// URL.`);return a}var Qv,Vv,_v,Xv,Kv,xo=H(()=>{"use strict";Qv=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;Vv=/^[^@]+@[^@]+$/;_v=/^[a-zA-Z0-9][a-zA-Z0-9._-]*(?:\/[a-zA-Z0-9][a-zA-Z0-9._-]*)?$/;Xv=/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/,Kv=/^https:\/\/[\w./:@?&=+#%-]+$/;});var wu={};Mc(wu,{FlowApiAdapter:()=>Nt});var $v,Nt,nd=H(()=>{"use strict";Cr();rd();I();xo();$v=P("catalog.flow-api"),Nt=class{id;name;source;removable=!1;contentSource;constructor(a){this.contentSource=a,this.id=a?`flow-api:${a}`:"flow-api",this.name=a?`Flow Marketplace (${a})`:"Flow Marketplace",this.source=process.env.PROMPT_MANAGER_URL??"";}async fetchItems(){try{let{plugins:a}=await Mt("v1/plugins/catalog",this.contentSource).json();return a.map(o=>({...o,catalogId:this.id,origin:o.origin??"internal",type:o.type??"bundle",...this.contentSource?{contentSource:this.contentSource}:{}}))}catch(a){let o=await qt(a);if(o)throw new Error(o);if(a instanceof HTTPError){let{status:t}=a.response;throw t===401||t===403?new Error("Authentication failed. Run: flow auth login"):new Error(`Failed to fetch plugin catalog: HTTP ${t}`)}throw a instanceof Error?a.name==="TimeoutError"||a.message.includes("timeout")?new Error("Request timed out while fetching plugin catalog"):new Error(`Failed to fetch plugin catalog: ${a.message}`):a}}async fetchManifest(a){Rr(a);try{return await Mt(`v1/plugins/${a}/manifest`,this.contentSource).json()}catch(o){let t=await qt(o);if(t)throw new Error(t);if(o instanceof HTTPError){let{status:r}=o.response;throw r===404?new Error(`Plugin '${a}' not found in catalog`):new Error(`Failed to fetch manifest: HTTP ${r}`)}throw o instanceof Error?new Error(`Failed to fetch manifest: ${o.message}`):o}}async ping(){try{return await Ya().head("v1/plugins/catalog"),$v.debug("ping ok"),!0}catch{return !1}}};});function Zv(){let e=process.env.GH_TOKEN??process.env.GITHUB_TOKEN;return e?Promise.resolve(e):execa("gh",["auth","token"],{reject:false}).then(({stdout:a})=>a.trim()||void 0).catch(()=>{})}function Cu(){return Su??=Zv(),Su}var Su,Ru=H(()=>{"use strict";});var Eu={};Mc(Eu,{GitRepoAdapter:()=>Gt});function xu(e,a){if(!ey.test(e))throw new Error(`Invalid ${a} in catalog source URL: "${e}"`)}var ey,Gt,dd=H(()=>{"use strict";Ru();Ho();ey=/^[a-zA-Z0-9_.-]+$/;Gt=class{id;name;source;constructor(a,o,t){this.id=a,this.name=o,this.source=t;}buildRawUrl(a,o="marketplace.json"){let t=new URL(this.source),{hostname:r,pathname:i}=t;if(Ln(r))throw new Error(`Catalog source URL points to a private/loopback address: "${r}"`);let s=i.replace(/^\//,"").split("/"),[n,d]=s;return xu(n,"owner"),xu(d,"repo"),r==="github.com"?`https://raw.githubusercontent.com/${n}/${d}/${a}/${o}`:r==="bitbucket.org"?`https://bitbucket.org/${n}/${d}/raw/${a}/${o}`:r==="gitlab.com"||r.startsWith("git.")?`https://${r}/${n}/${d}/-/raw/${a}/${o}`:`https://${r}/${n}/${d}/raw/${a}/${o}`}async fetchItems(){return this._fetchFromBranch("main").catch(a=>{if(this._is404(a))return this._fetchFromBranch("master");throw a})}async _fetchFromBranch(a){let o=await this._buildHeaders();try{let i=this.buildRawUrl(a,".claude-plugin/marketplace.json"),{plugins:s}=await Au.get(i,{headers:o}).json();return s.map(n=>({...n,catalogId:this.id,origin:n.origin??"external"}))}catch(i){if(this._is401or403(i))throw this._authError();if(!this._is404(i))throw i}let t=this.buildRawUrl(a),{plugins:r}=await Au.get(t,{headers:o}).json();return r.map(i=>({...i,catalogId:this.id,origin:i.origin??"external"}))}async _buildHeaders(){if(new URL(this.source).hostname!=="github.com")return {};let o=await Cu();return o?{Authorization:`token ${o}`}:{}}_is404(a){return a!==null&&typeof a=="object"&&"response"in a&&a.response?.status===404}_is401or403(a){return a!==null&&typeof a=="object"&&"response"in a&&[401,403].includes(a.response?.status??0)}_authError(){return Object.assign(new Error("Private repository or insufficient permissions. Set GH_TOKEN or GITHUB_TOKEN env var, or run `gh auth login`."),{code:"GITHUB_AUTH_REQUIRED"})}async fetchManifest(a){throw new Error("GitRepoAdapter does not support individual manifest fetch")}async ping(){try{return await this.fetchItems(),!0}catch{return !1}}};});U();var Lc=new Set(["skill","mcp","bundle","plugin"]),y=create(e=>({screen:"auth",activeTab:"discover",focus:"list",selectedIndex:0,actionMenuOpen:false,notification:null,loading:false,loadingMessage:"",downloadProgress:0,downloadTotal:0,catalogError:null,pendingExit:false,debugPanelOpen:false,catalogVersion:0,bundleInstallFlow:null,catalogFilters:{types:new Set(Lc),origins:new Set(rn)},setScreen:a=>e({screen:a}),setActiveTab:a=>e({activeTab:a}),setFocus:a=>e({focus:a}),setSelectedIndex:a=>e({selectedIndex:a}),setActionMenuOpen:a=>e({actionMenuOpen:a}),showNotification:(a,o)=>e({notification:{message:a,type:o}}),clearNotification:()=>e({notification:null}),setLoading:(a,o="")=>e({loading:a,loadingMessage:a?o:"",downloadProgress:0,downloadTotal:0}),setDownloadProgress:(a,o)=>e({downloadProgress:a,downloadTotal:o}),setCatalogError:a=>e({catalogError:a}),setPendingExit:a=>e({pendingExit:a}),toggleTypeFilter:a=>e(o=>{let{types:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,types:new Set([a])},selectedIndex:0}}),selectAllTypes:()=>e(a=>({catalogFilters:{...a.catalogFilters,types:new Set(Lc)},selectedIndex:0})),toggleOriginFilter:a=>e(o=>{let{origins:t}=o.catalogFilters;return t.size===1&&t.has(a)?{}:{catalogFilters:{...o.catalogFilters,origins:new Set([a])},selectedIndex:0}}),selectAllOrigins:()=>e(a=>({catalogFilters:{...a.catalogFilters,origins:new Set(rn)},selectedIndex:0})),setDebugPanelOpen:a=>e({debugPanelOpen:a}),incrementCatalogVersion:()=>e(a=>({catalogVersion:a.catalogVersion+1})),setBundleInstallFlow:a=>e({bundleInstallFlow:a})}));Se();St();Si();U();Ho();I();var Ri=P("api:metrics");function cl(){return Ta("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/")+"log-event"}function ll(e,a,o){return Au.post(e,{json:a,headers:o})}async function Kh(e){let a=await Dt();if(a)return a;let o=wt(e),t={sub:o.sub,name:o.name,email:o.email};return await wi(t),t}async function S(e,a){let o=await Ma(),t=await Kh(o),r=await Y();if(!_a.test(r.tenant))throw new Error(`Invalid tenant value: "${r.tenant}"`);let i={action:e,booster:tn,metadata:{...a},success:true,tenant:r.tenant,timestamp:new Date().toISOString(),user:{id:t.sub,name:t.name,email:t.email}};try{await ll(cl(),i,{Authorization:`Bearer ${o}`,FlowTenant:r.tenant}),Ri.debug(`Metrics event sent: ${e}`);}catch(s){throw Ri.warn(`Failed to send metrics event "${e}": ${String(s)}`),s}}async function ul(e,a,o){try{let t=o&&_a.test(o)?o:"unknown",r={action:e,booster:tn,metadata:a,success:!0,tenant:t,timestamp:new Date().toISOString(),user:{id:"anonymous",name:"unknown",email:"unknown"}};await ll(cl(),r,{FlowTenant:t}),Ri.debug(`Anonymous metrics event sent: ${e}`);}catch(t){Ri.warn(`Failed to send anonymous metrics event "${e}": ${String(t)}`);}}var w={CLI_SESSION_STARTED:"CLI_SESSION_STARTED",CLI_AUTH_FAILED:"CLI_AUTH_FAILED",CLI_STEP_COMPLETED:"CLI_STEP_COMPLETED",CLI_KIT_DISPLAYED:"CLI_KIT_DISPLAYED",CLI_KIT_ACCEPTED:"CLI_KIT_ACCEPTED",CLI_KIT_REJECTED:"CLI_KIT_REJECTED",CLI_ONBOARDING_COMPLETED:"CLI_ONBOARDING_COMPLETED",CLI_ONBOARDING_ABANDONED:"CLI_ONBOARDING_ABANDONED",CLI_CLAUDE_MD_ACCEPTED:"CLI_CLAUDE_MD_ACCEPTED",CLI_CLAUDE_MD_SKIPPED:"CLI_CLAUDE_MD_SKIPPED",CLI_TOOL_INSTALLED:"CLI_TOOL_INSTALLED",CLI_TOOL_UNINSTALLED:"CLI_TOOL_UNINSTALLED",CLI_TOOL_UPDATED:"CLI_TOOL_UPDATED",CLI_TOOL_ENABLED:"CLI_TOOL_ENABLED",CLI_TOOL_INSTALL_FAILED:"CLI_TOOL_INSTALL_FAILED",CLI_TOOL_DISABLED:"CLI_TOOL_DISABLED",CLI_CATALOG_VIEWED:"CLI_CATALOG_VIEWED",CLI_TUI_SESSION_ENDED:"CLI_TUI_SESSION_ENDED",CLI_MODULE_INSTALL_STARTED:"CLI_MODULE_INSTALL_STARTED",CLI_MODULE_INSTALL_COMPLETED:"CLI_MODULE_INSTALL_COMPLETED",CLI_MODULE_INSTALL_FAILED:"CLI_MODULE_INSTALL_FAILED",CLI_MODULE_PROXY_EXECUTED:"CLI_MODULE_PROXY_EXECUTED",CLI_MODULE_NOT_FOUND:"CLI_MODULE_NOT_FOUND",CLI_MODULE_UPDATED:"CLI_MODULE_UPDATED",CLI_BUNDLE_INSTALL_STARTED:"CLI_BUNDLE_INSTALL_STARTED",CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS:"CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS",CLI_BUNDLE_INSTALL_PLUGIN_FAILED:"CLI_BUNDLE_INSTALL_PLUGIN_FAILED",CLI_BUNDLE_INSTALL_COMPLETED:"CLI_BUNDLE_INSTALL_COMPLETED",CLI_STRATEGY_INIT_COMPLETED:"CLI_STRATEGY_INIT_COMPLETED",CLI_STRATEGY_INIT_FAILED:"CLI_STRATEGY_INIT_FAILED"};var $h={sessionStart:0,stepStart:0,currentStep:"auth",interfaceType:"cli",tuiSessionStart:0},va={...$h};function pl(e){let a=Date.now();va={sessionStart:a,stepStart:a,currentStep:"auth",interfaceType:e,tuiSessionStart:0};}function Vo(e){va.currentStep=e,va.stepStart=Date.now();}function Z(){return {...va}}function yo(){return va.sessionStart===0?0:Date.now()-va.sessionStart}function _o(){return va.stepStart===0?0:Date.now()-va.stepStart}function ml(){va.tuiSessionStart=Date.now();}function gl(){return va.tuiSessionStart===0?0:Date.now()-va.tuiSessionStart}I();var Yh=3e3,Zh=P("abandonment");async function Ai(e){let{currentStep:a,sessionStart:o}=Z();if(o===0)return;let t={last_step:a,trigger:e,duration_ms:yo()};try{await Promise.race([S(w.CLI_ONBOARDING_ABANDONED,t),new Promise((r,i)=>setTimeout(()=>i(new Error("abandonment timeout")),Yh))]);}catch(r){Zh.warn(`Abandonment event failed: ${String(r)}`);}}function fl(e,a){return Promise.race([e,new Promise(o=>setTimeout(o,a))])}I();var eb=3e3,ab=P("session-end");async function pr(e,a,o){let t=gl(),i=[S(w.CLI_TUI_SESSION_ENDED,{duration_ms:t,active_tab:a,interface:"tui"})];o!=="main"&&i.push(Ai(e));try{await fl(Promise.all(i).then(()=>{}),eb);}catch(s){ab.warn(`Session end event failed: ${String(s)}`);}}var ib=2e3;function bl(){let{exit:e}=useApp(),a=useRef(false),o=useRef(null),t=y(d=>d.pendingExit),r=y(d=>d.setPendingExit),i=y(d=>d.activeTab),s=y(d=>d.screen),n=useCallback(()=>{if(a.current){o.current&&clearTimeout(o.current),pr("double-ctrl-c",i,s).finally(()=>e());return}a.current=true,r(true),o.current=setTimeout(()=>{a.current=false,r(false);},ib);},[e,r,i,s]);return useInput((d,l)=>{l.ctrl&&d==="c"&&n();}),{pendingExit:t}}var cb=16;function vl({label:e,value:a,onChange:o,masked:t=false,isActive:r,error:i}){let s=useRef(a);useEffect(()=>{s.current=a;},[a]),useInput((d,l)=>{if(l.backspace){let c=s.current.slice(0,-1);s.current=c,o(c);}else if(d&&!l.ctrl&&!l.meta&&!l.escape&&!l.return&&!l.tab&&!l.upArrow&&!l.downArrow&&!l.leftArrow&&!l.rightArrow){let c=s.current+d;s.current=c,o(c);}},{isActive:r});let n=t?"\u2022".repeat(a.length):a;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:r?"cyan":"gray",children:r?"\u25B8 ":" "}),jsx(Text,{color:r?"white":"gray",bold:r,children:e.padEnd(cb)}),jsx(Text,{color:r?"cyan":"gray",children:n}),r&&jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Box,{paddingLeft:3,children:jsxs(Text,{color:"red",children:["\u26A0 ",i]})})]})}U();function yl({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="n"||d==="N"){o("input");return}(d==="y"||d==="Y"||l.return)&&e(null);return}if(l.escape){n.current="",r(""),s(false),o("confirm");return}if(l.return){let c=n.current.trim();ft.test(c)?(s(false),e(c)):s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}),jsxs(Box,{flexDirection:"column",gap:1,children:[a==="confirm"&&jsx(Text,{children:"Does your email use the @ciandt.com domain? (Y/n)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your email address:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:ht}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})}U();function kl({plan:e}){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Confirm Settings Update"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Ready to update ~/.claude/settings.json:"}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{color:"green",children:e.previousToken?" ~ env.ANTHROPIC_AUTH_TOKEN (replaced)":" + env.ANTHROPIC_AUTH_TOKEN (new)"}),jsx(Text,{color:"green",children:e.previousBaseUrl?" ~ env.ANTHROPIC_BASE_URL (replaced)":" + env.ANTHROPIC_BASE_URL (new)"}),e.hadExistingFile&&jsx(Text,{dimColor:true,children:" Existing settings preserved."})]})]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsx(Text,{dimColor:true,children:"Enter \u2014 update settings.json and continue"}),jsx(Text,{dimColor:true,children:"Esc \u2014 skip JWT update, continue"}),jsx(Text,{dimColor:true,children:"q \u2014 back to form"})]})]})}U();function Pl(){return jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"yellow",children:[mo," \u2014 settings.json is invalid"]})}),jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsx(Text,{children:"Your ~/.claude/settings.json contains invalid JSON."}),jsx(Text,{children:"Press Enter to overwrite it with a fresh file containing only the auth token,"}),jsx(Text,{children:"or Esc to cancel and fix the file manually."})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter overwrite \xB7 Esc cancel"})})]})}var oa=create(e=>({credentials:null,isAuthenticated:false,justAuthenticated:false,setCredentials:a=>e({credentials:a,isAuthenticated:true}),clearCredentials:()=>e({credentials:null,isAuthenticated:false,justAuthenticated:false}),setJustAuthenticated:a=>e({justAuthenticated:a})}));Ci();U();function $o(){return De__default.join(Le__default.homedir(),".claude","settings.json")}function wl(e){return `${(e&&e.trim().length>0?e.trim():ai).replace(/\/+$/,"")}/flow-litellm/`}function yr(){let e=$o();if(!we__default.existsSync(e))return {status:"missing"};let a=we__default.readFileSync(e,"utf-8"),o=a.charCodeAt(0)===65279?a.slice(1):a;try{let t=JSON.parse(o);return t===null||typeof t!="object"||Array.isArray(t)?{status:"malformed",raw:a}:{status:"ok",settings:t}}catch{return {status:"malformed",raw:a}}}function Ei(e){let a=$o();we__default.mkdirSync(De__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`;we__default.writeFileSync(o,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,a);}function Sl(e,a,o){let t=e.env&&typeof e.env=="object"&&!Array.isArray(e.env)?e.env:{};return {...e,env:{...t,ANTHROPIC_AUTH_TOKEN:a,ANTHROPIC_BASE_URL:o}}}function zn(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_AUTH_TOKEN;return typeof o=="string"&&o.length>0?o:null}function Cl(e){let a=e.env;if(!a||typeof a!="object"||Array.isArray(a))return null;let o=a.ANTHROPIC_BASE_URL;return typeof o=="string"&&o.length>0?o:null}var hb=3600,Yo=class extends Error{constructor(){super("~/.claude/settings.json contains invalid JSON"),this.name="MalformedSettingsError";}};function kr(e){let a=e.split(".");if(a.length!==3)throw new Error("Malformed JWT: invalid format");let o;try{o=JSON.parse(Buffer.from(a[1],"base64url").toString("utf8"));}catch{throw new Error("Malformed JWT: payload is not valid JSON")}if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Malformed JWT: payload must be a JSON object");let t=o;if(typeof t.clientId!="string"||!t.clientId)throw new Error("Invalid JWT: claim clientId must be a non-empty string");if(t.clientId.length>512)throw new Error("Invalid JWT: claim clientId exceeds maximum length");if(typeof t.clientSecret!="string"||!t.clientSecret)throw new Error("Invalid JWT: claim clientSecret must be a non-empty string");if(t.clientSecret.length>4096)throw new Error("Invalid JWT: claim clientSecret exceeds maximum length");if(typeof t.tenant!="string"||!t.tenant)throw new Error("Invalid JWT: claim tenant must be a non-empty string");if(t.tenant.length>512)throw new Error("Invalid JWT: claim tenant exceeds maximum length");return {clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}}function bb(e){return fb.sign({clientId:e.clientId,tenant:e.tenant},e.clientSecret,{algorithm:"HS256",expiresIn:hb})}function Ii(e,a={}){let o=yr();if(o.status==="malformed"&&!a.allowOverwriteMalformed)throw new Yo;let t=o.status==="ok"?o.settings:{},r=o.status==="ok"?zn(o.settings):null,i=o.status==="ok"?Cl(o.settings):null,s=a.jwtOverride??bb(e),n=wl(e.customUrl),d=Sl(t,s,n);return {jwt:s,anthropicBaseUrl:n,merged:d,previousToken:r,previousBaseUrl:i,hadExistingFile:o.status!=="missing"}}function Ti(e){Ei(e.merged);}function Rl(){let e=yr();return e.status!=="ok"?false:zn(e.settings)!==null}Se();He();function vb(){let e=Uc();if(!we__default.existsSync(e))return {};try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return {}}}var Wn=null;function yb(){return Wn===null&&(Wn=vb()),Wn}function Do(){return !!yb().ENABLE_EXPERIMENTAL_BETAS}U();function wb(){return se.filter(e=>e.platforms[process.platform]?.status==="supported")}function xl(e){let a=wb();return a.length>0&&a.every(o=>e.find(t=>t.module.alias===o.alias)?.alreadyInstalled===true)}var Mi={alias:"metrics",required:true,name:"flow-ai-obs",configCheck:()=>{try{let e=De__default.join(Le__default.homedir(),".claude","settings.json"),o=we__default.readFileSync(e,"utf-8").replace(/^\uFEFF/,""),r=JSON.parse(o).env;return typeof r=="object"&&r!==null&&"OTEL_EXPORTER_OTLP_ENDPOINT"in r}catch{return false}},binaryName:"flow-ai-obs",description:"AI usage telemetry and observability (hooks, OTEL, LLM proxy)",platforms:{darwin:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},linux:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]},win32:{status:"supported",strategies:[{type:"npm",package:"@ciandt-flow/flow-ai-obs"}]}},versionCheck:{type:"npm-registry",package:"@ciandt-flow/flow-ai-obs"},versionCommand:["flow-ai-obs","--version"],hasOwnUpdateCheck:true,postInstall:{onboarding:e=>{let a=["flow-ai-obs","init","--no-interactive"];if(a.push("--custom-url",e.customUrl??ai),e.credentials){let{clientId:o,clientSecret:t,tenant:r}=e.credentials;a.push("--client-id",o,"--client-secret",t,"--tenant",r);}return e.customEmail&&a.push("--custom-email",e.customEmail),[a]},onDemand:null,mode:"non-interactive"}},Sb={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=Do()?[Mi,Sb]:[Mi];Se();I();var xb=P("moduleState");function Li(){let e=process.env.FLOW_HOME??De__default.join(Le__default.homedir(),".flow");return De__default.join(e,"modules.json")}var Eb={retries:5,minTimeout:50};async function El(e,a){we__default.mkdirSync(De__default.dirname(e),{recursive:true});let o=await Ab.lock(e+".lock",{realpath:false,retries:Eb});try{return await a()}finally{await o();}}function Il(){let e=Li();if(!we__default.existsSync(e))return [];try{let a=JSON.parse(we__default.readFileSync(e,"utf-8"));return a.schemaVersion!==1?(xb.warn(`modules.json has unknown schemaVersion ${a.schemaVersion}, resetting`),we__default.rmSync(e,{force:!0}),[]):Array.isArray(a.modules)?a.modules.map(o=>({...o,name:o.name??null})):[]}catch{return we__default.rmSync(e,{force:true}),[]}}function Zo(){return Il()}function Tl(e){let a=Li();we__default.mkdirSync(De__default.dirname(a),{recursive:true});let o=`${a}.${randomUUID()}.tmp`,t={schemaVersion:1,modules:e};we__default.writeFileSync(o,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,a);}function ta(e){return Zo().find(a=>a.alias===e)??null}async function ya(e){let a=Li();await El(a,async()=>{let o=Il(),t=o.findIndex(r=>r.alias===e.alias);t===-1?o.push(e):o[t]=e,Tl(o);});}async function et(){let e=Li();we__default.existsSync(e)||await El(e,async()=>{we__default.existsSync(e)||Tl([]);});}var Mb=promisify(execFile);function wo(e,a){let o=e.platforms[process.platform];return !o||o.status!=="supported"?null:o.strategies.find(t=>t.type===a)??null}async function La(e){let a=process.platform==="win32"?"where":"which";try{return await Mb(a,[e]),!0}catch{return false}}function Ka(){return process.platform==="win32"?"npm.cmd":"npm"}var Ml=promisify(execFile),Rt=class{type="npm";async isAvailable(){return La("npm")}async install(a){let o=await this.getInstalledVersion(a);return o?{success:true,version:o,method:"npm",durationMs:0}:this.runNpmInstall(a,false)}async update(a,o){return this.runNpmInstall(a,true)}async getInstalledVersion(a){let o=wo(a,"npm");if(!o)return null;try{let{stdout:t}=await Ml(Ka(),["list","-g",o.package,"--depth=0","--json"],{shell:process.platform==="win32"});return JSON.parse(t).dependencies?.[o.package]?.version??null}catch{return null}}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runNpmInstall(a,o){let t=Date.now(),r=wo(a,"npm");if(!r)return {success:false,error:{code:"NPM_NOT_AVAILABLE",message:"No npm config for this module on this platform"},durationMs:Date.now()-t};let i=o?`${r.package}@latest`:r.package;try{return await Ml(Ka(),["install","-g",i],{shell:process.platform==="win32"}),{success:!0,version:await this.getInstalledVersion(a)??void 0,method:"npm",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:"NPM_INSTALL_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}};var Fi=promisify(execFile),Nb=/^(\S+)\s+([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/,Oi=class{type="homebrew";async isAvailable(){return La("brew")}async install(a){return this.runBrewCommand(a,"install")}async update(a,o){return this.runBrewCommand(a,"upgrade")}async getInstalledVersion(a){let o=wo(a,"homebrew");return o?this.getVersionByFormula(o.formula):null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async runBrewCommand(a,o){let t=Date.now(),r=wo(a,"homebrew");if(!r)return {success:false,error:{code:"HOMEBREW_NOT_AVAILABLE",message:"No homebrew config for this module on this platform"},durationMs:Date.now()-t};let i=o==="install"?"HOMEBREW_INSTALL_FAILED":"HOMEBREW_UPGRADE_FAILED";try{return r.tap&&(await Fi("brew",["tap",r.tap]),await Fi("brew",["trust",r.tap])),await Fi("brew",[o,r.formula]),{success:!0,version:await this.getVersionByFormula(r.formula)??void 0,method:"homebrew",durationMs:Date.now()-t}}catch(s){return {success:false,error:{code:i,message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-t}}}async getVersionByFormula(a){try{let{stdout:o}=await Fi("brew",["list","--versions",a]),t=o.trim().match(Nb);return t?t[2]:null}catch{return null}}};var At=promisify(execFile),Ll=/([\d]+\.[\d]+(?:\.[\d]+)*(?:[-_][^\s]+)?)/;function Fl(){let e=process.env.FLOW_HOME??De__default.join(Le__default.homedir(),".flow");return De__default.join(e,"bin")}var Ni=class{type="curl";async isAvailable(){return La("curl")}async install(a){let o=Date.now(),t=wo(a,"curl");if(!t)return {success:false,error:{code:"CURL_NOT_AVAILABLE",message:"No curl config for this module on this platform"},durationMs:Date.now()-o};let r=typeof t.url=="function"?t.url(process.arch):t.url;return (t.mode??"binary")==="script"?this.installScript(r,t.checksumUrl,a,o):this.installBinary(r,t.checksumUrl,a,o)}async update(a,o){return this.install(a)}async getInstalledVersion(a){let o=De__default.join(Fl(),De__default.basename(a.binaryName));for(let t of [o,a.binaryName])try{let{stdout:r}=await At(t,["--version"]),i=r.match(Ll);if(i)return i[1]}catch{}return null}async uninstall(a){return {success:false,error:{code:"NOT_IMPLEMENTED",message:"uninstall not implemented"},durationMs:0}}async installScript(a,o,t,r){if(!o)return {success:false,error:{code:"CHECKSUM_REQUIRED",message:`checksumUrl is required for script installs (${t.alias})`},durationMs:Date.now()-r};let i=De__default.join(Le__default.tmpdir(),`flow-install-${randomUUID()}.sh`);try{if(await At("curl",["-sSL","--fail","-o",i,a]),o){let n=await this.validateChecksum(i,o);if(!n.valid){try{we__default.unlinkSync(i);}catch{}return {success:!1,error:{code:"CHECKSUM_MISMATCH",message:n.message},durationMs:Date.now()-r}}}return we__default.chmodSync(i,448),await At("bash",[i]),{success:!0,version:await this.getInstalledVersion(t)??void 0,method:"curl",durationMs:Date.now()-r}}catch(s){return {success:false,error:{code:"CURL_SCRIPT_FAILED",message:s instanceof Error?s.message:String(s)},durationMs:Date.now()-r}}finally{try{we__default.unlinkSync(i);}catch{}}}async installBinary(a,o,t,r){let i=Fl(),s=De__default.join(i,De__default.basename(t.binaryName)),n=false;try{if(we__default.mkdirSync(i,{recursive:!0}),n=!0,await At("curl",["-L","--fail","-o",s,a]),o){let l=await this.validateChecksum(s,o);if(!l.valid)return we__default.unlinkSync(s),{success:!1,error:{code:"CHECKSUM_MISMATCH",message:l.message},durationMs:Date.now()-r}}we__default.chmodSync(s,493);let d=null;try{let{stdout:l}=await At(s,["--version"]),c=l.match(Ll);d=c?c[1]:null;}catch{}return {success:!0,version:d??void 0,method:"curl",durationMs:Date.now()-r}}catch(d){if(n)try{we__default.unlinkSync(s);}catch{}return {success:false,error:{code:"CURL_DOWNLOAD_FAILED",message:d instanceof Error?d.message:String(d)},durationMs:Date.now()-r}}}async validateChecksum(a,o){let t=De__default.join(Le__default.tmpdir(),`curl-checksum-${randomUUID()}`);try{await At("curl",["-L","--fail","-o",t,o]);let r=we__default.readFileSync(t,"utf-8").trim().split(/\s+/)[0],i=we__default.readFileSync(a),s=createHash("sha256").update(i).digest("hex");return s!==r?{valid:!1,message:`SHA256 mismatch: expected ${r}, got ${s}`}:{valid:!0,message:""}}catch(r){return {valid:false,message:`Checksum validation failed: ${String(r)}`}}finally{try{we__default.unlinkSync(t);}catch{}}}};I();var Ol="0.0.0";try{let e=JSON.parse(readFileSync(join(import.meta.dirname,"..","package.json"),"utf8"));typeof e.version=="string"&&(Ol=e.version);}catch{}var te=Ol;var Ee=P("moduleInstaller");function Oa(e){switch(e){case "npm":return new Rt;case "homebrew":return new Oi;case "curl":return new Ni}}async function Pr(e,a,o){try{await S(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:o.code,error_message:o.message,trigger:a});}catch(t){Ee.warn(`Failed to emit install failed event: ${String(t)}`);}}async function Co(e,a,o,t,r,i){let s=Date.now(),n=e.platforms[process.platform];if(!n)return {success:false,error:{code:"PLATFORM_NOT_SUPPORTED",message:`Platform ${process.platform} is not listed for module ${e.alias}`},durationMs:Date.now()-s};if(n.status==="experimental"){Ee.warn(`Module "${e.alias}" has experimental support on ${process.platform}`);let u={code:"PLATFORM_EXPERIMENTAL",message:`Experimental support on ${process.platform} \u2014 install manually`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(n.status!=="supported"){let u={code:"PLATFORM_NOT_SUPPORTED",message:`Module ${e.alias} is not supported on ${process.platform}`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}if(!n.strategies.some(u=>u.type===o)){let u={code:"STRATEGY_NOT_FOUND",message:`Strategy "${o}" is not configured for module "${e.alias}" on ${process.platform}`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}let d=Oa(o),l=false;try{l=await d.isAvailable();}catch(u){Ee.warn(`${o} availability check failed: ${String(u)}`);}if(!l){let u={code:"STRATEGY_NOT_AVAILABLE",message:`"${o}" is not installed on this system`};return await Pr(e,a,u),{success:false,error:u,durationMs:Date.now()-s}}try{await S(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:te,trigger:a});}catch(u){Ee.warn(`Failed to emit install started event: ${String(u)}`);}let c;try{c=i?.forceLatest?await d.update(e,"unknown"):await d.install(e);}catch(u){let m=u instanceof Error?u.message:String(u);Ee.warn(`${o} install threw: ${m}`),c={success:false,error:{code:"INSTALL_THREW",message:m},durationMs:Date.now()-s};}if(c.success){await ya({alias:e.alias,name:e.name,installedVersion:c.version??null,installMethod:c.method??null,installedAt:new Date().toISOString(),lastChecked:new Date().toISOString()});try{await S(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:c.version??"unknown",duration_ms:c.durationMs,os:process.platform,trigger:a});}catch(p){Ee.warn(`Failed to emit install completed event: ${String(p)}`);}let{pendingCmd:u,failed:m}=await Jb(e,a,t,r);return u?{...c,pendingInteractiveSetup:u}:m?{...c,postInstallFailed:true}:e.configCheck&&!e.configCheck()?{...c,configCheckFailed:true}:c}return await Pr(e,a,c.error??{code:"UNKNOWN",message:"unknown error"}),c}async function Jb(e,a,o,t){if(!e.postInstall)return {pendingCmd:null,failed:false};let r=a==="onboarding"?e.postInstall.onboarding:e.postInstall.onDemand;if(r==null)return {pendingCmd:null,failed:false};let i;if(typeof r=="function"){let n=await Y(),d={credentials:n?{clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant}:null,customUrl:o??null,customEmail:t??null};try{i=r(d);}catch(l){return Ee.warn(`postInstall function threw: ${String(l)}`),{pendingCmd:null,failed:false}}}else i=r;if(i.length===0)return {pendingCmd:null,failed:false};if((e.postInstall.mode??"non-interactive")==="interactive")return {pendingCmd:i[0]??null,failed:false};let s=false;for(let n=0;n<i.length;n++){let d=i[n];if(d.length===0)continue;let l=spawnSync(d[0],d.slice(1),{stdio:"pipe",env:process.env,encoding:"utf-8",shell:process.platform==="win32"});if(l.status!==0){s=true,Ee.warn(`postInstall "${d.join(" ")}" exited with status ${l.status??"null"}`),l.stderr&&Ee.warn(l.stderr);let c=i.slice(n+1).filter(u=>u.length>0);c.length>0&&Ee.debug(`continuing with remaining postInstall steps: ${c.map(u=>u.join(" ")).join(", ")}`);}}return {pendingCmd:null,failed:s}}async function Gi(e,a){let o=Date.now(),t=ta(e.alias);if(!t?.installMethod)return {success:false,error:{code:"NOT_INSTALLED",message:`Module '${e.alias}' is not installed`},durationMs:Date.now()-o};let r=Oa(t.installMethod),i=t.installedVersion??"unknown";if(a==="command")try{await S(w.CLI_MODULE_INSTALL_STARTED,{module_alias:e.alias,module_name:e.name,os:process.platform,cli_version:te,trigger:"command"});}catch(n){Ee.warn(`Failed to emit update started event: ${String(n)}`);}let s;try{s=await r.update(e,i);}catch(n){let d=n instanceof Error?n.message:String(n);Ee.warn(`${t.installMethod} update threw: ${d}`),s={success:false,error:{code:"UPDATE_THREW",message:d},durationMs:Date.now()-o};}if(s.success)if(await ya({...t,installedVersion:s.version??t.installedVersion,lastChecked:new Date().toISOString()}),a==="command")try{await S(w.CLI_MODULE_INSTALL_COMPLETED,{module_alias:e.alias,module_name:e.name,installed_version:s.version??"unknown",duration_ms:s.durationMs,os:process.platform,trigger:"command"});}catch(n){Ee.warn(`Failed to emit update completed event: ${String(n)}`);}else try{await S(w.CLI_MODULE_UPDATED,{module_alias:e.alias,from_version:i,to_version:s.version??"unknown",duration_ms:s.durationMs});}catch(n){Ee.warn(`Failed to emit module updated event: ${String(n)}`);}else if(a==="command")try{await S(w.CLI_MODULE_INSTALL_FAILED,{module_alias:e.alias,module_name:e.name,os:process.platform,error_code:s.error?.code??"UNKNOWN",error_message:s.error?.message??"unknown error",trigger:"command"});}catch(n){Ee.warn(`Failed to emit update failed event: ${String(n)}`);}return s}I();var Bi=P("flowAiObsSetup");async function ji(e,a){try{if(!await new Rt().isAvailable().catch(()=>!1))return Bi.warn("npm not available \u2014 skipping flow-ai-obs install"),{npmFailed:!0,initFailed:!1};let r=await Co(Mi,"onboarding","npm",e,a,{forceLatest:!0});return r.success?r.postInstallFailed||r.configCheckFailed?(Bi.debug("flow-ai-obs init failed (postInstall exit non-zero or configCheck failed)"),{npmFailed:!1,initFailed:!0}):{npmFailed:!1,initFailed:!1}:(Bi.warn(`flow-ai-obs install failed: ${r.error?.message??"unknown"}`),{npmFailed:!0,initFailed:!1})}catch(o){return Bi.warn(`installFlowAiObs threw: ${String(o)}`),{npmFailed:false,initFailed:false,unexpectedError:true}}}I();function Nl(e){if(!(e instanceof Error))return "unknown";let a=e.message.toLowerCase();return a.includes("401")||a.includes("unauthorized")?"invalid_credentials":a.includes("403")||a.includes("forbidden")?"forbidden":a.includes("timeout")||a.includes("timed out")?"timeout":a.includes("network")||a.includes("econnrefused")||a.includes("fetch")?"network_error":"unknown"}var Hb=P("useAuthSetup");function Gl(){let[e,a]=useState(""),o=useRef(null),t=useRef(null),r=useRef(null),[i,s]=useState(),[n,d]=useState(null),[l,c]=useState(false),[u,m]=useState("fields"),[p,h]=useState(null),f=useRef(0),g=useRef(false),{setCredentials:v,setJustAuthenticated:k}=oa(),T=()=>{m("fields"),h(null),a(""),o.current=null,t.current=null,r.current=null;},L=()=>{S(w.CLI_SESSION_STARTED,{cli_version:te,os:process.platform,node_version:process.version,duration_ms:yo(),interface:"tui"}).catch(()=>{});},A=async W=>{g.current=true;let _={...o.current,customUrl:t.current??void 0};try{W&&Ti(W),await bo(_);}catch(Q){d(Q instanceof Error?Q.message:"Failed to persist credentials"),T(),g.current=false;return}let{clientSecret:E,...B}=_;v(B),k(true),L(),await ji(t.current,r.current).catch(Q=>Hb.warn(`installFlowAiObs threw unexpectedly: ${String(Q)}`)),Ui({starterKit:B.starterKit});},M=async()=>A(),F=async W=>A(W),O=W=>{try{let _={...o.current,customUrl:t.current??void 0};return Ii(_,{allowOverwriteMalformed:W,jwtOverride:e.trim()})}catch(_){return _ instanceof Yo?(m("malformedConfirm"),null):(d(_ instanceof Error?_.message:"Failed to read settings.json"),m("fields"),null)}},ae=()=>{let W=O(true);W&&(h(W),F(W));},x=async()=>{let W=e.trim();if(!W){s("This field is required");return}let _;try{_=kr(W);}catch(E){s(E instanceof Error?E.message:"Invalid JWT");return}s(void 0),o.current=_,m("customUrl");},J=W=>{t.current=W,m("email");},ee=W=>{r.current=W,z();},z=async()=>{let W=t.current;W&&Ia(W),c(true),d(null),f.current+=1;try{await Qo(o.current);let _=O(!1);_&&(h(_),m("preview"));}catch(_){let E=_ instanceof Error?_.message:"Authentication failed";d(E),ul(w.CLI_AUTH_FAILED,{error_code:Nl(_),attempt:f.current},o.current.tenant).catch(()=>{}),a(""),o.current=null,m("fields");}finally{c(false);}};return {jwtValue:e,jwtError:i,authError:n,isSubmitting:l,step:u,plan:p,isCommittingRef:g,setJwtValue:a,setJwtError:s,cancelToFields:T,handleSubmit:x,goToEmailStep:J,handleEmailConfirm:ee,commitAndProceed:F,skipJwtAndProceed:M,planPersistOverwrite:ae}}U();j();function Bl(){let{jwtValue:e,jwtError:a,authError:o,isSubmitting:t,step:r,plan:i,isCommittingRef:s,setJwtValue:n,setJwtError:d,cancelToFields:l,handleSubmit:c,goToEmailStep:u,handleEmailConfirm:m,commitAndProceed:p,skipJwtAndProceed:h,planPersistOverwrite:f}=Gl(),[g,v]=useState("confirm"),[k,T]=useState(""),L=useRef(""),[A,M]=useState(false);return useEffect(()=>{r==="customUrl"&&(v("confirm"),L.current="",T(""),M(false));},[r]),useInput((F,O)=>{if(!(t||s.current)){if(r==="preview"){O.return&&i?p(i):O.escape?h():F==="q"&&l();return}if(r==="malformedConfirm"){O.return?f():O.escape&&l();return}if(r==="customUrl"){if(g==="confirm")F==="y"||F==="Y"?v("input"):(F==="n"||F==="N"||O.return)&&u(null);else if(O.escape)L.current="",T(""),v("confirm");else if(O.return){let ae=L.current.trim();ae.length>0&&mt.test(ae)?(M(false),u(ae)):ae.length>0&&M(true);}else O.backspace||O.delete?(L.current=L.current.slice(0,-1),T(L.current)):F&&!O.ctrl&&!O.meta&&(L.current=L.current+F,T(L.current),M(false));return}r!=="email"&&O.return&&c();}},{isActive:true}),r==="customUrl"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Initial Setup"]})}),jsxs(Box,{flexDirection:"column",gap:1,children:[t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),!t&&g==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),!t&&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:k}),jsx(Text,{color:"cyan",children:"\u2588"})]}),A&&jsx(Text,{color:"red",children:gt}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]}):r==="email"?jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \u2014 Initial Setup"]})}),t?jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}):jsx(yl,{onConfirm:m})]}):r==="preview"&&i?jsx(kl,{plan:i}):r==="malformedConfirm"?jsx(Pl,{}):jsxs(Box,{flexDirection:"column",padding:2,children:[jsx(Box,{marginBottom:1,children:jsxs(Text,{bold:true,color:"cyan",children:[mo," \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(vl,{label:"JWT",value:e,onChange:F=>{n(F),a&&d(void 0);},masked:true,isActive:!t,error:a})})}),t&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"cyan",children:"Authenticating..."})}),o&&jsx(Box,{marginTop:1,children:jsxs(Text,{color:"red",children:["\u26A0 ",b(o)]})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter confirm"})})]})}function Et(){return jsxs(Box,{flexDirection:"column",alignItems:"center",children:[jsx(Kb,{text:"FLOW",font:"block",colors:["white","white"]}),jsx(Box,{marginTop:-1,marginBottom:1,children:jsxs(Text,{dimColor:true,children:["Marketplace \xB7 v",te]})})]})}var Wl=[{id:"discover",focus:"list"},{id:"installed",focus:"list"},{id:"updates",focus:"list"},{id:"marketplaces",focus:"marketplaces"}],re=Do()?Wl:Wl.slice(0,3);function $b(e){return re.findIndex(a=>a.id===e)}function Qn(e,a,o){let t=$b(o.activeTab);if(a.rightArrow||a.tab){let r=re[(t+1)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}if(a.leftArrow){let r=re[(t-1+re.length)%re.length];return [{type:"setTab",tab:r.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:r.focus}]}return a.downArrow?[{type:"setFocus",focus:re[t]?.focus??"list"}]:[]}var Ql={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function Vl({outdatedCount:e=0}){let a=y(o=>o.activeTab);return jsx(Box,{paddingX:1,paddingBottom:1,children:re.map(({id:o})=>{let t=o===a,r=o==="updates"&&e>0?`${Ql[o]} (${e})`:Ql[o];return jsx(Box,{marginRight:1,children:t?jsx(Text,{bold:true,inverse:true,children:` ${r} `}):jsx(Text,{dimColor:true,children:` ${r} `})},o)})})}var _e=create(e=>({query:"",cursorPosition:0,setQuery:a=>e({query:a}),setCursorPosition:a=>e({cursorPosition:a}),resetQuery:()=>e({query:"",cursorPosition:0})}));function Xl(){let e=y(s=>s.focus),a=_e(s=>s.query),o=_e(s=>s.cursorPosition),t=e==="search",r=a.slice(0,o),i=a.slice(o);return jsxs(Box,{borderStyle:"single",borderTop:false,borderBottom:true,borderLeft:false,borderRight:false,paddingX:1,marginX:1,marginBottom:1,children:[jsx(Text,{color:t?"cyan":"gray",children:"\u{1F50D} "}),t?jsxs(Fragment,{children:[jsx(Text,{color:"white",children:r}),jsx(Text,{inverse:true,children:i[0]??" "}),jsx(Text,{color:"white",children:i.slice(1)})]}):jsx(Text,{dimColor:true,children:a||"Search..."})]})}U();var av=["skill","mcp","bundle"].map((e,a)=>({key:String(a+2),type:e,...pt[e]})),ov=["internal","external"].map((e,a)=>({key:String(a+6),origin:e,...qc[e]}));function Kl(){let e=y(t=>t.catalogFilters),a=e.types.has("skill")&&e.types.has("mcp")&&e.types.has("bundle"),o=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:a?"green":void 0,dimColor:!a,children:[a?"\u25C9":"\u25CB"," All"]})]}),av.map(t=>{let r=!a&&e.types.has(t.type);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"|"})}),jsx(Box,{marginLeft:2,children:jsx(Text,{bold:true,children:"Origin:"})}),jsxs(Box,{gap:0,children:[jsx(Text,{dimColor:true,children:"[5] "}),jsxs(Text,{color:o?"green":void 0,dimColor:!o,children:[o?"\u25C9":"\u25CB"," All"]})]}),ov.map(t=>{let r=!o&&e.origins.has(t.origin);return jsxs(Box,{gap:0,children:[jsxs(Text,{dimColor:true,children:["[",t.key,"] "]}),jsxs(Text,{color:r?t.color:void 0,dimColor:!r,children:[r?"\u25C9":"\u25CB"," ",t.label]})]},t.key)})]})}U();function $l({type:e}){let{label:a,color:o}=pt[e];return jsx(Text,{color:o,children:a})}U();function eu({origin:e}){return e===ir?jsx(Text,{color:"blue",children:"[Flow]"}):jsx(Text,{color:"white",children:"[External]"})}j();var Wi=iv.memo(function({item:a,isSelected:o}){let t=a.status==="disabled"?"yellow":"green";return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:a.name}),a.type&&jsxs(Text,{children:[" ",jsx($l,{type:a.type})]}),a.origin&&jsxs(Text,{children:[" ",jsx(eu,{origin:a.origin})]}),jsxs(Text,{dimColor:true,children:[a.authorName?` \xB7 ${a.authorName}`:"",a.version?` \xB7 v${a.version}`:" \xB7 n/a"]}),a.status&&jsxs(Text,{color:t,children:[" [",a.status,"]"]}),a.updateAvailable&&jsx(Text,{color:"yellow",children:" [\u2191 update available]"}),a.installedAt&&jsxs(Text,{dimColor:true,children:[" \xB7 ",Ea(a.installedAt)]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:a.description})})]})});function It({message:e}){return jsx(Box,{paddingX:2,paddingY:1,children:jsx(Text,{dimColor:true,children:e??"No items found."})})}U();function tu({items:e,emptyMessage:a}){let o=y(d=>d.selectedIndex);if(e.length===0)return jsx(It,{message:a});let t=Math.max(0,o-Math.floor(ea/2)),r=Math.min(e.length,t+ea);r===e.length&&(t=Math.max(0,r-ea));let i=e.slice(t,r),s=t,n=e.length-r;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:s>0?`\u2191 ${s} more above`:" "})}),i.map((d,l)=>jsx(Wi,{item:d,isSelected:t+l===o},d.name)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:n>0?`\u2193 ${n} more below`:" "})})]})}function su({label:e,pathHint:a}){return jsxs(Box,{paddingBottom:1,children:[jsx(Text,{bold:true,color:"blueBright",children:e}),jsxs(Text,{dimColor:true,children:[" ",a]})]})}U();function du({groups:e,emptyMessage:a}){let o=y(p=>p.selectedIndex),t=[],r=0;for(let p of e){t.push({kind:"header",label:p.label,pathHint:p.pathHint,key:`h-${p.scope}`});for(let h of p.items)t.push({kind:"item",item:h,itemIndex:r,key:`i-${p.scope}-${h.name}-${h.marketplace??""}`}),r++;}if(r===0)return jsx(It,{message:a});let s=t.findIndex(p=>p.kind==="item"&&p.itemIndex===o),n=s>=0?s:0,d=Math.max(0,n-Math.floor(ea/2)),l=Math.min(t.length,d+ea);l===t.length&&(d=Math.max(0,l-ea));let c=t.slice(d,l),u=d,m=t.length-l;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:u>0?`\u2191 ${u} more above`:" "})}),c.map(p=>p.kind==="header"?jsx(su,{label:p.label,pathHint:p.pathHint},p.key):jsx(Wi,{item:p.item,isSelected:p.itemIndex===o},p.key)),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:m>0?`\u2193 ${m} more below`:" "})})]})}var mv={discover:"Discover",installed:"Installed",updates:"Updates",marketplaces:"Marketplaces"};function gv({items:e,tabId:a,emptyMessage:o,groups:t,actionHint:r}){return jsxs(Box,{flexDirection:"column",children:[jsx(Xl,{}),jsx(Kl,{}),jsxs(Box,{paddingX:1,marginTop:1,children:[jsx(Text,{bold:true,children:mv[a]}),jsxs(Text,{dimColor:true,children:[" (",e.length,")"]}),r&&e.length>0&&jsx(Text,{dimColor:true,children:` \xB7 ${r}`})]}),t&&t.length>0?jsx(du,{groups:t,emptyMessage:o}):jsx(tu,{items:e,emptyMessage:o})]})}function cu({filteredItems:e,emptyMessage:a,groups:o,onBatchUpdate:t}){let r=y(d=>d.activeTab),i=y(d=>d.focus);return useInput(d=>{d==="a"&&e.length>0&&t?.();},{isActive:r==="updates"&&i==="list"}),jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(gv,{items:e,tabId:r,emptyMessage:a,groups:r!=="discover"?o:void 0,actionHint:r==="updates"?"press 'a' to update all":void 0},r)})}var bv={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 Ji(){let e=y(o=>o.focus),a=!!process.env.DEBUG;return jsx(Box,{borderStyle:"single",borderTop:true,borderBottom:false,borderLeft:false,borderRight:false,children:jsxs(Text,{dimColor:true,children:[bv[e],a?" | Ctrl+D: debug log":""]})})}j();function lu({message:e,type:a}){return e?jsx(Box,{paddingX:1,children:jsxs(Text,{color:a==="success"?"green":a==="info"?"cyan":"red",children:[a==="success"?"\u2713":a==="info"?"(i)":"\u2717"," ",b(e)]})}):null}function Hi({message:e}){return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{children:[" ",e]})]})}function Zn(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${(e/1024).toFixed(1)} KB`:`${e} B`}var gu=20;function Qi(e,a){let o=a>0?Math.min(e/a,1):0,t=Math.round(o*100),r=Math.round(o*gu),i="\u2588".repeat(r)+"\u2591".repeat(gu-r),s=`${Zn(e)} / ${Zn(a)}`;return {bar:i,percent:t,label:s}}function Vi({received:e,total:a}){let{bar:o,percent:t,label:r}=Qi(e,a);return jsxs(Text,{dimColor:true,children:[o," ",t,"%"," ","(",r,")"]})}function _i({message:e,onRetry:a,onBack:o}){return useInput((t,r)=>{t==="r"&&r.ctrl&&a?a():r.escape&&o&&o();}),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsxs(Text,{color:"red",children:["\u2717 ",e]}),a&&jsx(Text,{dimColor:true,children:"Press Ctrl+R to retry"}),o&&jsx(Text,{dimColor:true,children:"Press Escape to go back"})]})}function ra({itemName:e,actions:a,descriptions:o,onAction:t,onClose:r}){let i=y(d=>d.focus),[s,n]=useState(0);return useInput((d,l)=>{l.upArrow?n(c=>c>0?c-1:c):l.downArrow?n(c=>c<a.length-1?c+1:c):l.return?t(a[s]):l.escape&&r();},{isActive:i==="actionMenu"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsx(Box,{flexDirection:"column",marginTop:1,children:a.map((d,l)=>jsxs(Box,{children:[jsxs(Text,{bold:l===s,color:l===s?"cyan":void 0,children:[l===s?"\u203A ":" ",d]}),o?.[d]&&jsxs(Text,{dimColor:true,children:[" \u2014 ",o[d]]})]},l))})]})}U();var td=Object.entries(Va),vu=[...td.map(([,e])=>e.actionLabel),"Cancel"],yu=Object.fromEntries(td.map(([,e])=>[e.actionLabel,e.description]));function ku(e){let a=td.find(([,o])=>o.actionLabel===e);return a?a[0]:null}I();var Mv=P("provider.registry"),qv=3e4,Ki=class{adapters=new Map;availabilityCache=new Map;register(a){this.adapters.set(a.id,a);}async checkAvailability(a){let o=this.availabilityCache.get(a.id);if(o&&Date.now()<o.expiresAt)return o.result;let t=await a.isAvailable();return this.availabilityCache.set(a.id,{result:t,expiresAt:Date.now()+qv}),t}async getAvailableProviders(a){let o=[...this.adapters.values()].filter(r=>a in r.installers),t=await Promise.allSettled(o.map(r=>this.checkAvailability(r)));return t.forEach((r,i)=>{r.status==="rejected"&&Mv.warn(`Provider "${o[i].id}" isAvailable() threw: ${String(r.reason)}`);}),o.filter((r,i)=>{let s=t[i];return s.status==="fulfilled"&&s.value===true})}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};var Lv={user:"global",project:"project",local:"local"};function $i(e){return e?Lv[e]:"global"}var Xe=class extends Error{constructor(o,t){super(`${o} v${t} is already installed. Use --force to reinstall.`);this.pluginName=o;this.version=t;this.name="AlreadyInstalledError";}pluginName;version},Ao=class extends Error{constructor(o,t){super(`${o} is already up to date (v${t})`);this.pluginName=o;this.version=t;this.name="AlreadyUpToDateError";}pluginName;version};Cr();rd();I();var Nv=P("catalog.registry"),Yi=class{adapters=new Map;register(a){this.adapters.set(a.id,a);}unregister(a){this.adapters.delete(a);}async fetchAllWithErrors(){let a=this.listAdapters(),o=await Promise.allSettled(a.map(i=>i.fetchItems())),t=[],r=[];for(let i=0;i<o.length;i++){let s=o[i],n=a[i];if(s.status==="fulfilled")t.push(...s.value);else {let d=String(s.reason);Nv.warn(`Catalog adapter failed: ${d}`),r.push({adapterId:n.id,adapterName:n.name,reason:d});}}return {items:t,failures:r}}async fetchAll(){let{items:a}=await this.fetchAllWithErrors();return a}getAdapter(a){return this.adapters.get(a)}listAdapters(){return [...this.adapters.values()]}};He();var Hv={retries:5,minTimeout:50};async function id(e,a){mkdirSync(dirname(e),{recursive:true});let o=await Ab.lock(e+".lock",{realpath:false,retries:Hv});try{return await a()}finally{await o();}}var Zi=class{filePath;constructor(a){this.filePath=a??jc();}async read(){try{let a=await readFile(this.filePath,"utf-8");return JSON.parse(a).catalogs??[]}catch(a){if(a.code==="ENOENT")return [];throw a}}async write(a){let o=dirname(this.filePath);await mkdir(o,{recursive:true});let t=`${this.filePath}.${randomUUID()}.tmp`;await writeFile(t,JSON.stringify({catalogs:a},null,2),"utf-8"),await rename(t,this.filePath);}async add(a){await id(this.filePath,async()=>{let o=await this.read();if(o.some(r=>r.id===a.id))return;let t={...a,lastUpdated:a.lastUpdated??new Date().toISOString()};await this.write([...o,t]);});}async remove(a){if(a==="flow-api")throw new Error("The Flow Marketplace catalog cannot be removed");await id(this.filePath,async()=>{let o=await this.read();await this.write(o.filter(t=>t.id!==a));});}async updateField(a,o){await id(this.filePath,async()=>{let t=await this.read();t.some(r=>r.id===a)&&await this.write(t.map(r=>r.id===a?{...r,...o}:r));});}};nd();var pe=new Yi,Za=new Zi,ay=["flow-harness"];function oy(){let e=process.env.FLOW_CONTENT_SOURCES;return e===void 0?ay:e.split(",").map(a=>a.trim()).filter(Boolean)}pe.register(new Nt);for(let e of oy())pe.register(new Nt(e));var Iu=false;async function Tu(){if(Iu)return;Iu=true;let e=await Za.read(),{GitRepoAdapter:a}=await Promise.resolve().then(()=>(dd(),Eu));for(let o of e)pe.register(new a(o.id,o.name,o.source));}xo();var Mu=2;async function eo(e){if(e){let{FlowApiAdapter:a}=await Promise.resolve().then(()=>(nd(),wu));return new a(e).fetchItems()}return pe.fetchAll()}async function qu(){return pe.fetchAllWithErrors()}async function Bt(e,a){Rr(e);try{return await Mt(`v1/plugins/${e}/manifest`,a).json()}catch(o){let t=await qt(o);throw t?new Error(t):o instanceof Error?o.message.includes("404")?new Error(`Plugin '${e}' not found in catalog`):o.message.includes("timeout")?new Error("Download timed out after 30s"):new Error(`Failed to fetch plugin manifest: ${o.message}`):o}}async function Lu(e,a,o){Rr(e);try{let t=await Mt(`v1/plugins/${e}/archive`,o),r=t.headers.get("x-archive-size"),i=r?Number(r):NaN,s=Number.isFinite(i)&&i>0?i:0,n=s>0,d=t.body;if(!d)throw new Error("Failed to download plugin: response has no body");let l=d.getReader(),c=[],u=0;for(;;){let{done:m,value:p}=await l.read();if(m)break;if(u+=p.byteLength,n&&u>s*Mu)throw await l.cancel(),new Error(`Download exceeded expected size: received ${u} bytes, expected at most ${s*Mu}`);c.push(p),n&&a?.(u,s);}return Buffer.concat(c)}catch(t){if(t instanceof Error&&t.message.includes("Download exceeded expected size"))throw t;let r=await qt(t);throw r?new Error(r):t instanceof Error?new Error(`Failed to download plugin: ${t.message}`):t}}async function as(){try{let{profiles:e}=await Ya().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}}He();He();async function Fu(e,a){let o=De.resolve(a);await Na.mkdir(o,{recursive:true});let t=De.join(De.dirname(o),`${randomUUID()}.zip`);try{await Na.writeFile(t,e);let r=await ry.Open.file(t),i=De.normalize(o+De.sep);for(let s of r.files){if((s.externalFileAttributes>>16&61440)===40960)throw new Error(`Zip Slip (symlink): entry "${s.path}" is a symbolic link and was rejected`);let d=De.resolve(o,s.path);if(process.platform==="win32"&&d.length>=260)throw new Error(`Path too long: "${d}" (${d.length} chars) meets or exceeds the 260-character Windows MAX_PATH limit. Enable Long Paths in Windows or move the Claude plugin cache to a shorter base path.`);if(!d.startsWith(i)&&d!==o)throw new Error(`Zip Slip detected: entry "${s.path}" would escape target directory`)}await r.extract({path:o});try{let s=realpathSync(o);if(!s.startsWith(De.resolve(De.dirname(o))))throw new Error(`Zip Slip (post-extract): resolved path "${s}" is outside expected parent`)}catch(s){if(s.code!=="ENOENT")throw s}}finally{try{await Na.unlink(t);}catch{}}}async function cd(e){await Na.rm(e,{recursive:true,force:true});}async function Eo(){let e=Gc();await Na.mkdir(De.dirname(e),{recursive:true});try{await Na.writeFile(e,"",{flag:"wx"});}catch(o){if(o.code!=="EEXIST")throw o}return await Ab.lock(e,{stale:1e4,retries:{retries:2,minTimeout:500,maxTimeout:500}})}He();U();function ny(e){return {$schema:"https://anthropic.com/claude-code/marketplace.schema.json",name:e||le,description:"Flow Skills marketplace",owner:{name:"Flow Team",email:"flow@ciandt.com"},plugins:[]}}function Gu(e){let a=ii(e);if(!we__default.existsSync(a))return null;try{return JSON.parse(we__default.readFileSync(a,"utf-8"))}catch{return null}}function dy(e){let a=Gu(e);if(a)return a;let o=ny(e),t=ii(e);return we__default.mkdirSync(De__default.dirname(t),{recursive:true}),ld(o,e),o}function ld(e,a){let o=ii(a),t=`${o}.${randomUUID()}.tmp`;we__default.writeFileSync(t,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(t,o);}function cy(e){let a=e||le,o=Uo(),t={};try{we__default.existsSync(o)&&(t=JSON.parse(we__default.readFileSync(o,"utf-8")));}catch{t={};}if(t[a])return;t[a]={source:{source:"github",repo:`cit-flow/${a}`},installLocation:Nc(e),lastUpdated:new Date().toISOString(),autoUpdate:true};let r=`${o}.${randomUUID()}.tmp`;we__default.writeFileSync(r,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(r,o);}function Bu(e,a,o){wa(e.name),cy(o);let t=cn(e.name,o);we__default.mkdirSync(De__default.dirname(t),{recursive:true});try{we__default.lstatSync(t),we__default.rmSync(t,{recursive:!0,force:!0});}catch{}we__default.cpSync(a,t,{recursive:true,dereference:true});let r=dy(o);r.plugins.some(s=>s.name===e.name)||(r.plugins.push({name:e.name,description:e.description,version:e.version,author:e.author,source:`./plugins/native/${e.name}`,category:e.category}),ld(r,o));}function ud(e,a){wa(e);let o=cn(e,a);try{we__default.rmSync(o,{recursive:!0,force:!0});}catch{}let t=Gu(a);if(!t)return;let r=t.plugins.length;t.plugins=t.plugins.filter(i=>i.name!==e),t.plugins.length!==r&&ld(t,a);}j();I();var uy=P("mcpConfigReader"),py=500,my=512;function gy(){return De__default.join(Le__default.homedir(),".claude.json")}function fy(){return De__default.join(process.cwd(),".mcp.json")}function Uu(e){if(!we__default.existsSync(e))return null;try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return uy.debug(`[mcpConfigReader] Failed to parse ${e}`),null}}function Ar(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pd(e){if(!Ar(e))return {};let a=e.mcpServers;return Ar(a)?a:{}}function md(e,a){return Object.keys(e).slice(0,py).map(t=>({name:b(t.slice(0,my)),marketplace:"",version:void 0,installedAt:"",installPath:"",scope:a,description:void 0,author:void 0,status:"enabled",type:"mcp"}))}function Wu(){let e=[],a=gy(),o=Uu(a);if(Ar(o)){let n=o,d=pd(n);e.push(...md(d,"user"));let l=process.cwd();if(Ar(n.projects)){let c=n.projects[l];if(Ar(c)){let u=pd(c);e.push(...md(u,"local"));}}}let t=fy(),r=Uu(t),i=pd(r);e.push(...md(i,"project"));let s=new Map;for(let n of e){let d=`${n.name}@${n.scope}`;s.has(d)||s.set(d,n);}return [...s.values()]}I();var ia=P("storage");async function by(e,a,o){try{await S(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:o,source:a,interface:Z().interfaceType});}catch(t){ia.warn(`Failed to send uninstall metrics: ${String(t)}`);}}function vy(e,a,o){let t=a==="enabled"?w.CLI_TOOL_ENABLED:w.CLI_TOOL_DISABLED;S(t,{tool_id:e,source:o,interface:Z().interfaceType}).catch(r=>ia.warn(`Failed to send ${a} metrics: ${String(r)}`));}function bd(){return De__default.join(Le__default.homedir(),".claude","plugins","installed_plugins.json")}function yy(){return De__default.join(Le__default.homedir(),".claude","plugins")}function os(e){let a;try{a=we__default.realpathSync(e);}catch{a=De__default.resolve(e);}let o=De__default.resolve(yy()),t=De__default.resolve(De__default.join(process.cwd(),".claude","plugins")),r=a.startsWith(o+De__default.sep),i=a.startsWith(t+De__default.sep);if(!r&&!i)throw new Error(`Security error: installPath '${e}' is outside the plugins directory`)}function Hu(e="user"){return e==="local"?De__default.join(process.cwd(),".claude","settings.local.json"):e==="project"?De__default.join(process.cwd(),".claude","settings.json"):De__default.join(Le__default.homedir(),".claude","settings.json")}function Ce(){let e=bd();if(!we__default.existsSync(e))return {version:2,plugins:{}};try{return JSON.parse(we__default.readFileSync(e,"utf-8"))}catch{return {version:2,plugins:{}}}}async function vd(){let e=bd();try{let a=await we__default.promises.readFile(e,"utf-8");return JSON.parse(a)}catch{return {version:2,plugins:{}}}}function ky(e){let a=e?.code;return a==="EACCES"||a==="EPERM"}function Qu(e,a){try{we__default.mkdirSync(De__default.dirname(e),{recursive:!0});let o=`${e}.${randomUUID()}.tmp`;we__default.writeFileSync(o,JSON.stringify(a,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(o,e);}catch(o){throw ky(o)?new Error(`Permission denied: cannot write to '${e}'. Check your file system permissions.`):o}}function sa(e){Qu(bd(),e);}function xr(e){let a=e.lastIndexOf("@");return a===-1?{name:e,marketplace:""}:{name:e.slice(0,a),marketplace:e.slice(a+1)}}function Py(e,a){let o=De__default.join(e,".claude-plugin"),t=De__default.join(o,"plugin.json");if(we__default.existsSync(t))try{return JSON.parse(we__default.readFileSync(t,"utf-8"))}catch{return null}let r=De__default.join(o,"marketplace.json");if(we__default.existsSync(r))try{let i=JSON.parse(we__default.readFileSync(r,"utf-8"));return {description:i.plugins?.find(n=>n.name===a)?.description,author:i.owner}}catch{return null}return null}function yd(e="user"){let a=Hu(e);if(!we__default.existsSync(a))return {};try{return JSON.parse(we__default.readFileSync(a,"utf-8"))}catch{return {}}}function Vu(e,a="user"){Qu(Hu(a),e);}function Dy(e,a){let{name:o,marketplace:t}=xr(e),r;if(t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>xr(s).name===o)[0],!r)throw ia.error(`[${o}] Plugin is not installed`),new Error(`Plugin '${o}' is not installed`);return {key:r,name:o}}function wy(e,a){let{name:o,marketplace:t}=xr(e),r;return t?(r=`${o}@${t}`,a[r]||(r=void 0)):r=Object.keys(a).filter(s=>xr(s).name===o)[0],r?{key:r,name:o}:null}function gd(e="user"){return yd(e).enabledPlugins??{}}function fd(e,a="user"){let o=yd(a),t=o.enabledPlugins;if(!t||!(e in t))return;let{[e]:r,...i}=t;o.enabledPlugins=i,Vu(o,a);}function Er(e,a,o="user"){let t=yd(o),r=t.enabledPlugins??{};t.enabledPlugins={...r,[e]:a},Vu(t,o);}function Sy(e){let a=new Map;for(let o of e){let t=o.projectPath?`${o.scope}:${o.projectPath}`:o.scope,r=a.get(t);(!r||o.installedAt>r.installedAt)&&a.set(t,o);}return [...a.values()]}function ne(){let e=Ce(),a=gd(),o=gd("project"),t=gd("local"),r={project:o,local:t},i=Object.entries(e.plugins).flatMap(([l,c])=>{let{name:u,marketplace:m}=xr(l),p=c.map(f=>f.scope==="managed"?{...f,scope:"user"}:f);return Sy(p).map(f=>{let g=Py(f.installPath,u),k=(r[f.scope]??a)[l];return {name:u,marketplace:m,version:f.version&&f.version!=="unknown"?f.version:void 0,installedAt:f.installedAt,installPath:f.installPath,scope:f.scope,providerId:f.providerId,type:f.type,description:g?.description,author:g?.author,status:k===false?"disabled":"enabled"}})}),s=Wu(),n=new Set(i.map(l=>`${l.name}@${l.scope}`)),d=s.filter(l=>!n.has(`${l.name}@${l.scope}`));return [...i,...d]}function Ju(e){let a=e.lastIndexOf("@");return a>0?e.slice(a+1):void 0}async function Ir(e,a){ia.debug(`[${e}] Acquiring lock to uninstall`);let o=await Eo();try{let t=Ce(),r=wy(e,t.plugins);if(!r)throw new Error(`Plugin '${e}' is not in installed_plugins.json. If this is an MCP server from config, use the MCP remove command instead.`);let{key:i,name:s}=r,n=t.plugins[i];if(a){let d=n.find(u=>u.scope===a);if(!d)throw new Error(`Plugin '${s}' is not installed in ${a} scope`);ia.debug(`[${s}] Resolved key: ${i}, scope: ${a}`),os(d.installPath);let l=De__default.dirname(d.installPath);os(l),ia.debug(`[${s}] Removing directory: ${l}`),we__default.rmSync(l,{recursive:!0,force:!0});let c=n.filter(u=>u.scope!==a);if(c.length===0){let{[i]:u,...m}=t.plugins;sa({...t,plugins:m}),fd(i,a),ud(s,Ju(i));}else t.plugins[i]=c,sa(t),fd(i,a);}else {ia.debug(`[${s}] Resolved key: ${i}`);for(let c of n){os(c.installPath);let u=De__default.dirname(c.installPath);os(u),ia.debug(`[${s}] Removing directory: ${u}`),we__default.rmSync(u,{recursive:!0,force:!0}),fd(i,c.scope);}ud(s,Ju(i));let{[i]:d,...l}=t.plugins;sa({...t,plugins:l});}await by(s,n[0].origin??"internal",n[0].type??"skill"),ia.debug(`[${s}] Uninstalled successfully`);}finally{await o();}}async function Tr(e,a,o){ia.debug(`[${e}] Acquiring lock to set status \u2192 ${a}`);let t=await Eo();try{let r=Ce(),{key:i,name:s}=Dy(e,r.plugins),n=r.plugins[i],d=o??n[0].scope,l=n[0].origin??"internal";ia.debug(`[${s}] Resolved key: ${i}, scope: ${d}`),Er(i,a==="enabled",d),vy(s,a,l),ia.debug(`[${s}] Status updated to ${a}`);}finally{await t();}}U();I();var Cy=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/,Ry=/^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?$/;function wa(e){if(!Cy.test(e))throw new Error(`Invalid plugin name from manifest: "${e}". Plugin names must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Ay(e){if(!Ry.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 Io=P("installer");function xy(e,a,o){let t=`${e}@${o||le}`,i=Ce().plugins[t];if(i&&!a)throw new Xe(e,i[0].version??"unknown");return {pluginKey:t,alreadyInstalled:i}}async function Ey(e,a,o){o&&await cd(a);try{Io.debug(`[${a}] Extracting archive...`),await Fu(e,a);}catch(t){throw await cd(a),t}}function Iy(e,a,o,t,r,i="claude-code",s){let n=Ce(),d={scope:t,...t==="user"?{}:{projectPath:process.cwd()},installPath:a,version:o,installedAt:new Date().toISOString(),origin:r,providerId:i,type:s},l=n.plugins[e]??[];n.plugins[e]=[...l.filter(c=>c.scope!==t),d],sa(n),Er(e,true,t);}async function Ty(e,a,o,t,r,i){try{await S(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:i,source:r,scope:t,version:a,duration_ms:o,interface:Z().interfaceType});}catch(s){Io.warn(`Failed to send install metrics: ${String(s)}`);}}async function My(e,a,o,t){try{await S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:t,source:o,error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(r){Io.warn(`Failed to send install-failed metrics: ${String(r)}`);}}async function Ge(e,a={}){let o=Date.now(),t=null;try{Io.debug(`[${e}] Acquiring lock...`),t=await Eo();let{pluginKey:r,alreadyInstalled:i}=xy(e,a.force,a.source),{source:s}=a;Io.debug(`[${e}] Fetching manifest...`);let n=await Bt(e,s);wa(n.name),Ay(n.version),Io.debug(`[${e}] Downloading archive...`);let d=await Lu(e,a.onDownloadProgress,s),l=a.scope??"user",c=a.type??"skill",u=Oc(n.name,n.version,a.source);await Ey(d,u,!!i&&!!a.force),Iy(r,u,n.version,l,"internal",a.providerId,c),Bu(n,u,a.source);let m=Date.now()-o;Io.debug(`[${e}] Installed successfully in ${m}ms`);let p={name:n.name,version:n.version,path:u,duration_ms:m};return a.skipMetrics||await Ty(n.name,n.version,m,$i(l),"internal",c),p}catch(r){throw await My(e,r,"internal",a.type??"skill"),Io.error(`[${e}] Installation failed: ${r instanceof Error?r.message:String(r)}`),r}finally{t&&await t();}}I();j();Se();St();I();var qy=P("commands:helpers");async function me(){let e=await Y();if(!e)return C("Not authenticated. Run: flow auth login"),false;e.customUrl&&Ia(e.customUrl);try{await Ma();}catch(a){return qy.debug(`Token validation failed: ${String(a)}`),C("Session expired. Run: flow auth login"),false}return true}async function de(e){let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(["y","yes"].includes(t.toLowerCase().trim()));});})}async function To(e){let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(t.trim());});})}var Ly="\x1B[A",Fy="\x1B[B";function _u(e,a){let o=a?R.cyan("\u276F"):" ",t=a?R.cyan(e.label):e.label,r=e.description?R.dim(` \u2014 ${e.description}`):"";return ` ${o} ${t}${r}`}function Oy(e,a){return e.map((o,t)=>_u(o,t===a)).join(`
|
|
111
111
|
`)}async function ts(e,a){if(a.length===0)throw new Error("selectPrompt requires at least one option");return new Promise((o,t)=>{let r=0;process.stdout.write(`${b(e)}
|
|
112
|
-
`),process.stdout.write(
|
|
112
|
+
`),process.stdout.write(Oy(a,r));let i="",s=c=>{if(i+=c,i===""){d(),t(new Error("SIGINT"));return}if(i==="\r"||i===`
|
|
113
113
|
`){d(),process.stdout.write(`
|
|
114
|
-
`),o(a[r].value);return}if(i===
|
|
115
|
-
`);}function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",s),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s);})}xo();var Ut=P("claudeProxy"),Cd="claude ",Xu="flow ",Dd=class extends Error{constructor(a){super(`Invalid install command: "${a}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},jt=class extends Error{constructor(a){super(`Disallowed subcommand: "${a}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},
|
|
116
|
-
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!r))throw new Error("No marketplace source provided. Cannot retry install.");r=es(r),o?.(),Ut.debug(`[${t}] Adding marketplace via: claude plugin marketplace add ${r}`);try{let i=await execa("claude",["plugin","marketplace","add",r],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Ut.debug(`[${t}] Marketplace added successfully`);}catch(i){throw Rd(i)?new rs:i}}xo();U();He();I();var Zy=6e4,Mo=class extends Error{url;isTimeout;isAuthError;constructor(a,o,t=false,r=false){super(a),this.name="GitCloneError",this.url=o,this.isTimeout=t,this.isAuthError=r;}};async function Ga(e,a){let o=await mkdtemp(join(tmpdir(),"flow-skills-")),t=simpleGit({timeout:{block:Zy}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),r=a?["--depth","1","--branch",a]:["--depth","1"];try{return await t.clone(e,o,r),o}catch(i){await rm$1(o,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),n=s.includes("block timeout")||s.includes("timed out"),d=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw n?new Mo("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):d?new Mo(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Mo(`Failed to clone ${e}: ${s}`,e,false,false)}}async function Ba(e){let a=normalize(resolve(e)),o=normalize(resolve(tmpdir()));if(!a.startsWith(o+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function st(e,a=["--version"]){try{return (await execa(e,a,{reject:!1})).exitCode===0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return false;throw o}}function ak(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function ok(e){return typeof e=="object"&&e!==null&&e.source==="url"}function tk(e){return typeof e=="object"&&e!==null&&e.source==="github"}function zt(e,a){let o=e.source;if(ak(o)){let t=o.path?o.path.replace(/^\.\//,""):".",r=o.ref&&!/^[0-9a-f]{40}$/i.test(o.ref)?o.ref:void 0;return {cloneUrl:o.url,subPath:t||".",ref:r}}if(ok(o))return {cloneUrl:o.url,subPath:"."};if(tk(o))return {cloneUrl:`https://github.com/${o.repo}`,subPath:"."};if(typeof o=="string"){if(o.startsWith("https://")||o.startsWith("git@"))return {cloneUrl:o,subPath:"."};if((o.startsWith("./")||o===".")&&a){let t=o==="."?".":o.replace(/^\.\//,"")||".";return {cloneUrl:a,subPath:t}}}return null}function na(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var ja=P("claude-code.adapter");function sk(e,a){let o=e??"external";if(!a)return o;let t=a.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!t)return o;let r=t[1],i=Uo();if(!we__default.existsSync(i))return o;try{let s=JSON.parse(we__default.readFileSync(i,"utf-8"));for(let[n,d]of Object.entries(s))if(d.source?.repo===r)return n}catch{}return o}async function sp(e,a){let o=e.catalogId?pe.getAdapter(e.catalogId):void 0,t=zt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=e.type==="bundle"||e.type==null,i=sk(e.catalogId,o?.source),s=a.scope??"user",n;r?n=ln(i,e.name,"external"):n=join(zo(s==="user"?"global":"project"),e.name);let d=null;try{wa(e.name),d=await Ga(t.cloneUrl,t.ref);let l=t.subPath==="."?d:join(d,t.subPath);if(we__default.existsSync(n)&&we__default.rmSync(n,{recursive:!0,force:!0}),we__default.mkdirSync(dirname(n),{recursive:!0}),we__default.cpSync(l,n,{recursive:!0}),r){let c=`${e.name}@${i}`,u=await vd(),m={scope:s,installPath:n,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=u.plugins[c]??[];u.plugins[c]=[...p.filter(h=>h.scope!==s),m],sa(u),Er(c,!0,s);}return {success:!0,message:`Installed ${e.name} from ${t.cloneUrl}`}}catch(l){return ja.debug(`[${e.name}] External catalog install failed: ${String(l)}`),{success:false,message:l instanceof Error?l.message:String(l)}}finally{d&&await Ba(d).catch(()=>{});}}async function Ad(e,a,o,t){try{await S(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:o,source:"external",scope:$i(t),version:"unknown",duration_ms:a,interface:Z().interfaceType});}catch(r){ja.warn(`Failed to send external install metrics: ${String(r)}`);}}async function rp(e,a,o){try{await S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:o,source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(t){ja.warn(`Failed to send external install-failed metrics: ${String(t)}`);}}var nk={async install(e,a){if(e.origin===ut&&!e.installCommand&&!Lt(e.name))return sp(e,a);if(e.origin===ut&&e.installCommand){let o=e.type??"skill",t=await Mr(e.installCommand,a.scope);return t.exitCode===0?(await Ad(e.name,t.duration_ms,o,a.scope),{success:true,message:`Installed ${e.name}`}):(await rp(e.name,new Error(t.stderr||"Install failed"),o),{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`})}if(Lt(e.name)){let o=e.type??"skill",t=Ot(e.name,a.scope);ja.debug(`[${e.name}] Attempting install: ${t}`);let r=await Te(t);if(r.exitCode===0)return await Ad(e.name,r.duration_ms,o,a.scope),{success:true};ja.debug(`[${e.name}] First attempt failed, adding marketplace`),await is(e.name,a.marketplaceSource,()=>{});let i=await Te(t);return i.exitCode===0?(await Ad(e.name,i.duration_ms,o,a.scope),{success:true}):(await rp(e.name,new Error(i.stderr||"Install failed"),o),{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`})}try{let o=await Ge(e.name,{...a,type:e.type});return {success:!0,message:`Installed ${e.name}@${o.version}`}}catch(o){return ja.debug(`[${e.name}] Plugin install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}},async uninstall(e,a){await Ir(e,a);},getInstallPath(e,a){return ""}};function ip(e){return {async install(a,o){if(a.origin===ut&&!a.installCommand&&!Lt(a.name))return sp(a,o);if(!a.installCommand)try{let r=await Ge(a.name,{...o,type:e});return {success:!0,message:`Installed ${a.name}@${r.version}`}}catch(r){return ja.debug(`[${a.name}] ${e} install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}ja.debug(`[${a.name}] Executing install command: ${a.installCommand}`);let t=await Mr(a.installCommand,o.scope);return t.exitCode===0?{success:true}:{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`}},async uninstall(a,o){let t=Ce(),r=`${a}@${le}`;if(t.plugins[r]){await Ir(a,o);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${a}`)},getInstallPath(a,o){return ""}}}function dk(e){for(let a of [join(e,".claude","agents"),join(e,"agents")]){if(!we__default.existsSync(a))continue;let o=we__default.readdirSync(a).filter(t=>t.endsWith(".md")&&we__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}function xd(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,xd(o)]))}function np(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(xd(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(xd(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=np(i,r):o[t]=r;}return o}async function dp(e,a,o,t){let r=await vd(),i=`${e}@claude-code`,s={scope:a,installPath:o,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:t},n=r.plugins[i]??[];r.plugins[i]=[...n.filter(d=>d.scope!==a),s],sa(r);}var ck={async install(e,a){let o=a.scope??"user",t=e.catalogId?pe.getAdapter(e.catalogId):void 0,r=zt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{wa(e.name),i=await Ga(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=dk(s);if(n.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let d=ni(o);we__default.mkdirSync(d,{recursive:!0});let l=na(e.name);if(n.length===1)we__default.copyFileSync(n[0],join(d,`${l}.md`));else for(let u of n){let m=na(basename(u,".md"));we__default.copyFileSync(u,join(d,`${l}--${m}.md`));}let c=n.length===1?join(d,`${l}.md`):d;return await dp(e.name,o,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(s){return ja.debug(`[${e.name}] Agent install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ba(i).catch(()=>{});}},async uninstall(e,a){let o=ni(a),t=na(e);if(we__default.existsSync(o))for(let n of we__default.readdirSync(o).filter(d=>d===`${t}.md`||d.startsWith(`${t}--`)&&d.endsWith(".md")))we__default.rmSync(join(o,n),{force:true});let r=`${e}@claude-code`,i=Ce(),s=(i.plugins[r]??[]).filter(n=>n.scope!==a);if(s.length===0){let{[r]:n,...d}=i.plugins;sa({...i,plugins:d});}else sa({...i,plugins:{...i.plugins,[r]:s}});},getInstallPath(e,a){return join(ni(a),`${na(e)}.md`)}},lk={async install(e,a){let o=a.scope??"user",t=e.catalogId?pe.getAdapter(e.catalogId):void 0,r=zt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{wa(e.name),i=await Ga(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=join(s,"settings.json");if(!we__default.existsSync(n))return {success:!1,message:`No settings.json found in "${e.name}"`};let d;try{d=JSON.parse(we__default.readFileSync(n,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let l=d.hooks;if(!l||typeof l!="object"||Array.isArray(l))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=yr();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let u=c.status==="ok"?c.settings:{},m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=np(m,l);return Ei({...u,hooks:p}),await dp(e.name,o,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(s){return ja.debug(`[${e.name}] Hook install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ba(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,a){return ""}},ss=class{id="claude-code";name="Claude Code";async isAvailable(){return st("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:nk,skill:ip("skill"),mcp:ip("mcp"),agent:ck,hook:lk}};function ns(e,a){return {async install(o,t){if(!o.installCommand)return {success:false,message:"No install command provided"};let[r,...i]=o.installCommand.split(/\s+/).filter(Boolean);if(!r||!e.has(r))return {success:false,message:`Disallowed command: "${r??""}"`};let s=await execa(r,i,{reject:false});return s.exitCode===0?{success:true}:{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`}},async uninstall(o,t){throw new Error(`MCP uninstall not supported \u2014 ${a.replace("<name>",o)}`)},getInstallPath(o,t){return ""}}}var pk=new Set(["gh"]),mk=ns(pk,"use: gh copilot mcp remove <name>"),ds=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await st("gh",["--version"])?st("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:mk}};He();var gk=new Set(["opencode"]),fk=ns(gk,"use: opencode config remove mcp <name>");function hk(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
117
|
-
`)}function cp(){return {async install(e,a){try{wa(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?pe.getAdapter(e.catalogId):void 0,t=zt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Ga(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=si(a.scope??"user"),n=join(i,".opencode","plugins");if(we__default.existsSync(n)){let d=we__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};we__default.mkdirSync(s,{recursive:!0}),we__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);we__default.existsSync(d)&&we__default.rmSync(d,{recursive:!0,force:!0}),we__default.mkdirSync(d,{recursive:!0}),we__default.cpSync(i,d,{recursive:!0}),we__default.mkdirSync(s,{recursive:!0}),we__default.writeFileSync(join(s,`${e.name}.js`),hk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ba(r).catch(()=>{});}},async uninstall(e,a){wa(e);let o=si(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);we__default.existsSync(t)&&we__default.rmSync(t,{force:true}),we__default.existsSync(r)&&we__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(si(a),`${e}.js`)}}}var cs=class{id="opencode";name="OpenCode";async isAvailable(){return st("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:fk,skill:cp(),bundle:cp()}};var Ua=new Ki;Ua.register(new ss);Do()&&(Ua.register(new ds),Ua.register(new cs));function lp({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Ua.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let m=useCallback(g=>{g==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),p=useCallback(g=>{if(g==="Cancel"){n(false);return}let v=d.find(k=>k.name===g);v?(u(v.id),n(false),i(true)):n(false);},[d]),h=useCallback(g=>{let v=ku(g);v?o(v,c):i(false);},[o,c]),f=useCallback(()=>{i(false);},[]);if(s){let g=[...d.map(v=>v.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:vu,descriptions:yu,onAction:h,onClose:f},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:t},"main")}j();function pp({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(h=>h.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(h=>h.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let m=useCallback((h,f)=>{f.upArrow?n(g=>Math.max(0,g-1)):f.downArrow?n(g=>Math.min(u.length-1,g+1)):f.return?u[s]==="Confirm Install"?t():r():f.escape&&r();},[u,s,t,r]);useInput(m,{isActive:i==="actionMenu"&&a!==void 0});let p=useCallback(h=>{h==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(h=>{let f=b(h.name??h.flowId),g=h.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},h.flowId)})}),jsx(Box,{flexDirection:"column",children:u.map((h,f)=>jsx(Box,{children:jsxs(Text,{bold:f===s,color:f===s?"cyan":void 0,children:[f===s?"\u203A ":" ",h]})},h))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:r})}function ps({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}j();function fp({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=ps({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let u=o==="enabled"?"Disable":"Enable",m=r&&b(r),p=m?`Update to v${m}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,p,"Cancel"]:["Uninstall",u,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===u?s(a):g.startsWith("Update")?n?.():d();},onClose:d})}function vp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=ps({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var Ht=P("bundle:installer"),yp=/already exists/i;async function Sk(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if($u(a)){let o=await Yu(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(yp.test(t))return;throw new Error(t)}}else {let o=await Mr(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(yp.test(t))return;throw new Error(t)}}}async function Ck(e,a){try{await S(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){Ht.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function Rk(e,a,o){try{await S(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){Ht.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function kp(e,a,o,t){try{await S(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){Ht.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function Ak(e,a,o,t,r){try{await S(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){Ht.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function fs(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(p=>p.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await Ck(s,r.length);let d=[],l=0,c=r.length;for(let[p,h]of r.entries()){let f=h.name??h.flowId,g=h.type??"unknown";if(!h.type){Ht.warn(`Artifact "${f}" has no type \u2014 treated as failed`),d.push({name:f,type:g,reason:"unknown artifact type"}),await kp(s,f,g,"unknown artifact type"),o?.({index:p+1,total:c,artifact:h,success:false,error:"unknown artifact type"});continue}try{await Sk(h),l++,await Rk(s,f,g),o?.({index:p+1,total:c,artifact:h,success:!0});}catch(v){let k=v instanceof Error?v.message:String(v);Ht.error(`Failed to install artifact "${f}": ${k}`),d.push({name:f,type:g,reason:k}),await kp(s,f,g,k),o?.({index:p+1,total:c,artifact:h,success:false,error:k});}}let u=Date.now()-n,m=d.length;return await Ak(s,l,m,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:m,failures:d}}j();function Sp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,fs(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",b(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:ne()})}));j();function Cp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Ea(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}j();function Rp({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,m=c?.autoUpdate!==false,p=t==="detail",h=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${Ea(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:h.map((f,g)=>{let v=g===r;return jsxs(Box,{children:[jsx(Text,{color:v?"cyan":void 0,children:v?"\u203A ":" "}),jsx(Text,{bold:v,color:f.danger?"yellow":void 0,dimColor:!v,children:f.label})]},f.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Ap(e){return e.adapter.removable!==false?4:2}U();j();function xp({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",b(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:b(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",b(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",b(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:b(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",b(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",b(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",b(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Ip({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Tp({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,M)=>{if(M.escape){t();return}if(M.return){u(n[d]??null);return}if(M.upArrow){l(F=>Math.max(0,F-1));return}M.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(xp,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,d-Math.floor(ea/2)),p=Math.min(n.length,m+ea);p===n.length&&(m=Math.max(0,p-ea));let h=n.slice(m,p),f=m,g=n.length-p,v=i.length>0&&m<i.length,k=p>i.length,T=h.filter(A=>o.has(`${A.name}@${r}`)),L=h.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2191 ${f} more above`:" "})}),v&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),T.map(A=>jsx(Ip,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),k&&jsxs(Box,{flexDirection:"column",marginTop:v?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx(Ip,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}dd();var Lk=/^https?:\/\/.+/;function Fk(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Ok(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Fp(e){let a=y(g=>g.showNotification),o=y(g=>g.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),m=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{m.current=n;},[n]);let p=useCallback(()=>{u.current="",m.current="",s(""),d(""),c(null),r("add-name");},[]),h=useCallback(()=>{r("idle");},[]),f=useCallback(async()=>{let g=m.current,v=u.current;if(!Lk.test(g)){c("URL must start with http:// or https://");return}c(null),r("adding");let k=randomUUID(),T=new Gt(k,v,g);try{await T.fetchItems(),await Za.add({id:k,name:v,source:g}),pe.register(new Gt(k,v,g)),o(),e(),a(`Catalog "${v}" added`,"success"),s(""),d(""),u.current="",m.current="",r("idle");}catch(L){let A=Fk(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Ok(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((g,v)=>{if(v.escape){r("idle");return}if(v.return){u.current.trim().length>0&&r("add-url");return}if(v.backspace||v.delete){u.current=u.current.slice(0,-1),s(u.current);return}g&&!v.ctrl&&!v.meta&&(u.current=u.current+g,s(u.current));},{isActive:t==="add-name"}),useInput((g,v)=>{if(v.escape){r("add-name");return}if(v.return){f();return}if(v.backspace||v.delete){m.current=m.current.slice(0,-1),d(m.current),c(null);return}g&&!v.ctrl&&!v.meta&&(m.current=m.current+g,d(m.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:p,cancelAdd:h}}function Op(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await Za.remove(r),pe.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function Gp(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=fe(E=>E.installedItems),[r,i]=useState(()=>pe.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[m,p]=useState(null),[h,f]=useState("main"),g=useRef(r);useEffect(()=>{g.current=r;},[r]),useEffect(()=>{h==="browse"&&!r[s-1]&&f("main");},[h,r,s]);let v=useCallback(()=>{(async()=>{let E=pe.listAdapters(),B=await Za.read(),Q=new Map(B.map(qe=>[qe.id,qe]));i(E.map(qe=>({adapter:qe,stored:Q.get(qe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),v();},[a,v]),useEffect(()=>{if(s===0){p(null);return}let E=g.current[s-1];if(!E)return;let B=false;return p({items:[],loading:true,error:null}),E.adapter.fetchItems().then(Q=>{B||p({items:Q,loading:false,error:null});}).catch(Q=>{B||p({items:[],loading:false,error:Q instanceof Error?Q.message:"Failed to load catalog"});}),()=>{B=true;}},[s]);let k=Fp(v),T=useCallback(()=>{v(),n(0),l("list"),p(null),f("main");},[v]),{handleRemove:L}=Op(T),A=useCallback(async E=>{f("removing"),await L(E);},[L]),M=useCallback(async E=>{try{let B=await E.adapter.fetchItems();if(p({items:B,loading:!1,error:null}),E.stored){let Q=new Date().toISOString();await Za.updateField(E.stored.id,{lastUpdated:Q}),v();}o("Marketplace updated","success");}catch(B){o(B instanceof Error?B.message:"Update failed","error");}},[v,o]),F=useCallback(async E=>{if(!E.stored)return;let B=E.stored.autoUpdate!==false;await Za.updateField(E.stored.id,{autoUpdate:!B}),v();},[v]),O=useCallback(()=>f("browse"),[]),ae=useCallback(E=>{let B=r[s-1];if(!B)return;let Q=B.adapter.removable!==false;[O,()=>{M(B);},...Q?[()=>{F(B);},()=>{A(B.adapter.id);}]:[]][E]?.();},[r,s,O,M,F,A]),x=useCallback(()=>f("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&M(E);},[r,s,M]),ee=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,B)=>{if(B.upArrow){n(Q=>Math.max(0,Q-1));return}if(B.downArrow){n(Q=>Math.min(r.length,Q+1));return}(B.return||B.tab)&&(s===0?k.startAdd():(l("detail"),u(0)));},{isActive:h==="main"&&k.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,B)=>{if(B.escape||B.tab){l("list");return}if(B.upArrow){u(Q=>Math.max(0,Q-1));return}if(B.downArrow){let Q=r[s-1],qe=Q?Ap(Q)-1:0;u(ei=>Math.min(ei+1,qe));return}B.return&&ae(c);},{isActive:h==="main"&&k.phase==="idle"&&d==="detail"&&e==="marketplaces"}),k.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:k.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(k.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:k.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:k.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:k.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(k.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(h==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(h==="browse"){let E=r[s-1];if(!E)return jsx(Box,{});let B=E.adapter.id??"default",Q=new Set(t.filter(qe=>qe.marketplace===E.adapter.name).map(qe=>`${qe.name}@${B}`));return jsx(Tp,{entry:E,items:m?.items??[],installedKeys:Q,onBack:x})}if(r.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let W=r[s-1]??null,_=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Cp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx(Rp,{entry:W,detailData:m,installedCount:_,focusPanel:d,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:ee,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function Bp(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r-1+re.length)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function jp(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Up(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var Uk=new Set(re.filter(e=>e.focus!=="list").map(e=>e.focus));function zr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function zp({listLength:e}){let a=y(f=>f.focus),o=y(f=>f.selectedIndex),t=y(f=>f.actionMenuOpen),r=y(f=>f.setFocus),i=y(f=>f.setActionMenuOpen),s=_e(f=>f.query),n=_e(f=>f.setQuery),d=_e(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:f,setCursorPosition:g}=_e.getState();g(f.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let f=setTimeout(()=>u(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,g)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Qn(f,g,{activeTab:v}));},{isActive:a==="tabs"}),useInput((f,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Qn("",g,{activeTab:v}));},{isActive:Uk.has(a)}),useInput((f,g)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Bp(f,g,{activeTab:v,selectedIndex:k},l.current));},{isActive:a==="list"}),useInput((f,g)=>{zr(jp(f,g));},{isActive:a==="actionMenu"}),useInput((f,g)=>{let v=Up(f,g,_e.getState().query),k=v.queryUpdate;if(zr(v.actions),k==="reset")d(),u("");else if(k!==null){let{query:T,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in k)L>0&&(n(T.slice(0,L-1)+T.slice(L)),A(L-1));else if("append"in k)n(T.slice(0,L)+k.append+T.slice(L)),A(L+k.append.length);else if("cursorMove"in k){let M=L+k.cursorMove;M>=0&&M<=T.length&&A(M);}}},{isActive:a==="search"});let m=useCallback(()=>{i(false),r("list");},[i,r]),p=useCallback(f=>{let{setSelectedIndex:g,selectedIndex:v}=y.getState();f===0?g(0):v>=f&&g(f-1);},[]),h=useCallback(f=>{if(!c)return l.current=f.length,f;let g=c.toLowerCase(),v=f.filter(k=>k.name.toLowerCase().includes(g)||k.description?.toLowerCase().includes(g));return l.current=v.length,v},[c]);return {actionMenuOpen:t,closeMenu:m,selectedIndex:o,clampIndex:p,filteredItems:h}}function Jp(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function Ue(e,a,o=false){return o?true:!qd.valid(e)||!qd.valid(a)?false:qd.gt(a,e)}U();I();var to=P("updater");async function zk(e,a,o,t,r,i){try{await S(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:Z().interfaceType});}catch(s){to.warn(`Failed to send update metrics: ${String(s)}`);}}function Wk(e){let a=Ce(),o=`${e}@${le}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function ys(e,a={}){let o=Date.now(),t=null;try{to.debug(`[${e}] Acquiring lock...`),t=await Eo();let r=Wk(e);if(!r)throw to.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;to.debug(`[${e}] Fetching manifest...`);let l=(await Bt(e,a.source)).version;if(!s||!Ue(s,l,a.force))throw to.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Ao(e,s??"unknown");to.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await Ge(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await zk(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),to.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){to.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Eo();let u=Ce(),m=`${e}@${le}`;throw u.plugins[m]&&(u.plugins[m][0].version=s,u.plugins[m][0].installPath=n,sa(u),to.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}xo();I();var ks=P("dispatcher");async function Jk(e,a,o,t,r){let i=Ft(e);return ks.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await is(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),ks.debug(`[${e}] Retrying install after marketplace add`),Te(a)}async function Hp(e,a,o,t){let r=Ot(e,t),i=Ft(e);o?.onStatus?.(`Installing ${i}...`),ks.debug(`[${e}] Attempting install: ${r}`);let s=await Te(r);if(s.exitCode===0)return s;ks.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return Jk(e,r,n,a,o)}async function Qp(e,a,o){let t=e.type??"bundle",r=await Ua.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function Vp(){let e=fe(s=>s.installedItems),a=fe(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await Qp(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=ne().find(p=>p.name===s),l=d?.providerId??"claude-code",c=Ua.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",m=c.installers[u];if(!m)throw new Error(`Provider "${l}" does not support type "${u}"`);await m.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Tr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await ys(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}j();I();var Ds=P("mcp");function Wr(e,a){e.silent?Fe({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):C(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function Xp(e,a){e.silent?ye({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):(K(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&D(a.stdout));}function Hk(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function Ld(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function Kp(e,a,o){if(!await me())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return Wr(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Ds.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=Hk(e,a,o.transport,o.scope);if(!o.force){let i=b(e),s=b(t);if(!await de(`Install external MCP "${i}"?
|
|
114
|
+
`),o(a[r].value);return}if(i===Ly){r=(r-1+a.length)%a.length,n(),i="";return}if(i===Fy){r=(r+1)%a.length,n(),i="";return}i.startsWith("\x1B")&&i.length<3||(i="");};function n(){process.stdout.write(`\x1B[${a.length-1}A`);for(let c=0;c<a.length;c++)process.stdout.write(`\r\x1B[2K${_u(a[c],c===r)}`),c<a.length-1&&process.stdout.write(`
|
|
115
|
+
`);}function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",s),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s);})}xo();var Ut=P("claudeProxy"),Cd="claude ",Xu="flow ",Dd=class extends Error{constructor(a){super(`Invalid install command: "${a}". Command must start with "claude " for security.`),this.name="InvalidInstallCommandError";}},jt=class extends Error{constructor(a){super(`Disallowed subcommand: "${a}". Only "plugin install", "plugin marketplace add", "mcp add", and "mcp remove" are permitted.`),this.name="DisallowedSubcommandError";}},Ny=/^plugins?\s+(install|i)\s+|^plugins?\s+marketplace\s+add\s+|^mcp\s+(add|remove)\s+/,Gy=/^--(scope|transport|env|header|timeout|prefix-args|timeout-ms|local|global|user)$/,By={"--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}$/},jy=/^npm\s+(i|install)\s+-g\s+@ciandt-flow\/cli$/,Uy=/^(flow|claude)\s+auth\s+login(\s|$)/,Ku=/^flow\s+plugins?\s+(install|i)\s+([^@\s]+)$/;function $u(e){return Ku.test(e.trim())}function zy(e){return Ku.exec(e.trim())?.[2]??""}async function Yu(e){let a=zy(e);sd(a);let o=Date.now();Ut.debug(`[${a}] Executing: flow plugin install ${a}`);try{let t=await execa("flow",["plugin","install",a],{reject:!1});return {name:a,command:`flow plugin install ${a}`,exitCode:t.exitCode??1,stdout:t.stdout,stderr:t.stderr,duration_ms:Date.now()-o}}catch(t){throw Rd(t)?new wd:t}}function Wy(e){Zu(e);let a=e.slice(Cd.length);if(!Ny.test(a))throw new jt(e)}var rs=class extends Error{constructor(){super('Claude Code CLI not found. Ensure "claude" is installed and available on your PATH.'),this.name="ClaudeCliNotFoundError";}},wd=class extends Error{constructor(){super('Flow CLI not found. Ensure "flow" is installed and available on your PATH.'),this.name="FlowCliNotFoundError";}};function Zu(e){if(!e||!/^claude /.test(e))throw new Dd(e)}function Jy(e){for(let a=0;a<e.length;a++){let o=e[a];if(o==="--")return;if(!o.startsWith("-"))continue;if(!Gy.test(o))throw new jt(`Unexpected flag: ${o}`);let t=By[o];if(t!==void 0){let r=e[a+1];if(r===void 0||r.startsWith("-"))throw new jt(`Flag ${o} requires a value`);if(!t.test(r))throw new jt(`Unsafe value for flag ${o}`);a++;}}}async function Te(e){Zu(e);let a=e.slice(Cd.length).split(/\s+/).filter(Boolean);Jy(a);let o=Hy(a);Ut.debug(`[${o}] Executing proxy command: claude ${a.join(" ")}`);let t=Date.now();try{let r=await execa("claude",a,{reject:!1}),i=Date.now()-t;return Ut.debug(`[${o}] Proxy command finished with exit code ${r.exitCode} in ${i}ms`),{name:o,command:e,exitCode:r.exitCode??1,stdout:r.stdout,stderr:r.stderr,duration_ms:i}}catch(r){throw Rd(r)?new rs:r}}function Hy(e){return e.length>=3?e[2]:e.join(" ")}function Rd(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"}function Qy(e){return e.startsWith(Xu)?Cd+e.slice(Xu.length):e}function Vy(e){return jy.test(e)||Uy.test(e)}function _y(e){let a=0;for(;a<e.length&&Vy(e[a]);)a++;return e.slice(a)}var Xy=/^claude\s+(?:plugins?\s+(?:install|i)\s+|mcp\s+(?:add|remove)\s+)/;function Ky(e,a){return !a||e.includes("--scope")||!Xy.test(e)?e:`${e} --scope ${a}`}async function Mr(e,a){let o=e.split("&&").map(s=>s.trim()).filter(Boolean),r=_y(o).map(s=>Qy(s)).map(s=>Ky(s,a));if(r.length===0)throw new Error("Empty install command");for(let s of r)Wy(s);Ut.debug(`[installCommand] Executing ${r.length} command(s)`);let i=await Te(r[0]);if(i.exitCode!==0)return i;for(let s=1;s<r.length;s++)if(i=await Te(r[s]),i.exitCode!==0)return i;return i}async function is(e,a,o){let t=Ft(e),r=a?.trim();if(!r&&(r=(await To(`Plugin "${t}" could not be installed.
|
|
116
|
+
If a marketplace is needed, enter the source (owner/repo or URL), or press Enter to skip: `))?.trim(),!r))throw new Error("No marketplace source provided. Cannot retry install.");r=es(r),o?.(),Ut.debug(`[${t}] Adding marketplace via: claude plugin marketplace add ${r}`);try{let i=await execa("claude",["plugin","marketplace","add",r],{reject:!1});if(i.exitCode!==0)throw new Error(`Failed to add marketplace: ${i.stderr||"unknown error"}`);Ut.debug(`[${t}] Marketplace added successfully`);}catch(i){throw Rd(i)?new rs:i}}xo();U();He();I();var ak=6e4,Mo=class extends Error{url;isTimeout;isAuthError;constructor(a,o,t=false,r=false){super(a),this.name="GitCloneError",this.url=o,this.isTimeout=t,this.isAuthError=r;}};async function Ga(e,a){let o=await mkdtemp(join(tmpdir(),"flow-skills-")),t=simpleGit({timeout:{block:ak}}).env("GIT_TERMINAL_PROMPT","0").env("GIT_LFS_SKIP_SMUDGE","1"),r=a?["--depth","1","--branch",a]:["--depth","1"];try{return await t.clone(e,o,r),o}catch(i){await rm$1(o,{recursive:true,force:true}).catch(()=>{});let s=i instanceof Error?i.message:String(i),n=s.includes("block timeout")||s.includes("timed out"),d=s.includes("Authentication failed")||s.includes("could not read Username")||s.includes("Permission denied")||s.includes("Repository not found");throw n?new Mo("Clone timed out after 60s. Check your SSH keys or credentials.",e,true,false):d?new Mo(`Authentication failed for ${e}. Ensure you have access and credentials are configured.`,e,false,true):new Mo(`Failed to clone ${e}: ${s}`,e,false,false)}}async function Ba(e){let a=normalize(resolve(e)),o=normalize(resolve(tmpdir()));if(!a.startsWith(o+sep))throw new Error("Attempted to clean up directory outside of temp directory");await rm$1(e,{recursive:true,force:true});}async function st(e,a=["--version"]){try{return (await execa(e,a,{reject:!1})).exitCode===0}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return false;throw o}}function tk(e){return typeof e=="object"&&e!==null&&e.source==="git-subdir"}function rk(e){return typeof e=="object"&&e!==null&&e.source==="url"}function ik(e){return typeof e=="object"&&e!==null&&e.source==="github"}function zt(e,a){let o=e.source;if(tk(o)){let t=o.path?o.path.replace(/^\.\//,""):".",r=o.ref&&!/^[0-9a-f]{40}$/i.test(o.ref)?o.ref:void 0;return {cloneUrl:o.url,subPath:t||".",ref:r}}if(rk(o))return {cloneUrl:o.url,subPath:"."};if(ik(o))return {cloneUrl:`https://github.com/${o.repo}`,subPath:"."};if(typeof o=="string"){if(o.startsWith("https://")||o.startsWith("git@"))return {cloneUrl:o,subPath:"."};if((o.startsWith("./")||o===".")&&a){let t=o==="."?".":o.replace(/^\.\//,"")||".";return {cloneUrl:a,subPath:t}}}return null}function na(e){return e.toLowerCase().replace(/[^a-z0-9._]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").substring(0,255)||"unnamed"}var ja=P("claude-code.adapter");function dk(e,a){let o=e??"external";if(!a)return o;let t=a.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?(?:[/?#]|$)/);if(!t)return o;let r=t[1],i=Uo();if(!we__default.existsSync(i))return o;try{let s=JSON.parse(we__default.readFileSync(i,"utf-8"));for(let[n,d]of Object.entries(s))if(d.source?.repo===r)return n}catch{}return o}async function sp(e,a){let o=e.catalogId?pe.getAdapter(e.catalogId):void 0,t=zt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=e.type==="bundle"||e.type==null,i=dk(e.catalogId,o?.source),s=a.scope??"user",n;r?n=ln(i,e.name,"external"):n=join(zo(s==="user"?"global":"project"),e.name);let d=null;try{wa(e.name),d=await Ga(t.cloneUrl,t.ref);let l=t.subPath==="."?d:join(d,t.subPath);if(we__default.existsSync(n)&&we__default.rmSync(n,{recursive:!0,force:!0}),we__default.mkdirSync(dirname(n),{recursive:!0}),we__default.cpSync(l,n,{recursive:!0}),r){let c=`${e.name}@${i}`,u=await vd(),m={scope:s,installPath:n,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:e.type},p=u.plugins[c]??[];u.plugins[c]=[...p.filter(h=>h.scope!==s),m],sa(u),Er(c,!0,s);}return {success:!0,message:`Installed ${e.name} from ${t.cloneUrl}`}}catch(l){return ja.debug(`[${e.name}] External catalog install failed: ${String(l)}`),{success:false,message:l instanceof Error?l.message:String(l)}}finally{d&&await Ba(d).catch(()=>{});}}async function Ad(e,a,o,t){try{await S(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:o,source:"external",scope:$i(t),version:"unknown",duration_ms:a,interface:Z().interfaceType});}catch(r){ja.warn(`Failed to send external install metrics: ${String(r)}`);}}async function rp(e,a,o){try{await S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:o,source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(t){ja.warn(`Failed to send external install-failed metrics: ${String(t)}`);}}var ck={async install(e,a){if(e.origin===ut&&!e.installCommand&&!Lt(e.name))return sp(e,a);if(e.origin===ut&&e.installCommand){let o=e.type??"skill",t=await Mr(e.installCommand,a.scope);return t.exitCode===0?(await Ad(e.name,t.duration_ms,o,a.scope),{success:true,message:`Installed ${e.name}`}):(await rp(e.name,new Error(t.stderr||"Install failed"),o),{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`})}if(Lt(e.name)){let o=e.type??"skill",t=Ot(e.name,a.scope);ja.debug(`[${e.name}] Attempting install: ${t}`);let r=await Te(t);if(r.exitCode===0)return await Ad(e.name,r.duration_ms,o,a.scope),{success:true};ja.debug(`[${e.name}] First attempt failed, adding marketplace`),await is(e.name,a.marketplaceSource,()=>{});let i=await Te(t);return i.exitCode===0?(await Ad(e.name,i.duration_ms,o,a.scope),{success:true}):(await rp(e.name,new Error(i.stderr||"Install failed"),o),{success:false,message:i.stderr||`Install failed with exit code ${i.exitCode}`})}try{let o=await Ge(e.name,{...a,type:e.type});return {success:!0,message:`Installed ${e.name}@${o.version}`}}catch(o){return ja.debug(`[${e.name}] Plugin install failed: ${String(o)}`),{success:false,message:o instanceof Error?o.message:String(o)}}},async uninstall(e,a){await Ir(e,a);},getInstallPath(e,a){return ""}};function ip(e){return {async install(a,o){if(a.origin===ut&&!a.installCommand&&!Lt(a.name))return sp(a,o);if(!a.installCommand)try{let r=await Ge(a.name,{...o,type:e});return {success:!0,message:`Installed ${a.name}@${r.version}`}}catch(r){return ja.debug(`[${a.name}] ${e} install failed: ${String(r)}`),{success:false,message:r instanceof Error?r.message:String(r)}}ja.debug(`[${a.name}] Executing install command: ${a.installCommand}`);let t=await Mr(a.installCommand,o.scope);return t.exitCode===0?{success:true}:{success:false,message:t.stderr||`Install failed with exit code ${t.exitCode}`}},async uninstall(a,o){let t=Ce(),r=`${a}@${le}`;if(t.plugins[r]){await Ir(a,o);return}throw new Error(`${e.toUpperCase()} uninstall via claude CLI not supported \u2014 use: claude ${e} remove ${a}`)},getInstallPath(a,o){return ""}}}function lk(e){for(let a of [join(e,".claude","agents"),join(e,"agents")]){if(!we__default.existsSync(a))continue;let o=we__default.readdirSync(a).filter(t=>t.endsWith(".md")&&we__default.lstatSync(join(a,t)).isFile());if(o.length>0)return o.map(t=>join(a,t))}return []}function xd(e){return e===null||typeof e!="object"||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).sort(([a],[o])=>a.localeCompare(o)).map(([a,o])=>[a,xd(o)]))}function np(e,a){let o={...e};for(let[t,r]of Object.entries(a)){let i=o[t];if(Array.isArray(r)&&Array.isArray(i)){let s=new Set(i.map(n=>JSON.stringify(xd(n))));o[t]=[...i,...r.filter(n=>!s.has(JSON.stringify(xd(n))))];}else r!==null&&typeof r=="object"&&!Array.isArray(r)&&i!==null&&typeof i=="object"&&!Array.isArray(i)?o[t]=np(i,r):o[t]=r;}return o}async function dp(e,a,o,t){let r=await vd(),i=`${e}@claude-code`,s={scope:a,installPath:o,version:"external",installedAt:new Date().toISOString(),origin:"external",providerId:"claude-code",type:t},n=r.plugins[i]??[];r.plugins[i]=[...n.filter(d=>d.scope!==a),s],sa(r);}var uk={async install(e,a){let o=a.scope??"user",t=e.catalogId?pe.getAdapter(e.catalogId):void 0,r=zt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{wa(e.name),i=await Ga(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=lk(s);if(n.length===0)return {success:!1,message:`No agent files found in "${e.name}"`};let d=ni(o);we__default.mkdirSync(d,{recursive:!0});let l=na(e.name);if(n.length===1)we__default.copyFileSync(n[0],join(d,`${l}.md`));else for(let u of n){let m=na(basename(u,".md"));we__default.copyFileSync(u,join(d,`${l}--${m}.md`));}let c=n.length===1?join(d,`${l}.md`):d;return await dp(e.name,o,c,"agent"),{success:!0,message:`Installed agent(s) from ${e.name}`}}catch(s){return ja.debug(`[${e.name}] Agent install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ba(i).catch(()=>{});}},async uninstall(e,a){let o=ni(a),t=na(e);if(we__default.existsSync(o))for(let n of we__default.readdirSync(o).filter(d=>d===`${t}.md`||d.startsWith(`${t}--`)&&d.endsWith(".md")))we__default.rmSync(join(o,n),{force:true});let r=`${e}@claude-code`,i=Ce(),s=(i.plugins[r]??[]).filter(n=>n.scope!==a);if(s.length===0){let{[r]:n,...d}=i.plugins;sa({...i,plugins:d});}else sa({...i,plugins:{...i.plugins,[r]:s}});},getInstallPath(e,a){return join(ni(a),`${na(e)}.md`)}},pk={async install(e,a){let o=a.scope??"user",t=e.catalogId?pe.getAdapter(e.catalogId):void 0,r=zt(e,t?.source);if(!r)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let i=null;try{wa(e.name),i=await Ga(r.cloneUrl,r.ref);let s=r.subPath==="."?i:join(i,r.subPath),n=join(s,"settings.json");if(!we__default.existsSync(n))return {success:!1,message:`No settings.json found in "${e.name}"`};let d;try{d=JSON.parse(we__default.readFileSync(n,"utf-8"));}catch{return {success:!1,message:`settings.json in "${e.name}" contains invalid JSON`}}let l=d.hooks;if(!l||typeof l!="object"||Array.isArray(l))return {success:!1,message:`No hooks found in "${e.name}" settings.json`};let c=yr();if(c.status==="malformed")return {success:!1,message:"settings.json at destination contains invalid JSON \u2014 refusing to overwrite"};let u=c.status==="ok"?c.settings:{},m=u.hooks!==null&&typeof u.hooks=="object"&&!Array.isArray(u.hooks)?u.hooks:{},p=np(m,l);return Ei({...u,hooks:p}),await dp(e.name,o,"hooks","hook"),{success:!0,message:`Installed hooks from ${e.name}`}}catch(s){return ja.debug(`[${e.name}] Hook install failed: ${String(s)}`),{success:false,message:s instanceof Error?s.message:String(s)}}finally{i&&await Ba(i).catch(()=>{});}},async uninstall(e,a){throw new Error("Hook uninstall not supported \u2014 remove entries manually from settings.json")},getInstallPath(e,a){return ""}},ss=class{id="claude-code";name="Claude Code";async isAvailable(){return st("claude",["--version"])}getSupportedScopes(){return ["user","project","local"]}installers={bundle:ck,skill:ip("skill"),mcp:ip("mcp"),agent:uk,hook:pk}};function ns(e,a){return {async install(o,t){if(!o.installCommand)return {success:false,message:"No install command provided"};let[r,...i]=o.installCommand.split(/\s+/).filter(Boolean);if(!r||!e.has(r))return {success:false,message:`Disallowed command: "${r??""}"`};let s=await execa(r,i,{reject:false});return s.exitCode===0?{success:true}:{success:false,message:s.stderr||`Install failed with exit code ${s.exitCode}`}},async uninstall(o,t){throw new Error(`MCP uninstall not supported \u2014 ${a.replace("<name>",o)}`)},getInstallPath(o,t){return ""}}}var gk=new Set(["gh"]),fk=ns(gk,"use: gh copilot mcp remove <name>"),ds=class{id="copilot";name="GitHub Copilot";async isAvailable(){return await st("gh",["--version"])?st("gh",["copilot","--version"]):false}getSupportedScopes(){return ["user"]}installers={mcp:fk}};He();var hk=new Set(["opencode"]),bk=ns(hk,"use: opencode config remove mcp <name>");function vk(e){return [`// Auto-generated by Flow CLI for OpenCode compatibility \u2014 plugin: ${e}`,"import { readFileSync, readdirSync, existsSync } from 'node:fs';","import { join, dirname } from 'node:path';","import { fileURLToPath } from 'node:url';","",`const CONTENT_DIR = join(dirname(fileURLToPath(import.meta.url)), '${e}-content');`,"","function loadContent() {"," for (const dir of ['skills', '.']) {"," const d = join(CONTENT_DIR, dir);"," if (!existsSync(d)) continue;"," const files = readdirSync(d)"," .filter(f => f.endsWith('.md') && f !== 'README.md' && f !== 'LICENSE.md')"," .sort();"," if (files.length) return files.map(f => readFileSync(join(d, f), 'utf-8')).join('\\n\\n---\\n\\n');"," }"," return '';","}","","export const Plugin = async () => ({ getBootstrapContent: () => loadContent() });"].join(`
|
|
117
|
+
`)}function cp(){return {async install(e,a){try{wa(e.name);}catch{return {success:false,message:"Invalid plugin name."}}let o=e.catalogId?pe.getAdapter(e.catalogId):void 0,t=zt(e,o?.source);if(!t)return {success:false,message:`Cannot install "${e.name}": unsupported source format.`};let r=null;try{r=await Ga(t.cloneUrl,t.ref);let i=t.subPath==="."?r:join(r,t.subPath),s=si(a.scope??"user"),n=join(i,".opencode","plugins");if(we__default.existsSync(n)){let d=we__default.readdirSync(n).filter(l=>l.endsWith(".js")||l.endsWith(".mjs"));if(d.length===0)return {success:!1,message:"No JS plugin file found in .opencode/plugins/"};we__default.mkdirSync(s,{recursive:!0}),we__default.copyFileSync(join(n,d[0]),join(s,`${e.name}.js`));}else {let d=join(s,`${e.name}-content`);we__default.existsSync(d)&&we__default.rmSync(d,{recursive:!0,force:!0}),we__default.mkdirSync(d,{recursive:!0}),we__default.cpSync(i,d,{recursive:!0}),we__default.mkdirSync(s,{recursive:!0}),we__default.writeFileSync(join(s,`${e.name}.js`),vk(e.name),"utf-8");}return {success:!0,message:`Installed ${e.name} for OpenCode`}}catch(i){return {success:false,message:i instanceof Error?i.message:String(i)}}finally{r&&await Ba(r).catch(()=>{});}},async uninstall(e,a){wa(e);let o=si(a),t=join(o,`${e}.js`),r=join(o,`${e}-content`);we__default.existsSync(t)&&we__default.rmSync(t,{force:true}),we__default.existsSync(r)&&we__default.rmSync(r,{recursive:true,force:true});},getInstallPath(e,a){return join(si(a),`${e}.js`)}}}var cs=class{id="opencode";name="OpenCode";async isAvailable(){return st("opencode",["--version"])}getSupportedScopes(){return ["user","project"]}installers={mcp:bk,skill:cp(),bundle:cp()}};var Ua=new Ki;Ua.register(new ss);Do()&&(Ua.register(new ds),Ua.register(new cs));function lp({itemName:e,itemType:a,onInstall:o,onClose:t}){let[r,i]=useState(false),[s,n]=useState(false),[d,l]=useState([]),[c,u]=useState(void 0);useEffect(()=>{Ua.getAvailableProviders(a??"bundle").then(l).catch(()=>{});},[a]);let m=useCallback(g=>{g==="Install"?d.length>1?n(true):i(true):t();},[t,d.length]),p=useCallback(g=>{if(g==="Cancel"){n(false);return}let v=d.find(k=>k.name===g);v?(u(v.id),n(false),i(true)):n(false);},[d]),h=useCallback(g=>{let v=ku(g);v?o(v,c):i(false);},[o,c]),f=useCallback(()=>{i(false);},[]);if(s){let g=[...d.map(v=>v.name),"Cancel"];return jsx(ra,{itemName:`${e} \u2014 Choose provider`,actions:g,onAction:p,onClose:()=>n(false)},"provider")}return r?jsx(ra,{itemName:`${e} \u2014 Choose scope`,actions:vu,descriptions:yu,onAction:h,onClose:f},"scope"):jsx(ra,{itemName:e,actions:["Install","Cancel"],onAction:m,onClose:t},"main")}j();function pp({itemName:e,bundle:a,onInstall:o,onConfirm:t,onClose:r}){let i=y(h=>h.focus),[s,n]=useState(0),l=(a?.artifact.artifacts??[]).filter(h=>h.available),c=a!==void 0&&l.length===0,u=useMemo(()=>c?["Cancel"]:["Confirm Install","Cancel"],[c]);useEffect(()=>{n(0);},[a]);let m=useCallback((h,f)=>{f.upArrow?n(g=>Math.max(0,g-1)):f.downArrow?n(g=>Math.min(u.length-1,g+1)):f.return?u[s]==="Confirm Install"?t():r():f.escape&&r();},[u,s,t,r]);useInput(m,{isActive:i==="actionMenu"&&a!==void 0});let p=useCallback(h=>{h==="Install Bundle"?o():r();},[o,r]);return a?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:a.title}),jsx(Box,{marginTop:1,children:jsxs(Text,{children:[l.length," artifact",l.length!==1?"s":""," available"]})}),jsx(Box,{flexDirection:"column",marginTop:1,marginBottom:1,children:l.map(h=>{let f=b(h.name??h.flowId),g=h.type??"unknown";return jsxs(Box,{gap:1,children:[jsx(Text,{color:"green",children:"\u2713"}),jsx(Text,{children:f}),jsxs(Text,{dimColor:true,children:["(",g,")"]})]},h.flowId)})}),jsx(Box,{flexDirection:"column",children:u.map((h,f)=>jsx(Box,{children:jsxs(Text,{bold:f===s,color:f===s?"cyan":void 0,children:[f===s?"\u203A ":" ",h]})},h))})]}):jsx(ra,{itemName:e,actions:["Install Bundle","Cancel"],onAction:p,onClose:r})}function ps({activeFocus:e,onConfirm:a}){let[o,t]=useState("idle"),r=y(i=>i.focus);return useInput((i,s)=>{s.escape||i==="n"?t("idle"):i==="y"&&a();},{isActive:o==="confirming"&&r===e}),{isConfirming:o==="confirming",requestConfirm:()=>t("confirming"),cancelConfirm:()=>t("idle")}}j();function fp({itemName:e,itemScope:a,itemStatus:o,updateAvailable:t,catalogVersion:r,onUninstall:i,onToggleStatus:s,onUpdate:n,onClose:d}){let{isConfirming:l,requestConfirm:c}=ps({activeFocus:"actionMenu",onConfirm:()=>i(a)});if(l)return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Uninstall "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]});let u=o==="enabled"?"Disable":"Enable",m=r&&b(r),p=m?`Update to v${m}`:"Update";return jsx(ra,{itemName:e,actions:t?["Uninstall",u,p,"Cancel"]:["Uninstall",u,"Cancel"],onAction:g=>{g==="Uninstall"?c():g===u?s(a):g.startsWith("Update")?n?.():d();},onClose:d})}function vp({itemName:e,itemScope:a,onUninstall:o,onClose:t}){let{isConfirming:r,requestConfirm:i}=ps({activeFocus:"actionMenu",onConfirm:()=>o(a)});return r?jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,flexShrink:0,children:[jsx(Text,{bold:true,children:e}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Remove MCP "}),jsx(Text,{bold:true,color:"red",children:e}),jsx(Text,{children:"? (y/N)"})]})]}):jsx(ra,{itemName:e,actions:["Uninstall","Cancel"],onAction:d=>{d==="Uninstall"?i():t();},onClose:t})}I();var Ht=P("bundle:installer"),yp=/already exists/i;async function Rk(e){if(!e.installCommand)throw new Error("Missing install command");let a=e.installCommand;if($u(a)){let o=await Yu(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(yp.test(t))return;throw new Error(t)}}else {let o=await Mr(a);if(o.exitCode!==0){let t=o.stderr?.trim()||o.stdout?.trim()||`exit code ${o.exitCode}`;if(yp.test(t))return;throw new Error(t)}}}async function Ak(e,a){try{await S(w.CLI_BUNDLE_INSTALL_STARTED,{bundle_slug:e,artifact_count:a});}catch(o){Ht.warn(`Failed to emit bundle install started event: ${String(o)}`);}}async function xk(e,a,o){try{await S(w.CLI_BUNDLE_INSTALL_PLUGIN_SUCCESS,{bundle_slug:e,artifact_name:a,artifact_type:o});}catch(t){Ht.warn(`Failed to emit bundle install plugin success event: ${String(t)}`);}}async function kp(e,a,o,t){try{await S(w.CLI_BUNDLE_INSTALL_PLUGIN_FAILED,{bundle_slug:e,artifact_name:a,artifact_type:o,error_message:t});}catch(r){Ht.warn(`Failed to emit bundle install plugin failed event: ${String(r)}`);}}async function Ek(e,a,o,t,r){try{await S(w.CLI_BUNDLE_INSTALL_COMPLETED,{bundle_slug:e,installed_count:a,failed_count:o,unavailable_count:t,duration_ms:r});}catch(i){Ht.warn(`Failed to emit bundle install completed event: ${String(i)}`);}}async function fs(e,a={}){let{onProgress:o}=a,t=e.artifact.artifacts,r=t.filter(p=>p.available),i=t.length-r.length,s=e.artifact.name,n=Date.now();await Ak(s,r.length);let d=[],l=0,c=r.length;for(let[p,h]of r.entries()){let f=h.name??h.flowId,g=h.type??"unknown";if(!h.type){Ht.warn(`Artifact "${f}" has no type \u2014 treated as failed`),d.push({name:f,type:g,reason:"unknown artifact type"}),await kp(s,f,g,"unknown artifact type"),o?.({index:p+1,total:c,artifact:h,success:false,error:"unknown artifact type"});continue}try{await Rk(h),l++,await xk(s,f,g),o?.({index:p+1,total:c,artifact:h,success:!0});}catch(v){let k=v instanceof Error?v.message:String(v);Ht.error(`Failed to install artifact "${f}": ${k}`),d.push({name:f,type:g,reason:k}),await kp(s,f,g,k),o?.({index:p+1,total:c,artifact:h,success:false,error:k});}}let u=Date.now()-n,m=d.length;return await Ek(s,l,m,i,u),{bundleTitle:e.title,total:t.length,installed:l,skipped:i,failed:m,failures:d}}j();function Sp({bundle:e,onComplete:a}){let[o,t]=useState(null),[r,i]=useState(null),s=useRef(false);return useEffect(()=>{s.current||(s.current=true,fs(e,{onProgress:t}).then(i).catch(n=>{let d=n instanceof Error?n.message:"Installation failed",l=e.artifact.artifacts,c=l.filter(u=>u.available);i({bundleTitle:e.title,total:l.length,installed:0,skipped:l.length-c.length,failed:c.length,failures:c.map(u=>({name:u.name??u.flowId,type:u.type??"unknown",reason:d}))});}));},[e]),useEffect(()=>{r&&a(r);},[r,a]),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingBottom:1,children:jsxs(Text,{bold:true,children:["Installing ",e.title,"..."]})}),o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:["[",o.index,"/",o.total,"] Installing"," ",b(o.artifact.name??o.artifact.flowId)," (",o.artifact.type??"unknown",")"]})]}),!o&&jsxs(Box,{gap:1,children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsx(Text,{color:"cyan",children:"Preparing..."})]})]})}var fe=create(e=>({installedItems:[],setInstalledItems:a=>e({installedItems:a}),loadFromDisk:()=>e({installedItems:ne()})}));j();function Cp({entries:e,selectedIndex:a,focusPanel:o}){let t=o==="list",r=a===0&&t;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{marginBottom:1,children:[jsx(Text,{color:"cyan",bold:true,children:r?"\u203A ":" "}),jsx(Text,{color:"cyan",bold:r,dimColor:!t,children:"+ Add Marketplace"})]}),e.map((i,s)=>{let n=s+1,d=a===n&&t,l=i.stored?.autoUpdate!==false;return jsxs(Box,{flexDirection:"column",marginBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:d?"\u203A ":" "}),jsx(Text,{bold:d,dimColor:!t,children:i.adapter.name}),l&&i.stored&&jsx(Text,{color:"yellow",children:" \u2605"})]}),i.stored?.lastUpdated&&jsx(Box,{marginLeft:2,children:jsxs(Text,{dimColor:true,children:["Updated ",Ea(i.stored.lastUpdated)]})})]},i.adapter.id)})]})}j();function Rp({entry:e,detailData:a,installedCount:o,focusPanel:t,actionIndex:r,onBrowse:i,onUpdate:s,onToggleAutoUpdate:n,onRemove:d}){let{adapter:l,stored:c}=e,u=l.removable!==false,m=c?.autoUpdate!==false,p=t==="detail",h=[{label:`Browse plugins${a&&!a.loading?` (${a.items.length})`:""}`,handler:i},{label:"Update marketplace",handler:s},...u?[{label:"Toggle auto-update",handler:n},{label:"Remove marketplace",handler:d,danger:true}]:[]];return p?jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:a?.loading?jsx(Text,{dimColor:true,children:"Loading..."}):a?.error?jsx(Text,{color:"red",children:a.error}):jsxs(Text,{dimColor:true,children:[a?`${a.items.length} available`:"\u2014 available",o>0?` \xB7 ${o} installed`:"",c?.lastUpdated?` \xB7 Updated ${Ea(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:h.map((f,g)=>{let v=g===r;return jsxs(Box,{children:[jsx(Text,{color:v?"cyan":void 0,children:v?"\u203A ":" "}),jsx(Text,{bold:v,color:f.danger?"yellow":void 0,dimColor:!v,children:f.label})]},f.label)})})]}):jsxs(Box,{flexDirection:"column",paddingLeft:1,children:[jsx(Text,{bold:true,children:l.name}),jsx(Text,{dimColor:true,children:l.source}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab to see details"})})]})}function Ap(e){return e.adapter.removable!==false?4:2}U();j();function xp({item:e,adapterName:a,isInstalled:o,onBack:t,onInstall:r,onUninstall:i}){let s=[...o&&i?[{label:"Uninstall",handler:()=>i(e),danger:true}]:!o&&r?[{label:"Install",handler:()=>r(e)}]:[],{label:"Back",handler:t}],[n,d]=useState(0);return useInput((l,c)=>{if(c.escape){t();return}if(c.upArrow){d(u=>Math.max(0,u-1));return}if(c.downArrow){d(u=>Math.min(s.length-1,u+1));return}c.return&&s[n].handler();}),jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",a," \u203A Browse plugins \u203A ",b(e.name)]}),jsxs(Box,{marginTop:1,flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{bold:true,children:b(e.name)}),e.type&&jsxs(Text,{dimColor:true,children:[" [",b(e.type),"]"]}),e.origin&&jsxs(Text,{dimColor:true,children:[" [",b(e.origin),"]"]})]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2500".repeat(50)})}),e.description?jsx(Box,{marginTop:1,children:jsx(Text,{children:b(e.description)})}):null,(e.author?.name||e.version||e.category)&&jsxs(Box,{flexDirection:"column",marginTop:1,children:[e.author?.name&&jsxs(Text,{dimColor:true,children:["Author ",b(e.author.name)]}),e.version&&jsxs(Text,{dimColor:true,children:["Version ",b(e.version)]}),e.category&&jsxs(Text,{dimColor:true,children:["Category ",b(e.category)]})]})]}),jsx(Box,{flexDirection:"column",marginTop:1,children:s.map((l,c)=>jsxs(Box,{children:[jsx(Text,{color:c===n?"cyan":void 0,children:c===n?"\u203A ":" "}),jsx(Text,{bold:c===n,color:l.danger?"yellow":void 0,dimColor:c!==n,children:l.label})]},l.label))}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter: confirm \xB7 Esc: back"})})]})}function Ip({item:e,isSelected:a,isInstalled:o}){return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:a?"\u203A ":" "}),jsx(Text,{color:o?"green":void 0,bold:a,children:e.name}),o&&jsx(Text,{color:"green",children:" \u2713"})]}),e.description?jsx(Box,{paddingLeft:4,children:jsx(Text,{dimColor:true,wrap:"truncate",children:e.description})}):null]})}function Tp({entry:e,items:a,installedKeys:o,onBack:t}){let r=e.adapter.id??"default",i=a.filter(A=>o.has(`${A.name}@${r}`)),s=a.filter(A=>!o.has(`${A.name}@${r}`)),n=[...i,...s],[d,l]=useState(0),[c,u]=useState(null);if(useInput((A,M)=>{if(M.escape){t();return}if(M.return){u(n[d]??null);return}if(M.upArrow){l(F=>Math.max(0,F-1));return}M.downArrow&&l(F=>Math.min(n.length-1,F+1));},{isActive:c===null}),c!==null)return jsx(xp,{item:c,adapterName:e.adapter.name,isInstalled:o.has(`${c.name}@${r}`),onBack:()=>u(null)});if(a.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Empty catalog"})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Esc: back"})})]});let m=Math.max(0,d-Math.floor(ea/2)),p=Math.min(n.length,m+ea);p===n.length&&(m=Math.max(0,p-ea));let h=n.slice(m,p),f=m,g=n.length-p,v=i.length>0&&m<i.length,k=p>i.length,T=h.filter(A=>o.has(`${A.name}@${r}`)),L=h.filter(A=>!o.has(`${A.name}@${r}`));return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsxs(Text,{dimColor:true,children:["Marketplaces \u203A ",e.adapter.name," \u203A Browse plugins"]}),jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:f>0?`\u2191 ${f} more above`:" "})}),v&&jsxs(Box,{flexDirection:"column",children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Installed (",i.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),T.map(A=>jsx(Ip,{item:A,isSelected:n.indexOf(A)===d,isInstalled:true},A.name))]}),k&&jsxs(Box,{flexDirection:"column",marginTop:v?1:0,children:[jsxs(Text,{dimColor:true,children:["\u2500\u2500 Available (",s.length,") \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]}),L.map(A=>jsx(Ip,{item:A,isSelected:n.indexOf(A)===d,isInstalled:false},A.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"})})]})}dd();var Ok=/^https?:\/\/.+/;function Nk(e){return e!==null&&typeof e=="object"&&"response"in e&&e.response?.status===404}function Gk(e){return e instanceof Error&&e.code==="GITHUB_AUTH_REQUIRED"}function Fp(e){let a=y(g=>g.showNotification),o=y(g=>g.incrementCatalogVersion),[t,r]=useState("idle"),[i,s]=useState(""),[n,d]=useState(""),[l,c]=useState(null),u=useRef(""),m=useRef("");useEffect(()=>{u.current=i;},[i]),useEffect(()=>{m.current=n;},[n]);let p=useCallback(()=>{u.current="",m.current="",s(""),d(""),c(null),r("add-name");},[]),h=useCallback(()=>{r("idle");},[]),f=useCallback(async()=>{let g=m.current,v=u.current;if(!Ok.test(g)){c("URL must start with http:// or https://");return}c(null),r("adding");let k=randomUUID(),T=new Gt(k,v,g);try{await T.fetchItems(),await Za.add({id:k,name:v,source:g}),pe.register(new Gt(k,v,g)),o(),e(),a(`Catalog "${v}" added`,"success"),s(""),d(""),u.current="",m.current="",r("idle");}catch(L){let A=Nk(L)?"No marketplace.json found in this repository (checked main and master branches). Ensure the repo has a marketplace.json at its root.":Gk(L)?L.message:L instanceof Error?`Could not reach catalog URL: ${L.message}`:"Failed to validate catalog URL";a(A,"error"),r("add-url");}},[e,a,o]);return useInput((g,v)=>{if(v.escape){r("idle");return}if(v.return){u.current.trim().length>0&&r("add-url");return}if(v.backspace||v.delete){u.current=u.current.slice(0,-1),s(u.current);return}g&&!v.ctrl&&!v.meta&&(u.current=u.current+g,s(u.current));},{isActive:t==="add-name"}),useInput((g,v)=>{if(v.escape){r("add-name");return}if(v.return){f();return}if(v.backspace||v.delete){m.current=m.current.slice(0,-1),d(m.current),c(null);return}g&&!v.ctrl&&!v.meta&&(m.current=m.current+g,d(m.current),c(null));},{isActive:t==="add-url"}),{phase:t,inputName:i,inputUrl:n,urlError:l,setInputName:s,setInputUrl:d,startAdd:p,cancelAdd:h}}function Op(e){let a=y(r=>r.showNotification),o=y(r=>r.incrementCatalogVersion);return {handleRemove:useCallback(async r=>{try{await Za.remove(r),pe.unregister(r),o(),e(),a("Catalog removed","success");}catch(i){a(i instanceof Error?i.message:"Failed to remove catalog","error");}},[e,a,o])}}function Gp(){let e=y(E=>E.focus),a=y(E=>E.setFocus),o=y(E=>E.showNotification),t=fe(E=>E.installedItems),[r,i]=useState(()=>pe.listAdapters().map(E=>({adapter:E,stored:null}))),[s,n]=useState(0),[d,l]=useState("list"),[c,u]=useState(0),[m,p]=useState(null),[h,f]=useState("main"),g=useRef(r);useEffect(()=>{g.current=r;},[r]),useEffect(()=>{h==="browse"&&!r[s-1]&&f("main");},[h,r,s]);let v=useCallback(()=>{(async()=>{let E=pe.listAdapters(),B=await Za.read(),Q=new Map(B.map(qe=>[qe.id,qe]));i(E.map(qe=>({adapter:qe,stored:Q.get(qe.id)??null})));})();},[]);useEffect(()=>{a("marketplaces"),v();},[a,v]),useEffect(()=>{if(s===0){p(null);return}let E=g.current[s-1];if(!E)return;let B=false;return p({items:[],loading:true,error:null}),E.adapter.fetchItems().then(Q=>{B||p({items:Q,loading:false,error:null});}).catch(Q=>{B||p({items:[],loading:false,error:Q instanceof Error?Q.message:"Failed to load catalog"});}),()=>{B=true;}},[s]);let k=Fp(v),T=useCallback(()=>{v(),n(0),l("list"),p(null),f("main");},[v]),{handleRemove:L}=Op(T),A=useCallback(async E=>{f("removing"),await L(E);},[L]),M=useCallback(async E=>{try{let B=await E.adapter.fetchItems();if(p({items:B,loading:!1,error:null}),E.stored){let Q=new Date().toISOString();await Za.updateField(E.stored.id,{lastUpdated:Q}),v();}o("Marketplace updated","success");}catch(B){o(B instanceof Error?B.message:"Update failed","error");}},[v,o]),F=useCallback(async E=>{if(!E.stored)return;let B=E.stored.autoUpdate!==false;await Za.updateField(E.stored.id,{autoUpdate:!B}),v();},[v]),O=useCallback(()=>f("browse"),[]),ae=useCallback(E=>{let B=r[s-1];if(!B)return;let Q=B.adapter.removable!==false;[O,()=>{M(B);},...Q?[()=>{F(B);},()=>{A(B.adapter.id);}]:[]][E]?.();},[r,s,O,M,F,A]),x=useCallback(()=>f("main"),[]),J=useCallback(()=>{let E=r[s-1];E&&M(E);},[r,s,M]),ee=useCallback(()=>{let E=r[s-1];E&&F(E);},[r,s,F]),z=useCallback(()=>{let E=r[s-1];E&&A(E.adapter.id);},[r,s,A]);if(useInput((E,B)=>{if(B.upArrow){n(Q=>Math.max(0,Q-1));return}if(B.downArrow){n(Q=>Math.min(r.length,Q+1));return}(B.return||B.tab)&&(s===0?k.startAdd():(l("detail"),u(0)));},{isActive:h==="main"&&k.phase==="idle"&&d==="list"&&e==="marketplaces"}),useInput((E,B)=>{if(B.escape||B.tab){l("list");return}if(B.upArrow){u(Q=>Math.max(0,Q-1));return}if(B.downArrow){let Q=r[s-1],qe=Q?Ap(Q)-1:0;u(ei=>Math.min(ei+1,qe));return}B.return&&ae(c);},{isActive:h==="main"&&k.phase==="idle"&&d==="detail"&&e==="marketplaces"}),k.phase==="add-name")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 1/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{children:"Name: "}),jsx(Text,{color:"cyan",children:k.inputName}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.inputName.trim().length===0&&jsx(Text,{dimColor:true,children:"Enter a display name for this catalog"}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: next | Esc: cancel"})})]});if(k.phase==="add-url")return jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Text,{bold:true,children:"Add Catalog \u2014 Step 2/2"}),jsxs(Box,{marginTop:1,children:[jsx(Text,{dimColor:true,children:"Name: "}),jsx(Text,{children:k.inputName})]}),jsxs(Box,{children:[jsx(Text,{children:"URL: "}),jsx(Text,{color:"cyan",children:k.inputUrl}),jsx(Text,{color:"gray",children:"\u2588"})]}),k.urlError&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"red",children:k.urlError})}),jsx(Box,{marginTop:1,children:jsx(Text,{dimColor:true,children:"Enter: confirm | Esc: back | Must start with http:// or https://"})})]});if(k.phase==="adding")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Validating catalog URL..."})});if(h==="removing")return jsx(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:jsx(Text,{children:"Removing catalog..."})});if(h==="browse"){let E=r[s-1];if(!E)return jsx(Box,{});let B=E.adapter.id??"default",Q=new Set(t.filter(qe=>qe.marketplace===E.adapter.name).map(qe=>`${qe.name}@${B}`));return jsx(Tp,{entry:E,items:m?.items??[],installedKeys:Q,onBack:x})}if(r.length===0)return jsxs(Box,{flexDirection:"column",paddingX:1,children:[jsx(Box,{paddingX:1,marginBottom:1,children:jsx(Text,{bold:true,children:"Marketplaces"})}),jsx(Box,{paddingX:2,children:jsx(Text,{dimColor:true,children:"No catalogs registered"})}),jsx(Box,{marginTop:1,paddingX:1,children:jsx(Text,{dimColor:true,children:"Enter or Tab: add marketplace \xB7 \u2190\u2192: switch tab"})})]});let W=r[s-1]??null,_=W?t.filter(E=>E.marketplace===W.adapter.name).length:0;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Box,{flexDirection:"column",width:30,marginRight:1,children:jsx(Cp,{entries:r,selectedIndex:s,focusPanel:d})}),jsx(Box,{flexDirection:"column",flexGrow:1,children:d==="detail"&&W?jsx(Rp,{entry:W,detailData:m,installedCount:_,focusPanel:d,actionIndex:c,onBrowse:O,onUpdate:J,onToggleAutoUpdate:ee,onRemove:z}):jsx(Box,{paddingLeft:1,children:jsx(Text,{dimColor:true,children:W?"Enter or Tab to see details":"\u2191\u2193 to navigate, Enter or Tab to see details"})})})]}),jsx(Box,{marginTop:1,paddingX:1,children:d==="list"?jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate \xB7 Enter / Tab: see details \xB7 \u2190\u2192: switch tab"}):jsx(Text,{dimColor:true,children:"\u2191\u2193 navigate actions \xB7 Enter: execute \xB7 Esc / Tab: back to list"})})]})}function Bp(e,a,o,t){if(a.upArrow)return o.selectedIndex===0?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"}]:[{type:"setSelectedIndex",index:o.selectedIndex-1}];if(a.downArrow&&o.selectedIndex<t-1)return [{type:"setSelectedIndex",index:o.selectedIndex+1}];if(a.leftArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r-1+re.length)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.rightArrow){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}if(a.tab){let r=re.findIndex(s=>s.id===o.activeTab),i=re[(r+1)%re.length];return [{type:"setTab",tab:i.id},{type:"setSelectedIndex",index:0},{type:"setFocus",focus:i.focus}]}return a.return?[{type:"setActionMenuOpen",open:true},{type:"setFocus",focus:"actionMenu"}]:e==="/"?[{type:"setFocus",focus:"search"}]:e==="1"?[{type:"selectAllTypes"}]:e==="2"?[{type:"toggleTypeFilter",catalogType:"skill"}]:e==="3"?[{type:"toggleTypeFilter",catalogType:"mcp"}]:e==="4"?[{type:"toggleTypeFilter",catalogType:"bundle"}]:e==="5"?[{type:"selectAllOrigins"}]:e==="6"?[{type:"toggleOriginFilter",origin:"internal"}]:e==="7"?[{type:"toggleOriginFilter",origin:"external"}]:e==="a"&&o.activeTab==="updates"?[]:e&&e!==" "&&!a.ctrl&&!a.meta&&!a.escape?[{type:"setSelectedIndex",index:-1},{type:"setFocus",focus:"search"},{type:"searchAppend",char:e}]:[]}function jp(e,a){return a.escape?[{type:"setActionMenuOpen",open:false},{type:"setFocus",focus:"list"}]:[]}function Up(e,a,o){return a.escape?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:"reset"}:a.downArrow?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.leftArrow?{actions:[],queryUpdate:{cursorMove:-1}}:a.rightArrow?{actions:[],queryUpdate:{cursorMove:1}}:a.return?{actions:[{type:"setSelectedIndex",index:0},{type:"setFocus",focus:"list"}],queryUpdate:null}:a.backspace?o.length===0?{actions:[{type:"setFocus",focus:"list"},{type:"setSelectedIndex",index:0}],queryUpdate:null}:{actions:[],queryUpdate:{backspace:true}}:e&&!a.ctrl&&!a.meta?{actions:[],queryUpdate:{append:e}}:{actions:[],queryUpdate:null}}var Wk=new Set(re.filter(e=>e.focus!=="list").map(e=>e.focus));function zr(e){let{setActiveTab:a,setFocus:o,setSelectedIndex:t,setActionMenuOpen:r}=y.getState();for(let i of e)if(i.type==="setTab")a(i.tab);else if(i.type==="setFocus")o(i.focus);else if(i.type==="setSelectedIndex")t(i.index);else if(i.type==="setActionMenuOpen")r(i.open);else if(i.type==="searchAppend"){let{setQuery:s,query:n,setCursorPosition:d,cursorPosition:l}=_e.getState();s(n.slice(0,l)+i.char+n.slice(l)),d(l+i.char.length);}else i.type==="toggleTypeFilter"?y.getState().toggleTypeFilter(i.catalogType):i.type==="selectAllTypes"?y.getState().selectAllTypes():i.type==="toggleOriginFilter"?y.getState().toggleOriginFilter(i.origin):i.type==="selectAllOrigins"&&y.getState().selectAllOrigins();}function zp({listLength:e}){let a=y(f=>f.focus),o=y(f=>f.selectedIndex),t=y(f=>f.actionMenuOpen),r=y(f=>f.setFocus),i=y(f=>f.setActionMenuOpen),s=_e(f=>f.query),n=_e(f=>f.setQuery),d=_e(f=>f.resetQuery),l=useRef(e);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{if(a==="search"){let{query:f,setCursorPosition:g}=_e.getState();g(f.length);}},[a]);let[c,u]=useState("");useEffect(()=>{let f=setTimeout(()=>u(s),300);return ()=>clearTimeout(f)},[s]),useInput((f,g)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Qn(f,g,{activeTab:v}));},{isActive:a==="tabs"}),useInput((f,g)=>{if(!g.leftArrow&&!g.rightArrow)return;let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Qn("",g,{activeTab:v}));},{isActive:Wk.has(a)}),useInput((f,g)=>{let{activeTab:v,selectedIndex:k,actionMenuOpen:T}=y.getState();zr(Bp(f,g,{activeTab:v,selectedIndex:k},l.current));},{isActive:a==="list"}),useInput((f,g)=>{zr(jp(f,g));},{isActive:a==="actionMenu"}),useInput((f,g)=>{let v=Up(f,g,_e.getState().query),k=v.queryUpdate;if(zr(v.actions),k==="reset")d(),u("");else if(k!==null){let{query:T,cursorPosition:L,setCursorPosition:A}=_e.getState();if("backspace"in k)L>0&&(n(T.slice(0,L-1)+T.slice(L)),A(L-1));else if("append"in k)n(T.slice(0,L)+k.append+T.slice(L)),A(L+k.append.length);else if("cursorMove"in k){let M=L+k.cursorMove;M>=0&&M<=T.length&&A(M);}}},{isActive:a==="search"});let m=useCallback(()=>{i(false),r("list");},[i,r]),p=useCallback(f=>{let{setSelectedIndex:g,selectedIndex:v}=y.getState();f===0?g(0):v>=f&&g(f-1);},[]),h=useCallback(f=>{if(!c)return l.current=f.length,f;let g=c.toLowerCase(),v=f.filter(k=>k.name.toLowerCase().includes(g)||k.description?.toLowerCase().includes(g));return l.current=v.length,v},[c]);return {actionMenuOpen:t,closeMenu:m,selectedIndex:o,clampIndex:p,filteredItems:h}}function Jp(){let e=y(n=>n.notification),a=y(n=>n.showNotification),o=y(n=>n.clearNotification),t=oa(n=>n.justAuthenticated),r=oa(n=>n.credentials),i=oa(n=>n.setJustAuthenticated);return useEffect(()=>{t&&r&&(a(`Authenticated. Tenant: ${r.tenant}`,"success"),i(false));},[t,r]),useEffect(()=>{if(!e)return;let n=setTimeout(o,3e3);return ()=>clearTimeout(n)},[e]),{notify:(n,d)=>{a(n,d);}}}function Ue(e,a,o=false){return o?true:!qd.valid(e)||!qd.valid(a)?false:qd.gt(a,e)}U();I();var to=P("updater");async function Jk(e,a,o,t,r,i){try{await S(w.CLI_TOOL_UPDATED,{tool_id:e,tool_type:i,source:r,from_version:a,to_version:o,duration_ms:t,interface:Z().interfaceType});}catch(s){to.warn(`Failed to send update metrics: ${String(s)}`);}}function Hk(e){let a=Ce(),o=`${e}@${le}`,t=a.plugins[o];return !t||t.length===0?null:{pluginKey:o,entry:t[0]}}async function ys(e,a={}){let o=Date.now(),t=null;try{to.debug(`[${e}] Acquiring lock...`),t=await Eo();let r=Hk(e);if(!r)throw to.error(`[${e}] Plugin is not installed`),new Error(`Plugin "${e}" is not installed`);let{entry:i}=r,s=i.version,n=i.installPath;to.debug(`[${e}] Fetching manifest...`);let l=(await Bt(e,a.source)).version;if(!s||!Ue(s,l,a.force))throw to.debug(`[${e}] Already up to date (v${s??"n/a"})`),new Ao(e,s??"unknown");to.info(`[${e}] Updating v${s} \u2192 v${l}...`),await t(),t=null;try{let c=await Ge(e,{force:!0,skipMetrics:!0,source:a.source}),u=Date.now()-o;return await Jk(c.name,s,c.version,u,i.origin??"internal",i.type??"skill"),to.debug(`[${e}] Updated successfully in ${u}ms`),{name:c.name,previousVersion:s,newVersion:c.version,path:c.path,duration_ms:u}}catch(c){to.warn(`[${e}] Install failed, rolling back to v${s}...`),t=await Eo();let u=Ce(),m=`${e}@${le}`;throw u.plugins[m]&&(u.plugins[m][0].version=s,u.plugins[m][0].installPath=n,sa(u),to.info(`[${e}] Rollback completed, restored to v${s}`)),c}}finally{t&&await t();}}xo();I();var ks=P("dispatcher");async function Qk(e,a,o,t,r){let i=Ft(e);return ks.debug(`[${e}] Install failed (exit code), attempting marketplace add`),r?.onError?.(o),t?r?.onStatus?.(`Adding marketplace for ${i}...`):r?.onPause?.(),await is(e,t,()=>{}),r?.onResume?.(`Retrying install for ${i}...`),ks.debug(`[${e}] Retrying install after marketplace add`),Te(a)}async function Hp(e,a,o,t){let r=Ot(e,t),i=Ft(e);o?.onStatus?.(`Installing ${i}...`),ks.debug(`[${e}] Attempting install: ${r}`);let s=await Te(r);if(s.exitCode===0)return s;ks.debug(`[${e}] Install failed (exit ${s.exitCode}), attempting marketplace add`);let n=s.stderr||`Install failed with exit code ${s.exitCode}`;return Qk(e,r,n,a,o)}async function Qp(e,a,o){let t=e.type??"bundle",r=await Ua.getAvailableProviders(t),i=r[0];if(!i)throw new Error(`No available provider for artifact type "${t}"`);let s=i.installers[t];if(!s)throw new Error(`Provider "${i.id}" does not support type "${t}"`);let n=a??{},d=n;return s.install(e,d)}function Vp(){let e=fe(s=>s.installedItems),a=fe(s=>s.loadFromDisk),o=useCallback(async(s,n)=>{let d=await Qp(s,n);if(!d.success)throw new Error(d.message||"Installation failed");a();},[a]),t=useCallback(async(s,n)=>{let d=ne().find(p=>p.name===s),l=d?.providerId??"claude-code",c=Ua.getAdapter(l);if(!c)throw new Error(`Provider "${l}" not found`);let u=d?.type??"bundle",m=c.installers[u];if(!m)throw new Error(`Provider "${l}" does not support type "${u}"`);await m.uninstall(s,n??"user"),a();},[a]),r=useCallback(async(s,n)=>{let l=e.find(c=>c.name===s)?.status==="enabled"?"disabled":"enabled";await Tr(s,l,n),a();},[e,a]),i=useCallback(async s=>{await ys(s),a();},[a]);return {install:o,uninstall:t,toggle:r,update:i}}j();I();var Ds=P("mcp");function Wr(e,a){e.silent?Fe({status:"error",mcp:a.name,...a.exitCode!==void 0&&{exitCode:a.exitCode},message:a.message}):C(`Failed to ${a.action} MCP "${a.name}": ${a.message}`);}function Xp(e,a){e.silent?ye({status:"success",mcp:a.name,command:a.command,duration_ms:a.durationMs}):(K(`MCP "${a.name}" ${a.actionPastTense} successfully`),e.verbose&&a.stdout&&D(a.stdout));}function Vk(e,a,o,t){let r=["claude","mcp","add","--transport",o,e];return a.length>0&&r.push(...a),t&&r.push("--scope",t),r.join(" ")}function Ld(e,a){if(e.startsWith("-"))throw new Error(`Invalid MCP server name: "${e}". Names must not start with '-'.`);let o=["claude","mcp","remove",e];return a&&o.push("--scope",a),o.join(" ")}async function Kp(e,a,o){if(!await me())return 1;if(a.length===0){let i=o.transport==="http"?"a URL":"a command";return Wr(o,{name:e,action:"add",message:`${o.transport} transport requires ${i}`}),1}Ds.debug(`[${e}] Starting MCP add with args: ${a.join(" ")}`);let t=Vk(e,a,o.transport,o.scope);if(!o.force){let i=b(e),s=b(t);if(!await de(`Install external MCP "${i}"?
|
|
118
118
|
This will run: ${s}
|
|
119
119
|
[y/N] `))return Ds.debug(`[${e}] Installation cancelled by user`),D("Operation cancelled."),0}let r=o.silent?void 0:nc({text:`Adding MCP "${b(e)}"...`}).start();try{let i=await Te(t);return r?.stop(),i.exitCode!==0?(Wr(o,{name:e,action:"add",message:i.stderr||"Command failed",exitCode:i.exitCode}),!o.silent&&o.verbose&&i.stdout&&D(`stdout: ${i.stdout}`),1):(Xp(o,{name:e,actionPastTense:"added",command:t,durationMs:i.duration_ms,stdout:i.stdout}),0)}catch(i){return r?.stop(),Wr(o,{name:e,action:"add",message:$(i)}),1}}async function $p(e,a){if(!await me())return 1;Ds.debug(`[${e}] Starting MCP remove`);let o=Ld(e,a.scope);if(!a.force){let r=b(e),i=b(o);if(!await de(`Remove MCP "${r}"?
|
|
120
120
|
This will run: ${i}
|
|
121
|
-
[y/N] `))return Ds.debug(`[${e}] Removal cancelled by user`),D("Operation cancelled."),0}let t=a.silent?void 0:nc({text:`Removing MCP "${b(e)}"...`}).start();try{let r=await Te(o);return t?.stop(),r.exitCode!==0?(Wr(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&D(`stdout: ${r.stdout}`),1):(Xp(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),Wr(a,{name:e,action:"remove",message:$(r)}),1}}I();function Yp({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=P("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:m,update:p}=Vp(),h=async(A,M,F)=>{d(true,A),t();try{await M(),r(o.length),i(F,"success");}catch(O){let ae=O instanceof Error?O.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${ae}`),i(ae,"error");}finally{d(false);}};return {handleInstall:(A,M)=>{e&&a&&(n.current=0,h(`Installing ${e.name}...`,()=>c(a,{scope:A,...M!==void 0?{providerId:M}:{},onDownloadProgress:(F,O)=>{let ae=Date.now();(ae-n.current>100||F>=O)&&(n.current=ae,l(F,O));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&h(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let M=e.status==="enabled";h(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,A),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await p(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Ao)i(F.message,"info");else {let O=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${O}`),i(O,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let M=A.length;(async()=>{d(true,`Updating ${M} plugin${M>1?"s":""}...`),t();try{let O=[];for(let J of A)O.push(await p(J.name).then(()=>({status:"fulfilled",value:void 0}),ee=>({status:"rejected",reason:ee})));let ae=O.filter(J=>J.status==="fulfilled").length,x=O.map((J,ee)=>J.status==="rejected"?A[ee].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${ae}/${M} plugin${M>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${ae}/${M}; failed: ${x.join(", ")}`,ae>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&h(`Removing MCP ${e.name}...`,async()=>{let M=Ld(e.name,A),F=await Te(M);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Cr();I();var Jr=P("api:bundle"),Kt=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Hr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},_k=/^[a-zA-Z0-9_-]{1,128}$/;async function em(e,a){if(e instanceof HTTPError){let o=e.response.status;throw Jr.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new Kt(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Hr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw Jr.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function am(e){if(!_k.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);Jr.debug(`Fetching bundle by flowId "${e}"`);try{return await Ya().get(`v1/use-cases/${a}`).json()}catch(o){return em(o,e)}}async function ws(e){let a=encodeURIComponent(e);Jr.debug(`Fetching bundle by name "${e}"`);let o;try{o=await Ya().get(`v1/use-cases/by-name/${a}`).json(),Jr.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return em(t,e)}if(o.length===0)throw new Kt(e);return o[0]}I();var Xk=P("tui:bundle-flow");function om({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();Xk.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?am(u):ws(n)).then(p=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{l(false),a(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),fe.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}j();U();var Qr=["local","project","user"],Kk=new Set(["--transport","--scope","-s"]);function tm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(Kk.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function dt(e,a){return a?`${e}::${a}`:e}function Fd(e){return e===le?ir:ut}function rm(e){return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??ir,flowId:e.flowId}}function Od(e,a){let o=Fd(e.marketplace);return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function im(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return Qr.filter(o=>a.has(o)).map(o=>({scope:o,label:Va[o].label,pathHint:Va[o].pathHint,items:a.get(o)??[]}))}function sm(e){let a=o=>{if(!o)return 1/0;let t=Qr.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function nm({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(h=>dt(h.name,h.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(h=>h.type==="mcp").map(h=>h.name.toLowerCase())),[a]),n=useMemo(()=>{let h=new Map(e.map(g=>[dt(g.name,g.author?.name),g])),f=new Map(e.map(g=>[g.name,g]));return a.map(g=>{let v=h.get(dt(g.name,g.author?.name))??f.get(g.name),k=v?.version,T=!!k&&!!g.version&&Ue(g.version,k);return {...g,updateAvailable:T,catalogItem:v}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(h=>{if(i.has(dt(h.name,h.author?.name)))return false;if(h.type==="mcp"){let f=h.installCommand?tm(h.installCommand)?.toLowerCase():null;if(s.has(h.name.toLowerCase())||f&&s.has(f))return false}return true}).map(h=>rm(h)):o==="updates"?n.filter(h=>h.updateAvailable).map(h=>Od(h,h.catalogItem)):n.map(h=>Od(h,h.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(h=>{let f=h.type??"bundle";if(!t.types.has(f))return false;let g=h.origin??"internal";return t.origins.has(g)}),[d,t]),c=useMemo(()=>{let{types:h}=t;if(h.size===1){if(h.has("skill"))return "skills";if(h.has("mcp"))return "MCPs";if(h.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),m=useMemo(()=>{let h=new Map(e.map(g=>[dt(g.name,g.author?.name),g])),f=new Map(e.map(g=>[g.name,g]));return g=>g?h.get(dt(g.name,g.authorName))??f.get(g.name)??null:null},[e]),p=useMemo(()=>n.filter(h=>h.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:m,outdatedCount:p}}function Nd(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:m}=await qu();if(a(u),m.length>0){let p=m.map(h=>h.adapterName).join(", ");n(`Some catalogs failed to load: ${p}`);}d.current||(d.current=!0,S(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function dm(){return {items:fe(a=>a.installedItems)}}I();var aP=P("catalog");function lm(){let e=y(X=>X.bundleInstallFlow),a=y(X=>X.activeTab),o=y(X=>X.notification),t=y(X=>X.loading),r=y(X=>X.loadingMessage),i=y(X=>X.downloadProgress),s=y(X=>X.downloadTotal),n=y(X=>X.catalogError),d=y(X=>X.setCatalogError),l=y(X=>X.catalogFilters),c=_e(X=>X.query),{catalog:u,isLoading:m,error:p,refetch:h}=Nd(),{items:f}=dm(),g=fe(X=>X.loadFromDisk),{items:v,emptyMessage:k,getSelectedCatalogItem:T,outdatedCount:L}=nm({catalog:u,installedItems:f,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:M,selectedIndex:F,clampIndex:O,filteredItems:ae}=zp({listLength:v.length}),x=ae(v),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:sm(x),[a,x]),ee=useMemo(()=>a==="installed"||a==="updates"?im(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>T(z),[T,z]),{notify:_}=Jp(),{handleInstall:E,handleUninstall:B,handleToggleStatus:Q,handleUpdate:qe,handleBatchUpdate:ei,handleMcpConfigUninstall:Zf}=Yp({selectedItem:z,selectedCatalogItem:W,items:v,closeMenu:M,clampIndex:O,notify:_}),{handleBundleInstallStart:eh,handleBundleDetailConfirm:ah,handleBundleDetailBack:oh,handleBundleInstallComplete:th}=om({closeMenu:M,notify:_}),rh=useCallback(()=>ei(J),[ei,J]);return useEffect(()=>{g();},[]),useEffect(()=>{O(J.length);},[J.length,O]),useEffect(()=>{p&&(aP.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),d("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsx(Vl,{outdatedCount:L}),a==="marketplaces"&&Do()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Gp,{})}):jsx(cu,{filteredItems:J,groups:ee,emptyMessage:k,onBatchUpdate:rh}),(t||m)&&jsxs(Fragment,{children:[jsx(Hi,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(Vi,{received:i,total:s})})]}),n&&!m&&a==="discover"&&jsx(_i,{message:n,onRetry:()=>{d(null),h();},onBack:()=>d(null)}),o&&jsx(lu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Sp,{bundle:e.bundle,onComplete:th}):jsx(pp,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>eh(z.name,z.flowId),onConfirm:ah,onClose:e?.phase==="detail"?oh:M}):jsx(lp,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:M}):z.type==="mcp"?jsx(vp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:Zf,onClose:M}):jsx(fp,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:B,onToggleStatus:X=>Q(X),onUpdate:qe,onClose:M})),jsx(Ji,{})]})}var q=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(fe.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Se();var sP=3;function pm(){let e=q(c=>c.setStarterKits),a=q(c=>c.setIsLoadingStarterKits),o=q(c=>c.setStarterKitsError),t=q(c=>c.setPluginStatus),r=q(c=>c.setPluginDownloadProgress),i=q(c=>c.setStep),s=q(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await as();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{fe.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=q.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){t(m.name,"installing"),d.current=0;let p="",h=false;for(let f=1;f<=sP;f++)try{await Ge(m.name,{onDownloadProgress:(g,v)=>{let k=Date.now();(k-d.current>100||g>=v)&&(d.current=k,r(m.name,g,v));}}),t(m.name,"success"),h=!0;break}catch(g){if(g instanceof Xe){t(m.name,"success"),h=true;break}p=g instanceof Error?g.message:"Unknown error";}h||(t(m.name,"failed",p),S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Z().interfaceType}).catch(()=>{}));}let u=_o();Vo("summary_review"),S(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),fe.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var Vr={cursorDelta:0,confirm:false,back:false};function mm(e,a){return a.upArrow?{...Vr,cursorDelta:-1}:a.downArrow?{...Vr,cursorDelta:1}:a.escape?{...Vr,back:true}:a.return?{...Vr,confirm:true}:Vr}var nP={cursorDelta:0,select:false};function gm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:nP}j();var fm=tv.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:b(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:b(a.description)})})]})});var Jd=5;function hm({onRetry:e}){let a=q(c=>c.starterKits),o=q(c=>c.selectedStarterKitIndex),t=q(c=>c.isLoadingStarterKits),r=q(c=>c.starterKitsError);if(t)return jsx(Hi,{message:"Loading Starter Kits..."});if(r)return jsx(_i,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(It,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(Jd/2)),s=Math.min(a.length,i+Jd);s===a.length&&(i=Math.max(0,s-Jd));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(fm,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var vm=tv.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",b(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});j();var Vd=8;function ym(){let e=q(c=>c.selectedStarterKit),a=q(c=>c.plugins),o=q(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,S(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(Vd/2)),s=Math.min(a.length,i+Vd);s===a.length&&(i=Math.max(0,s-Vd));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:b(e.name)}),jsx(Text,{dimColor:true,children:b(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(vm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var hP=["Retry failed","Continue anyway"];function km({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=b(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(Vi,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function Pm({onComplete:e,onRetry:a}){let o=q(l=>l.plugins),t=q(l=>l.step),r=q(l=>l.successCount),i=q(l=>l.failedCount),s=q(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:n.map(l=>jsx(km,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(km,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:hP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Dm(){let e=q(x=>x.step),a=q(x=>x.starterKits),o=q(x=>x.selectedStarterKitIndex),t=q(x=>x.setSelectedStarterKitIndex),r=q(x=>x.selectStarterKit),i=q(x=>x.plugins),s=q(x=>x.pluginCursorIndex),n=q(x=>x.setPluginCursorIndex),d=q(x=>x.setStep),l=q(x=>x.summaryActionIndex),c=q(x=>x.setSummaryActionIndex),u=q(x=>x.failedCount),m=q(x=>x.resetForRetry),p=q(x=>x.goBackToList),h=y(x=>x.setScreen),f=y(x=>x.setFocus),g=y(x=>x.focus),v=oa(x=>x.setJustAuthenticated),k=oa(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:L}=pm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),A.current||(A.current=true,Vo("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let M=useCallback(async()=>{let x=q.getState().selectedStarterKit;if(x){let ee=await Y();ee&&await bo({...ee,starterKit:x.slug});}S(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:_o()}).catch(()=>{});let{successCount:J}=q.getState();S(w.CLI_ONBOARDING_COMPLETED,{duration_ms:yo(),tools_installed_count:J}).catch(()=>{}),v(false),f("verify"),h("verify");},[v,f,h]),F=useCallback(()=>{m(),L();},[m,L]),O=useCallback(()=>{T();},[T]),ae=useCallback(()=>{f("verify"),h("verify");},[f,h]);return useInput((x,J)=>{if(J.escape)Ai("esc"),ae();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ee=_o();r(a[o]),Vo("kit_display"),S(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ee}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((x,J)=>{let ee=mm(x,J);if(ee.cursorDelta!==0){let z=s+ee.cursorDelta;z>=0&&z<i.length&&n(z);}if(ee.confirm){let z=q.getState().selectedStarterKit;z&&(async()=>(await Y())?.starterKit!==z.slug&&S(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=_o();Vo("kit_confirmation"),S(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let _=_o();Vo("tool_installation"),S(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:_}).catch(()=>{}),d("installing"),L();}if(ee.back){let z=q.getState().selectedStarterKit;z&&S(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ee=gm(x,J);if(ee.cursorDelta!==0){let z=l+ee.cursorDelta;z>=0&&z<=1&&c(z);}ee.select&&(l===0?F():M());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!k&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(hm,{onRetry:O}),e==="starterKitDetail"&&jsx(ym,{}),(e==="installing"||e==="summary")&&jsx(Pm,{onComplete:M,onRetry:F})]}),jsx(Ji,{})]})}U();var Cm=null;function Rm(){return Cm}async function Ts(){let a=Zo().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=se.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await Am(t);(r||i)&&await ya({...o,installedVersion:r,installMethod:i});}}async function Am(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await Oa(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function Yt(e){let a=await Promise.all(e.map(o=>yP(o)));return Cm=a,a}async function yP(e){let a=wm(e.versionCommand);a==="permission-denied"&&(kP(e.versionCommand[0]),a=wm(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await Oa(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await Am(e);await ya({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function wm(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function kP(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=we__default.realpathSync(o),{mode:r}=we__default.statSync(t);we__default.chmodSync(t,r|73);}catch{}}function wP(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function Mm(e,a){let[o,t]=useState(()=>wP(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(m=>m.map(p=>p.module.alias!==u||p.module.required?p:{...p,checked:!p.checked}));},[]),l=useCallback((u,m)=>{t(p=>p.map(h=>h.module.alias===u?{...h,selectedStrategy:m}:h));},[]);useInput((u,m)=>{let p=s.current,h=n.current,f=m.upArrow||u==="[A",g=m.downArrow||u==="[B";if(f||g)f&&p>0?i(p-1):g&&p<h.length-1&&i(p+1);else if(u===" "){let v=h[p];v&&!v.module.required&&d(v.module.alias);}else if(m.tab){let v=h[p];if(v&&v.availableStrategies.length>1){let k=v.availableStrategies.indexOf(v.selectedStrategy??v.availableStrategies[0]),T=v.availableStrategies[(k+1)%v.availableStrategies.length];t(L=>L.map(A=>A.module.alias===v.module.alias?{...A,selectedStrategy:T}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}j();function Lm({probeResults:e,onConfirm:a}){let o=y(p=>p.focus),t=y(p=>p.actionMenuOpen),r=y(p=>p.setActionMenuOpen),i=y(p=>p.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=Mm(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&a(d),l();},[d,a,l]);useInput((p,h)=>{h.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],m=d.length>0?`Install ${d.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:s.map((p,h)=>{let f=h===n,g=b(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:f?"cyan":void 0,children:[f?"\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:b(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"})}),t&&jsx(ra,{itemName:m,actions:u,onAction:c,onClose:l})]})}var xP=/^https?:\/\/.+/;function Fm({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&xP.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function IP(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function Gm(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,m)=>{t(p=>p.map(h=>h.alias===u?{...h,...m}:h));},[]),n=useCallback(async()=>{for(let u of e){let m=IP(u);if(!u.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}s(u.module.alias,{status:"installing"});try{let p=await Co(u.module,"onboarding",u.selectedStrategy,a);p.success?s(u.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){s(u.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();j();function Bm({module:e}){let a=b(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:b(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",b(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function Wm({confirmedItems:e,customUrl:a}){let o=y(v=>v.setScreen),t=y(v=>v.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=Gm(e,a),c=r.some(v=>v.pendingSetupCommand),u=useRef(false),m=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let p=useCallback(()=>{et().catch(()=>{}),t("list");let v=ne().some(k=>k.name===ue);o(v?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!m.current){m.current=true;let v=setTimeout(p,1500);return ()=>clearTimeout(v)}},[s,d,c,p]),useInput((v,k)=>{k.return&&p();},{isActive:s});let h=r.filter(v=>v.pendingSetupCommand).length,f=n-h,g=[];return f>0&&g.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),h>0&&g.push(jsxs(Text,{color:"red",children:[h," needs setup"]},"p")),d>0&&g.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&g.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(v=>jsx(Bm,{module:v},v.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((v,k,T)=>(T>0&&v.push(jsx(Text,{children:" | "},`sep-${T}`)),v.push(k),v),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Hm(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(p=>p.setFocus),l=y(p=>p.setScreen),c=useCallback(p=>{if(xl(p)){et().catch(()=>{}),d("list");let f=ne().some(g=>g.name===ue);l(f?"main":"claudeMdSuggestion");}else t(p),a("selection");},[d,l]);useEffect(()=>{let p=Rm();if(p){c(p);return}Yt(se).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(p=>{i(p);let h=p.some(f=>f.module.alias==="metrics");a(h?"customUrl":"installation");},[]),m=useCallback(p=>{n(p),a("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Lm,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(Fm,{onConfirm:m}),e==="installation"&&jsx(Wm,{confirmedItems:r,customUrl:s})]})}U();I();var jP=P("ClaudeMdSuggestion"),UP=[`Install ${ue}`,"Skip for now"],zP=["Retry","Skip for now"];function _m(){let e=y(m=>m.setScreen),a=y(m=>m.setFocus),o=q(m=>m.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{S(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,S(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await Ge(ue),r("installed");}catch(m){if(m instanceof Xe){r("installed");return}jP.warn(`Failed to install ${ue}: ${m instanceof Error?m.message:m}`),r("error");}},[]),u=t==="error"?zP:UP;return useInput((m,p)=>{if(p.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){p.upArrow&&i>0?s(i-1):p.downArrow&&i<u.length-1?s(i+1):p.return&&(i===0?(s(0),c()):l());return}t==="installed"&&p.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Vm,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ue,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ue," 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:["/",ue]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ue]}),jsx(Vm,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Vm({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var QP=promisify(execFile),Os="@ciandt-flow/cli";async function Xm(){let e=te;if(qd.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Os};try{let a=await fetch(`https://registry.npmjs.org/${Os}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Os}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Os}}}async function Ns(e){try{return await QP(Ka(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function VP(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await Oa(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await ya({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function Km(e){let a=await VP(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function $m(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await Oa(o.installMethod).update(e,a.currentVersion??"");return r.success?(await ya({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function Ym(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function Zm(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...se.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([Xm(),Yt(se),Promise.all(se.map(d=>Km(d)))]);if(Ts(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Ns(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=se.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await $m(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:Ym(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await et(),a(d=>({...d,outcome:"done"}));}catch{await et(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function ZP({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{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 eD({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 eg(){let{outcome:e,items:a}=Zm(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=ne().some(s=>s.name===ue);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:a.map(r=>jsx(ZP,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(eD,{outcome:e})})]})}Se();St();I();mn();var rD={debug:"gray",info:"cyan",warn:"yellow",error:"red"},ag=10;function og(){let[e,a]=useState(pn());useEffect(()=>Hc(()=>{a([...pn()]);}),[]);let o=e.slice(-ag);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",ag,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:rD[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var dD=P("app"),cD={auth:Bl,starterKitSetup:Dm,moduleSetup:Hm,claudeMdSuggestion:_m,verify:eg,main:lm};function ig(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Ui(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function sg(){S(w.CLI_SESSION_STARTED,{cli_version:te,os:process.platform,node_version:process.version,duration_ms:yo(),interface:"tui"}).catch(()=>{});}async function dg(){let e=await Y();if(e&&Rl()&&await vo()){e.customUrl&&Ia(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),sg(),Ui(e);return}if(!e){ig();return}try{e.customUrl&&Ia(e.customUrl),await Ma();}catch(t){dD.debug(`Token validation failed: ${String(t)}`),ig();return}sg();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Ui(e);}function cg(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=cD[o],{pendingExit:r}=bl(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(og,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Se();Ci();j();U();I();lr();Se();async function ic(e,a={}){let o=Ii({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return Ti(o),await bo(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Aa=P("auth");function ug(){Ve.clearFallbackFile(),Pi();}var lD=3,lg=3,pg=` \u2139 The data collected during setup is used solely to improve
|
|
121
|
+
[y/N] `))return Ds.debug(`[${e}] Removal cancelled by user`),D("Operation cancelled."),0}let t=a.silent?void 0:nc({text:`Removing MCP "${b(e)}"...`}).start();try{let r=await Te(o);return t?.stop(),r.exitCode!==0?(Wr(a,{name:e,action:"remove",message:r.stderr||"Command failed",exitCode:r.exitCode}),!a.silent&&a.verbose&&r.stdout&&D(`stdout: ${r.stdout}`),1):(Xp(a,{name:e,actionPastTense:"removed",command:o,durationMs:r.duration_ms,stdout:r.stdout}),0)}catch(r){return t?.stop(),Wr(a,{name:e,action:"remove",message:$(r)}),1}}I();function Yp({selectedItem:e,selectedCatalogItem:a,items:o,closeMenu:t,clampIndex:r,notify:i}){let s=P("pluginHandlers"),n=useRef(0),d=y(A=>A.setLoading),l=y(A=>A.setDownloadProgress),{install:c,uninstall:u,toggle:m,update:p}=Vp(),h=async(A,M,F)=>{d(true,A),t();try{await M(),r(o.length),i(F,"success");}catch(O){let ae=O instanceof Error?O.message:"Something went wrong";s.error(`[withLoading] ${A} failed: ${ae}`),i(ae,"error");}finally{d(false);}};return {handleInstall:(A,M)=>{e&&a&&(n.current=0,h(`Installing ${e.name}...`,()=>c(a,{scope:A,...M!==void 0?{providerId:M}:{},onDownloadProgress:(F,O)=>{let ae=Date.now();(ae-n.current>100||F>=O)&&(n.current=ae,l(F,O));}}),"\u2713 Installed successfully"));},handleUninstall:A=>{e&&h(`Uninstalling ${e.name}...`,()=>u(e.name,A),"\u2713 Uninstalled");},handleToggleStatus:A=>{if(!e)return;let M=e.status==="enabled";h(M?`Disabling ${e.name}...`:`Enabling ${e.name}...`,()=>m(e.name,A),M?"\u2713 Disabled":"\u2713 Enabled");},handleUpdate:()=>{if(!e)return;let A=a?` to v${a.version}`:"";(async()=>{d(true,`Updating ${e.name}${A}...`),t();try{await p(e.name),r(o.length),i(`\u2713 Updated ${e.name}${A}`,"success");}catch(F){if(F instanceof Ao)i(F.message,"info");else {let O=F instanceof Error?F.message:"Something went wrong";s.error(`[handleUpdate] ${e.name} failed: ${O}`),i(O,"error");}}finally{d(false);}})();},handleBatchUpdate:A=>{if(A.length===0)return;let M=A.length;(async()=>{d(true,`Updating ${M} plugin${M>1?"s":""}...`),t();try{let O=[];for(let J of A)O.push(await p(J.name).then(()=>({status:"fulfilled",value:void 0}),ee=>({status:"rejected",reason:ee})));let ae=O.filter(J=>J.status==="fulfilled").length,x=O.map((J,ee)=>J.status==="rejected"?A[ee].name:null).filter(J=>J!==null);r(o.length),x.length===0?i(`\u2713 Updated ${ae}/${M} plugin${M>1?"s":""}`,"success"):(s.error(`[handleBatchUpdate] failed: ${x.join(", ")}`),i(`Updated ${ae}/${M}; failed: ${x.join(", ")}`,ae>0?"info":"error"));}finally{d(false);}})();},handleMcpConfigUninstall:A=>{e&&h(`Removing MCP ${e.name}...`,async()=>{let M=Ld(e.name,A),F=await Te(M);if(F.exitCode!==0)throw new Error(F.stderr||"MCP removal failed");fe.getState().loadFromDisk();},"\u2713 MCP removed");}}}Cr();I();var Jr=P("api:bundle"),Kt=class extends Error{constructor(a){super(`Bundle '${a}' not found in your tenant. Verify the name with whoever shared the command.`),this.name="BundleNotFoundError";}},Hr=class extends Error{constructor(){super("The server encountered an error while fetching the bundle. Please try again later."),this.name="BundleServerError";}},Kk=/^[a-zA-Z0-9_-]{1,128}$/;async function em(e,a){if(e instanceof HTTPError){let o=e.response.status;throw Jr.error(`HTTP error fetching bundle '${a}' [status=${o}]`),o===StatusCodes.NOT_FOUND?new Kt(a):o===StatusCodes.INTERNAL_SERVER_ERROR?new Hr:new Error(`Server error (${o}) \u2014 please try again later.`)}throw Jr.error(`Unexpected error fetching bundle '${a}': ${e instanceof Error?e.message:String(e)}`),e}async function am(e){if(!Kk.test(e))throw new Error("Invalid bundle identifier format.");let a=encodeURIComponent(e);Jr.debug(`Fetching bundle by flowId "${e}"`);try{return await Ya().get(`v1/use-cases/${a}`).json()}catch(o){return em(o,e)}}async function ws(e){let a=encodeURIComponent(e);Jr.debug(`Fetching bundle by name "${e}"`);let o;try{o=await Ya().get(`v1/use-cases/by-name/${a}`).json(),Jr.debug(`API returned ${o.length} result(s) for "${e}"`);}catch(t){return em(t,e)}if(o.length===0)throw new Kt(e);return o[0]}I();var $k=P("tui:bundle-flow");function om({closeMenu:e,notify:a}){let o=y(n=>n.bundleInstallFlow);return {handleBundleInstallStart:(n,d)=>{let{setLoading:l,setBundleInstallFlow:c}=y.getState(),u=d?.trim();$k.debug(`Starting bundle install: itemName="${n}" flowId="${u??"none"}"`),l(true,"Loading bundle..."),(u?am(u):ws(n)).then(p=>{l(false),y.getState().actionMenuOpen&&c({phase:"detail",bundle:p});}).catch(p=>{l(false),a(p instanceof Error?p.message:"Failed to load bundle","error");});},handleBundleDetailConfirm:()=>{if(!o||o.phase!=="detail")return;let{setBundleInstallFlow:n,setFocus:d}=y.getState();n({phase:"installing",bundle:o.bundle}),d("bundleInstallProgress");},handleBundleDetailBack:()=>{let{setBundleInstallFlow:n}=y.getState();n(null),e();},handleBundleInstallComplete:n=>{y.getState().setBundleInstallFlow(null),e(),fe.getState().loadFromDisk(),a(`\u2713 Installed ${n.installed} of ${n.total} artifacts`,"success");}}}j();U();var Qr=["local","project","user"],Yk=new Set(["--transport","--scope","-s"]);function tm(e){let a=e.split(/\s+/).filter(Boolean),o=a.indexOf("add");if(o===-1)return null;let t=o+1;for(;t<a.length;){let r=a[t];if(Yk.has(r))t+=2;else if(r.startsWith("-"))t+=1;else return r.replace(/^["']|["']$/g,"")}return null}function dt(e,a){return a?`${e}::${a}`:e}function Fd(e){return e===le?ir:ut}function rm(e){return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,updateAvailable:e.updateAvailable,type:e.type??"bundle",origin:e.origin??ir,flowId:e.flowId}}function Od(e,a){let o=Fd(e.marketplace);return {name:b(e.name),version:e.version?b(e.version):e.version,description:e.description?b(e.description):e.description,authorName:e.author?.name?b(e.author.name):e.author?.name,status:e.status,scope:e.scope,marketplace:e.marketplace,updateAvailable:e.updateAvailable,installedAt:e.installedAt,type:a?.type??e.type??"bundle",origin:a?.origin??o}}function im(e){let a=new Map;for(let o of e){if(!o.scope)continue;let t=a.get(o.scope)??[];t.push(o),a.set(o.scope,t);}return Qr.filter(o=>a.has(o)).map(o=>({scope:o,label:Va[o].label,pathHint:Va[o].pathHint,items:a.get(o)??[]}))}function sm(e){let a=o=>{if(!o)return 1/0;let t=Qr.indexOf(o);return t===-1?1/0:t};return [...e].sort((o,t)=>a(o.scope)-a(t.scope))}function nm({catalog:e,installedItems:a,activeTab:o,catalogFilters:t,searchQuery:r}){let i=useMemo(()=>new Set(a.map(h=>dt(h.name,h.author?.name))),[a]),s=useMemo(()=>new Set(a.filter(h=>h.type==="mcp").map(h=>h.name.toLowerCase())),[a]),n=useMemo(()=>{let h=new Map(e.map(g=>[dt(g.name,g.author?.name),g])),f=new Map(e.map(g=>[g.name,g]));return a.map(g=>{let v=h.get(dt(g.name,g.author?.name))??f.get(g.name),k=v?.version,T=!!k&&!!g.version&&Ue(g.version,k);return {...g,updateAvailable:T,catalogItem:v}})},[a,e]),d=useMemo(()=>o==="discover"?e.filter(h=>{if(i.has(dt(h.name,h.author?.name)))return false;if(h.type==="mcp"){let f=h.installCommand?tm(h.installCommand)?.toLowerCase():null;if(s.has(h.name.toLowerCase())||f&&s.has(f))return false}return true}).map(h=>rm(h)):o==="updates"?n.filter(h=>h.updateAvailable).map(h=>Od(h,h.catalogItem)):n.map(h=>Od(h,h.catalogItem)),[o,e,i,s,n]),l=useMemo(()=>d.filter(h=>{let f=h.type??"bundle";if(!t.types.has(f))return false;let g=h.origin??"internal";return t.origins.has(g)}),[d,t]),c=useMemo(()=>{let{types:h}=t;if(h.size===1){if(h.has("skill"))return "skills";if(h.has("mcp"))return "MCPs";if(h.has("bundle"))return "bundles"}return "items"},[t]),u=useMemo(()=>o==="installed"?r?`No ${c} found for '${r}' \u2014 explore the Discover tab!`:`No ${c} installed \u2014 explore the Discover tab!`:o==="updates"?r?`No ${c} found for '${r}' \u2014 all up to date!`:"All up to date \u2014 nothing to update":r?`No ${c} found for '${r}'`:`No ${c} available in the catalog`,[o,r,c]),m=useMemo(()=>{let h=new Map(e.map(g=>[dt(g.name,g.author?.name),g])),f=new Map(e.map(g=>[g.name,g]));return g=>g?h.get(dt(g.name,g.authorName))??f.get(g.name)??null:null},[e]),p=useMemo(()=>n.filter(h=>h.updateAvailable).length,[n]);return {items:l,emptyMessage:u,getSelectedCatalogItem:m,outdatedCount:p}}function Nd(){let[e,a]=useState([]),[o,t]=useState(true),[r,i]=useState(null),[s,n]=useState(null),d=useRef(false),l=y(u=>u.catalogVersion),c=useCallback(async()=>{t(true),i(null),n(null);try{let{items:u,failures:m}=await qu();if(a(u),m.length>0){let p=m.map(h=>h.adapterName).join(", ");n(`Some catalogs failed to load: ${p}`);}d.current||(d.current=!0,S(w.CLI_CATALOG_VIEWED,{interface:"tui",filter_type:"all",result_count:u.length}).catch(()=>{}));}catch(u){i(u instanceof Error?u:new Error(String(u))),a([]);}finally{t(false);}},[]);return useEffect(()=>{c();},[c,l]),{catalog:e,isLoading:o,error:r,partialError:s,refetch:c}}function dm(){return {items:fe(a=>a.installedItems)}}I();var tP=P("catalog");function lm(){let e=y(X=>X.bundleInstallFlow),a=y(X=>X.activeTab),o=y(X=>X.notification),t=y(X=>X.loading),r=y(X=>X.loadingMessage),i=y(X=>X.downloadProgress),s=y(X=>X.downloadTotal),n=y(X=>X.catalogError),d=y(X=>X.setCatalogError),l=y(X=>X.catalogFilters),c=_e(X=>X.query),{catalog:u,isLoading:m,error:p,refetch:h}=Nd(),{items:f}=dm(),g=fe(X=>X.loadFromDisk),{items:v,emptyMessage:k,getSelectedCatalogItem:T,outdatedCount:L}=nm({catalog:u,installedItems:f,activeTab:a,catalogFilters:l,searchQuery:c}),{actionMenuOpen:A,closeMenu:M,selectedIndex:F,clampIndex:O,filteredItems:ae}=zp({listLength:v.length}),x=ae(v),J=useMemo(()=>a!=="installed"&&a!=="updates"?x:sm(x),[a,x]),ee=useMemo(()=>a==="installed"||a==="updates"?im(J):[],[a,J]),z=J[F]??null,W=useMemo(()=>T(z),[T,z]),{notify:_}=Jp(),{handleInstall:E,handleUninstall:B,handleToggleStatus:Q,handleUpdate:qe,handleBatchUpdate:ei,handleMcpConfigUninstall:ah}=Yp({selectedItem:z,selectedCatalogItem:W,items:v,closeMenu:M,clampIndex:O,notify:_}),{handleBundleInstallStart:oh,handleBundleDetailConfirm:th,handleBundleDetailBack:rh,handleBundleInstallComplete:ih}=om({closeMenu:M,notify:_}),sh=useCallback(()=>ei(J),[ei,J]);return useEffect(()=>{g();},[]),useEffect(()=>{O(J.length);},[J.length,O]),useEffect(()=>{p&&(tP.error(`[catalog] ${p instanceof Error?p.message:String(p)}`),d("Failed to load catalog"));},[p]),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsx(Vl,{outdatedCount:L}),a==="marketplaces"&&Do()?jsx(Box,{flexDirection:"column",flexGrow:1,children:jsx(Gp,{})}):jsx(cu,{filteredItems:J,groups:ee,emptyMessage:k,onBatchUpdate:sh}),(t||m)&&jsxs(Fragment,{children:[jsx(Hi,{message:t?r:"Loading catalog..."}),t&&s>0&&i>0&&jsx(Box,{paddingLeft:2,children:jsx(Vi,{received:i,total:s})})]}),n&&!m&&a==="discover"&&jsx(_i,{message:n,onRetry:()=>{d(null),h();},onBack:()=>d(null)}),o&&jsx(lu,{message:o.message,type:o.type}),A&&z&&(a==="discover"?W?.type==="bundle"?e?.phase==="installing"?jsx(Sp,{bundle:e.bundle,onComplete:ih}):jsx(pp,{itemName:z.name,bundle:e?.phase==="detail"?e.bundle:void 0,onInstall:()=>oh(z.name,z.flowId),onConfirm:th,onClose:e?.phase==="detail"?rh:M}):jsx(lp,{itemName:z.name,itemType:W?.type,onInstall:E,onClose:M}):z.type==="mcp"?jsx(vp,{itemName:z.name,itemScope:z.scope??"user",onUninstall:ah,onClose:M}):jsx(fp,{itemName:z.name,itemScope:z.scope??"user",itemStatus:z.status??"enabled",updateAvailable:z.updateAvailable??false,catalogVersion:W?.version,onUninstall:B,onToggleStatus:X=>Q(X),onUpdate:qe,onClose:M})),jsx(Ji,{})]})}var q=create((e,a)=>({starterKits:[],selectedStarterKitIndex:0,selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList",isLoadingStarterKits:false,starterKitsError:null,successCount:0,failedCount:0,summaryActionIndex:0,setStarterKits:o=>e({starterKits:o}),setSelectedStarterKitIndex:o=>e({selectedStarterKitIndex:o}),selectStarterKit:o=>{let t=new Set(fe.getState().installedItems.map(r=>r.name));e({selectedStarterKit:o,plugins:o.plugins.map(r=>({name:r,selected:true,status:t.has(r)?"success":"pending",installed:t.has(r)})),pluginCursorIndex:0,step:"starterKitDetail"});},setPluginCursorIndex:o=>e({pluginCursorIndex:o}),setStep:o=>e({step:o}),setPluginStatus:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,status:t,error:r}:s);e({plugins:i});},setPluginDownloadProgress:(o,t,r)=>{let i=a().plugins.map(s=>s.name===o?{...s,downloadProgress:t,downloadTotal:r}:s);e({plugins:i});},setIsLoadingStarterKits:o=>e({isLoadingStarterKits:o}),setStarterKitsError:o=>e({starterKitsError:o}),setSummaryActionIndex:o=>e({summaryActionIndex:o}),computeSummary:()=>{let t=a().plugins.filter(r=>r.selected);e({successCount:t.filter(r=>r.status==="success").length,failedCount:t.filter(r=>r.status==="failed").length});},resetForRetry:()=>{let o=a().plugins.map(t=>t.status==="failed"?{...t,status:"pending",error:void 0}:t);e({plugins:o,step:"installing"});},goBackToList:()=>e({selectedStarterKit:null,plugins:[],pluginCursorIndex:0,step:"starterKitList"})}));Se();var dP=3;function pm(){let e=q(c=>c.setStarterKits),a=q(c=>c.setIsLoadingStarterKits),o=q(c=>c.setStarterKitsError),t=q(c=>c.setPluginStatus),r=q(c=>c.setPluginDownloadProgress),i=q(c=>c.setStep),s=q(c=>c.computeSummary),n=useCallback(async()=>{a(true),o(null);try{let c=await as();e(c);}catch(c){o(c instanceof Error?c.message:String(c));}finally{a(false);}},[a,o,e]);useEffect(()=>{fe.getState().loadFromDisk(),n();},[n]);let d=useRef(0),l=useCallback(async()=>{let c=q.getState().plugins.filter(m=>m.selected&&m.status==="pending");for(let m of c){t(m.name,"installing"),d.current=0;let p="",h=false;for(let f=1;f<=dP;f++)try{await Ge(m.name,{onDownloadProgress:(g,v)=>{let k=Date.now();(k-d.current>100||g>=v)&&(d.current=k,r(m.name,g,v));}}),t(m.name,"success"),h=!0;break}catch(g){if(g instanceof Xe){t(m.name,"success"),h=true;break}p=g instanceof Error?g.message:"Unknown error";}h||(t(m.name,"failed",p),S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:m.name,tool_type:"skill",source:"internal",error_code:"install_failed",error_message:p,interface:Z().interfaceType}).catch(()=>{}));}let u=_o();Vo("summary_review"),S(w.CLI_STEP_COMPLETED,{step:"tool_installation",duration_ms:u}).catch(()=>{}),fe.getState().loadFromDisk(),s(),i("summary");},[t,r,s,i]);return {loadStarterKits:n,installSelected:l}}var Vr={cursorDelta:0,confirm:false,back:false};function mm(e,a){return a.upArrow?{...Vr,cursorDelta:-1}:a.downArrow?{...Vr,cursorDelta:1}:a.escape?{...Vr,back:true}:a.return?{...Vr,confirm:true}:Vr}var cP={cursorDelta:0,select:false};function gm(e,a){return a.upArrow?{cursorDelta:-1,select:false}:a.downArrow?{cursorDelta:1,select:false}:a.return?{cursorDelta:0,select:true}:cP}j();var fm=iv.memo(function({starterKit:a,isSelected:o}){return jsxs(Box,{flexDirection:"column",paddingBottom:1,children:[jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":"\u25CB "}),jsx(Text,{bold:o,color:o?"cyan":"white",children:b(a.name)}),jsxs(Text,{dimColor:true,children:[" \xB7 ",a.plugins.length," ",a.plugins.length===1?"plugin":"plugins"]})]}),jsx(Box,{paddingLeft:2,children:jsx(Text,{dimColor:true,children:b(a.description)})})]})});var Jd=5;function hm({onRetry:e}){let a=q(c=>c.starterKits),o=q(c=>c.selectedStarterKitIndex),t=q(c=>c.isLoadingStarterKits),r=q(c=>c.starterKitsError);if(t)return jsx(Hi,{message:"Loading Starter Kits..."});if(r)return jsx(_i,{message:r,onRetry:e,onBack:e});if(a.length===0)return jsx(It,{message:"No Starter Kits available."});let i=Math.max(0,o-Math.floor(Jd/2)),s=Math.min(a.length,i+Jd);s===a.length&&(i=Math.max(0,s-Jd));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Select a Starter Kit to get started"})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(fm,{starterKit:c,isSelected:i+u===o},c.slug)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var vm=iv.memo(function({plugin:a,isCursor:o}){return jsxs(Box,{children:[jsx(Text,{color:o?"cyan":"gray",children:o?"\u203A ":" "}),jsx(Text,{color:"cyan",children:"\u2022"}),jsxs(Text,{bold:o,color:o?"cyan":"white",children:[" ",b(a.name)]}),a.installed&&jsx(Text,{color:"green",children:" (installed)"})]})});j();var Vd=8;function ym(){let e=q(c=>c.selectedStarterKit),a=q(c=>c.plugins),o=q(c=>c.pluginCursorIndex),t=useRef(false);if(useEffect(()=>{e&&!t.current&&(t.current=true,S(w.CLI_KIT_DISPLAYED,{bundle_slug:e.slug,tool_count:a.length}).catch(()=>{}));},[e,a.length]),!e)return jsx(Text,{dimColor:true,children:"No Starter Kit selected."});let r=a.filter(c=>c.installed).length,i=Math.max(0,o-Math.floor(Vd/2)),s=Math.min(a.length,i+Vd);s===a.length&&(i=Math.max(0,s-Vd));let n=a.slice(i,s),d=i,l=a.length-s;return jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[jsx(Text,{bold:true,color:"cyan",children:b(e.name)}),jsx(Text,{dimColor:true,children:b(e.description)})]}),jsx(Box,{paddingX:1,paddingBottom:1,children:jsxs(Text,{children:[a.length," plugins to install",r>0&&` \xB7 ${r} already installed`]})}),d>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2191 ",d," more above"]})}),n.map((c,u)=>jsx(vm,{plugin:c,isCursor:i+u===o},c.name)),l>0&&jsx(Box,{paddingX:2,children:jsxs(Text,{dimColor:true,children:["\u2193 ",l," more below"]})})]})}j();var vP=["Retry failed","Continue anyway"];function km({name:e,status:a,error:o,downloadProgress:t,downloadTotal:r}){let i=b(e);return a==="installing"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",i]})]}),r!==void 0&&r>0&&t!==void 0&&t>0&&jsx(Box,{paddingLeft:2,children:jsx(Vi,{received:t,total:r})})]}):a==="success"?jsx(Box,{children:jsxs(Text,{color:"green",children:["\u2713 ",i]})}):a==="failed"?jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",i]}),o&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(o)]})]}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",i]})})}function Pm({onComplete:e,onRetry:a}){let o=q(l=>l.plugins),t=q(l=>l.step),r=q(l=>l.successCount),i=q(l=>l.failedCount),s=q(l=>l.summaryActionIndex),n=o.filter(l=>l.selected),d=useRef(false);return useEffect(()=>{if(t==="summary"&&i===0&&!d.current){d.current=true;let l=setTimeout(e,1500);return ()=>clearTimeout(l)}},[t,i,e]),t==="installing"?jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installing plugins..."})}),jsx(Box,{flexDirection:"column",paddingX:1,children:n.map(l=>jsx(km,{name:l.name,status:l.status,error:l.error,downloadProgress:l.downloadProgress,downloadTotal:l.downloadTotal},l.name))})]}):jsxs(Box,{flexDirection:"column",children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Installation Complete"})}),jsxs(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:[r>0&&jsxs(Text,{color:"green",children:["\u2713 ",r," ",r===1?"plugin":"plugins"," installed successfully"]}),i>0&&jsxs(Text,{color:"red",children:["\u2717 ",i," ",i===1?"plugin":"plugins"," failed"]})]}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:n.filter(l=>l.status==="failed").map(l=>jsx(km,{name:l.name,status:l.status,error:l.error},l.name))}),i>0&&jsx(Box,{flexDirection:"column",paddingX:1,children:vP.map((l,c)=>jsx(Box,{children:jsxs(Text,{bold:c===s,color:c===s?"cyan":void 0,children:[c===s?"\u203A ":" ",l]})},l))}),i===0&&jsx(Box,{paddingX:1,children:jsx(Text,{dimColor:true,children:"Proceeding to main screen..."})})]})}function Dm(){let e=q(x=>x.step),a=q(x=>x.starterKits),o=q(x=>x.selectedStarterKitIndex),t=q(x=>x.setSelectedStarterKitIndex),r=q(x=>x.selectStarterKit),i=q(x=>x.plugins),s=q(x=>x.pluginCursorIndex),n=q(x=>x.setPluginCursorIndex),d=q(x=>x.setStep),l=q(x=>x.summaryActionIndex),c=q(x=>x.setSummaryActionIndex),u=q(x=>x.failedCount),m=q(x=>x.resetForRetry),p=q(x=>x.goBackToList),h=y(x=>x.setScreen),f=y(x=>x.setFocus),g=y(x=>x.focus),v=oa(x=>x.setJustAuthenticated),k=oa(x=>x.justAuthenticated),{loadStarterKits:T,installSelected:L}=pm(),A=useRef(false);useEffect(()=>{e==="starterKitList"?(f("starterKitList"),A.current||(A.current=true,Vo("bundle_selection"))):f(e==="starterKitDetail"?"starterKitDetail":"installProgress");},[e,f]);let M=useCallback(async()=>{let x=q.getState().selectedStarterKit;if(x){let ee=await Y();ee&&await bo({...ee,starterKit:x.slug});}S(w.CLI_STEP_COMPLETED,{step:"summary_review",duration_ms:_o()}).catch(()=>{});let{successCount:J}=q.getState();S(w.CLI_ONBOARDING_COMPLETED,{duration_ms:yo(),tools_installed_count:J}).catch(()=>{}),v(false),f("verify"),h("verify");},[v,f,h]),F=useCallback(()=>{m(),L();},[m,L]),O=useCallback(()=>{T();},[T]),ae=useCallback(()=>{f("verify"),h("verify");},[f,h]);return useInput((x,J)=>{if(J.escape)Ai("esc"),ae();else if(J.upArrow&&o>0)t(o-1);else if(J.downArrow&&o<a.length-1)t(o+1);else if(J.return&&a.length>0){let ee=_o();r(a[o]),Vo("kit_display"),S(w.CLI_STEP_COMPLETED,{step:"bundle_selection",duration_ms:ee}).catch(()=>{});}},{isActive:g==="starterKitList"}),useInput((x,J)=>{let ee=mm(x,J);if(ee.cursorDelta!==0){let z=s+ee.cursorDelta;z>=0&&z<i.length&&n(z);}if(ee.confirm){let z=q.getState().selectedStarterKit;z&&(async()=>(await Y())?.starterKit!==z.slug&&S(w.CLI_KIT_ACCEPTED,{bundle_slug:z.slug}).catch(()=>{}))();let W=_o();Vo("kit_confirmation"),S(w.CLI_STEP_COMPLETED,{step:"kit_display",duration_ms:W}).catch(()=>{});let _=_o();Vo("tool_installation"),S(w.CLI_STEP_COMPLETED,{step:"kit_confirmation",duration_ms:_}).catch(()=>{}),d("installing"),L();}if(ee.back){let z=q.getState().selectedStarterKit;z&&S(w.CLI_KIT_REJECTED,{bundle_slug:z.slug}).catch(()=>{}),p();}},{isActive:g==="starterKitDetail"}),useInput((x,J)=>{if(u===0)return;let ee=gm(x,J);if(ee.cursorDelta!==0){let z=l+ee.cursorDelta;z>=0&&z<=1&&c(z);}ee.select&&(l===0?F():M());},{isActive:g==="installProgress"&&e==="summary"}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsxs(Box,{flexDirection:"column",paddingX:1,marginBottom:1,children:[jsx(Text,{dimColor:true,children:"The data collected during setup is used solely to improve"}),jsx(Text,{dimColor:true,children:"Flow's internal tools and will not be shared externally."}),!k&&jsx(Box,{marginTop:1,children:jsx(Text,{color:"yellow",children:"Welcome back! We noticed your Starter Kit is not set up yet. Choose a Starter Kit below to get your recommended tools."})})]}),jsxs(Box,{flexDirection:"column",flexGrow:1,children:[e==="starterKitList"&&jsx(hm,{onRetry:O}),e==="starterKitDetail"&&jsx(ym,{}),(e==="installing"||e==="summary")&&jsx(Pm,{onComplete:M,onRetry:F})]}),jsx(Ji,{})]})}U();var Cm=null;function Rm(){return Cm}async function Ts(){let a=Zo().filter(o=>o.installedVersion===null&&o.installMethod===null);for(let o of a){let t=se.find(s=>s.alias===o.alias);if(!t)continue;let{installedVersion:r,installMethod:i}=await Am(t);(r||i)&&await ya({...o,installedVersion:r,installMethod:i});}}async function Am(e){let a=e.platforms[process.platform];if(a?.status!=="supported")return {installedVersion:null,installMethod:null};for(let o of a.strategies)if(o.type!=="curl")try{let r=await Oa(o.type).getInstalledVersion(e);if(r)return {installedVersion:r,installMethod:o.type}}catch{}return {installedVersion:null,installMethod:null}}async function Yt(e){let a=await Promise.all(e.map(o=>PP(o)));return Cm=a,a}async function PP(e){let a=wm(e.versionCommand);a==="permission-denied"&&(DP(e.versionCommand[0]),a=wm(e.versionCommand));let t=a==="installed"&&(!e.configCheck||e.configCheck()),r=e.platforms[process.platform],i=r?.status==="supported"?r.strategies:[],n=(await Promise.all(i.map(async d=>{try{return await Oa(d.type).isAvailable()?d.type:null}catch{return null}}))).filter(d=>d!==null);if(t&&!ta(e.alias)){let{installedVersion:d,installMethod:l}=await Am(e);await ya({alias:e.alias,name:e.name,installedVersion:d,installMethod:l,installedAt:null,lastChecked:new Date().toISOString()});}return {module:e,alreadyInstalled:t,availableStrategies:n}}function wm(e){if(e.length===0)return "not-found";try{let a=spawnSync(e[0],e.slice(1),{timeout:3e3,stdio:"pipe",shell:process.platform==="win32"});return a.status===0?"installed":a.status===126?"permission-denied":"not-found"}catch{return "not-found"}}function DP(e){if(process.platform!=="win32")try{let a=spawnSync("which",[e],{stdio:"pipe"});if(a.status!==0)return;let o=a.stdout.toString().trim(),t=we__default.realpathSync(o),{mode:r}=we__default.statSync(t);we__default.chmodSync(t,r|73);}catch{}}function CP(e){return e.filter(a=>a.module.platforms[process.platform]?.status==="supported").filter(a=>!a.alreadyInstalled).map(a=>({module:a.module,alreadyInstalled:a.alreadyInstalled,checked:!a.alreadyInstalled&&(a.availableStrategies.length>0||a.module.required===true),selectedStrategy:a.availableStrategies[0]??null,availableStrategies:a.availableStrategies}))}function Mm(e,a){let[o,t]=useState(()=>CP(e)),[r,i]=useState(0),s=useRef(r);useEffect(()=>{s.current=r;},[r]);let n=useRef(o);useEffect(()=>{n.current=o;},[o]);let d=useCallback(u=>{t(m=>m.map(p=>p.module.alias!==u||p.module.required?p:{...p,checked:!p.checked}));},[]),l=useCallback((u,m)=>{t(p=>p.map(h=>h.module.alias===u?{...h,selectedStrategy:m}:h));},[]);useInput((u,m)=>{let p=s.current,h=n.current,f=m.upArrow||u==="[A",g=m.downArrow||u==="[B";if(f||g)f&&p>0?i(p-1):g&&p<h.length-1&&i(p+1);else if(u===" "){let v=h[p];v&&!v.module.required&&d(v.module.alias);}else if(m.tab){let v=h[p];if(v&&v.availableStrategies.length>1){let k=v.availableStrategies.indexOf(v.selectedStrategy??v.availableStrategies[0]),T=v.availableStrategies[(k+1)%v.availableStrategies.length];t(L=>L.map(A=>A.module.alias===v.module.alias?{...A,selectedStrategy:T}:A));}}},{isActive:a});let c=useMemo(()=>o.filter(u=>u.checked),[o]);return {items:o,focusedIndex:r,toggle:d,setStrategy:l,confirmedItems:c}}j();function Lm({probeResults:e,onConfirm:a}){let o=y(p=>p.focus),t=y(p=>p.actionMenuOpen),r=y(p=>p.setActionMenuOpen),i=y(p=>p.setFocus),{items:s,focusedIndex:n,confirmedItems:d}=Mm(e,o==="moduleSetup"),l=useCallback(()=>{r(false),i("moduleSetup");},[r,i]),c=useCallback(p=>{(p==="Install"||p==="Skip")&&a(d),l();},[d,a,l]);useInput((p,h)=>{h.return&&(r(true),i("actionMenu"));},{isActive:o==="moduleSetup"});let u=d.length>0?["Install","Cancel"]:["Skip","Cancel"],m=d.length>0?`Install ${d.length} module(s)?`:"No modules selected";return jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:s.map((p,h)=>{let f=h===n,g=b(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:f?"cyan":void 0,children:[f?"\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:b(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"})}),t&&jsx(ra,{itemName:m,actions:u,onAction:c,onClose:l})]})}var IP=/^https?:\/\/.+/;function Fm({onConfirm:e}){let[a,o]=useState("confirm"),[t,r]=useState(""),[i,s]=useState(false),n=useRef("");return useInput((d,l)=>{if(a==="confirm"){if(d==="y"||d==="Y"){o("input");return}if(d==="n"||d==="N"||l.return){e(null);return}}if(a==="input"){if(l.escape){n.current="",r(""),o("confirm");return}if(l.return){let c=n.current.trim();c.length>0&&IP.test(c)?(s(false),e(c)):c.length>0&&s(true);return}if(l.backspace||l.delete){n.current=n.current.slice(0,-1),r(n.current);return}d&&!l.ctrl&&!l.meta&&(n.current=n.current+d,r(n.current),s(false));}}),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Configure modules"})}),jsxs(Box,{paddingX:1,paddingBottom:1,flexDirection:"column",children:[a==="confirm"&&jsx(Text,{children:"Does your organization use a custom Flow URL? (y/N)"}),a==="input"&&jsxs(Box,{flexDirection:"column",gap:1,children:[jsx(Text,{children:"Enter your custom Flow base URL:"}),jsxs(Box,{children:[jsx(Text,{color:"cyan",children:"> "}),jsx(Text,{children:t}),jsx(Text,{color:"cyan",children:"\u2588"})]}),i&&jsx(Text,{color:"red",children:"URL must start with http:// or https://"}),jsx(Text,{dimColor:true,children:"Enter to confirm \xB7 Esc to go back"})]})]})]})}function MP(e){let a=e.module.platforms[process.platform];return (a?.status==="supported"?a.strategies:[]).map(t=>t.type==="npm"?`npm install -g ${t.package}`:t.type==="homebrew"?`brew install ${t.formula}`:"curl (see docs)").join(" or ")}function Gm(e,a){let[o,t]=useState(()=>e.map(u=>({alias:u.module.alias,name:u.module.name,status:"pending"}))),[r,i]=useState(false),s=useCallback((u,m)=>{t(p=>p.map(h=>h.alias===u?{...h,...m}:h));},[]),n=useCallback(async()=>{for(let u of e){let m=MP(u);if(!u.selectedStrategy){let p=m?`No package manager available. Install manually: ${m}`:"No package manager available for this platform";s(u.module.alias,{status:"failed",error:p,manualInstallHint:m||void 0});continue}s(u.module.alias,{status:"installing"});try{let p=await Co(u.module,"onboarding",u.selectedStrategy,a);p.success?s(u.module.alias,{status:"installed",pendingSetupCommand:p.configCheckFailed?"flow-ai-obs init \u2014 run manually to complete setup (required for metrics collection)":p.pendingInteractiveSetup?.join(" ")}):s(u.module.alias,{status:"failed",error:p.error?.message??"Installation failed",manualInstallHint:m});}catch(p){s(u.module.alias,{status:"failed",error:p instanceof Error?p.message:"Unknown error",manualInstallHint:m});}}i(true);},[e,s,a]),d=useMemo(()=>o.filter(u=>u.status==="installed").length,[o]),l=useMemo(()=>o.filter(u=>u.status==="failed").length,[o]),c=useMemo(()=>o.filter(u=>u.status==="skipped").length,[o]);return {modules:o,install:n,isComplete:r,installedCount:d,failedCount:l,skippedCount:c}}U();j();function Bm({module:e}){let a=b(e.name);if(e.status==="installing")return jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" ",a," \u2014 Installing..."]})]});if(e.status==="installed"){let o=!!e.pendingSetupCommand;return jsxs(Box,{flexDirection:"column",children:[jsx(Box,{children:jsxs(Text,{color:o?"red":"green",children:[o?"\u2717":"\u2713"," ",a]})}),e.pendingSetupCommand&&jsx(Box,{paddingLeft:2,children:jsx(Text,{color:"red",children:b(e.pendingSetupCommand)})})]})}return e.status==="failed"?jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{children:[jsxs(Text,{color:"red",children:["\u2717 ",a]}),e.error&&jsxs(Text,{dimColor:true,children:[" \u2014 ",b(e.error)]})]}),e.manualInstallHint&&jsx(Box,{paddingLeft:2,children:jsxs(Text,{dimColor:true,children:["Install manually: ",b(e.manualInstallHint)]})})]}):e.status==="skipped"?jsx(Box,{children:jsxs(Text,{dimColor:true,children:["- ",a," (not supported on this platform)"]})}):jsx(Box,{children:jsxs(Text,{dimColor:true,children:["\u25CB ",a]})})}function Wm({confirmedItems:e,customUrl:a}){let o=y(v=>v.setScreen),t=y(v=>v.setFocus),{modules:r,install:i,isComplete:s,installedCount:n,failedCount:d,skippedCount:l}=Gm(e,a),c=r.some(v=>v.pendingSetupCommand),u=useRef(false),m=useRef(false);useEffect(()=>{u.current||(u.current=true,i());},[i]);let p=useCallback(()=>{et().catch(()=>{}),t("list");let v=ne().some(k=>k.name===ue);o(v?"main":"claudeMdSuggestion");},[t,o]);useEffect(()=>{if(s&&d===0&&!c&&!m.current){m.current=true;let v=setTimeout(p,1500);return ()=>clearTimeout(v)}},[s,d,c,p]),useInput((v,k)=>{k.return&&p();},{isActive:s});let h=r.filter(v=>v.pendingSetupCommand).length,f=n-h,g=[];return f>0&&g.push(jsxs(Text,{color:"green",children:[f," installed"]},"i")),h>0&&g.push(jsxs(Text,{color:"red",children:[h," needs setup"]},"p")),d>0&&g.push(jsxs(Text,{color:"red",children:[d," failed"]},"f")),l>0&&g.push(jsxs(Text,{dimColor:true,children:[l," skipped"]},"s")),jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:s?"Modules ready":"Setting up modules..."})}),jsx(Box,{flexDirection:"column",paddingX:1,paddingBottom:1,children:r.map(v=>jsx(Bm,{module:v},v.alias))}),s&&jsxs(Fragment,{children:[jsx(Box,{paddingX:1,paddingBottom:1,children:g.reduce((v,k,T)=>(T>0&&v.push(jsx(Text,{children:" | "},`sep-${T}`)),v.push(k),v),[])}),jsx(Box,{paddingX:1,children:d>0||c?jsx(Text,{dimColor:true,children:"Press Enter to continue"}):jsx(Text,{dimColor:true,children:"Proceeding..."})})]})]})}function Hm(){let[e,a]=useState("loading"),[o,t]=useState([]),[r,i]=useState([]),[s,n]=useState(null),d=y(p=>p.setFocus),l=y(p=>p.setScreen),c=useCallback(p=>{if(xl(p)){et().catch(()=>{}),d("list");let f=ne().some(g=>g.name===ue);l(f?"main":"claudeMdSuggestion");}else t(p),a("selection");},[d,l]);useEffect(()=>{let p=Rm();if(p){c(p);return}Yt(se).then(c).catch(()=>{t([]),a("selection");});},[c]);let u=useCallback(p=>{i(p);let h=p.some(f=>f.module.alias==="metrics");a(h?"customUrl":"installation");},[]),m=useCallback(p=>{n(p),a("installation");},[]);return jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[e==="loading"&&jsx(Box,{paddingX:1,paddingBottom:1,children:jsx(Text,{bold:true,children:"Setting up modules..."})}),e==="selection"&&jsx(Lm,{probeResults:o,onConfirm:u}),e==="customUrl"&&jsx(Fm,{onConfirm:m}),e==="installation"&&jsx(Wm,{confirmedItems:r,customUrl:s})]})}U();I();var zP=P("ClaudeMdSuggestion"),WP=[`Install ${ue}`,"Skip for now"],JP=["Retry","Skip for now"];function _m(){let e=y(m=>m.setScreen),a=y(m=>m.setFocus),o=q(m=>m.successCount),[t,r]=useState("prompt"),[i,s]=useState(0),n=useRef(0),d=useCallback(()=>{a("list"),e("main");},[a,e]),l=useCallback(()=>{S(w.CLI_CLAUDE_MD_SKIPPED,{interface:"tui"}).catch(()=>{}),d();},[d]),c=useCallback(async()=>{n.current+=1,S(w.CLI_CLAUDE_MD_ACCEPTED,{interface:"tui",attempt:n.current}).catch(()=>{}),r("installing");try{await Ge(ue),r("installed");}catch(m){if(m instanceof Xe){r("installed");return}zP.warn(`Failed to install ${ue}: ${m instanceof Error?m.message:m}`),r("error");}},[]),u=t==="error"?JP:WP;return useInput((m,p)=>{if(p.escape){t==="prompt"||t==="error"?l():t==="installed"&&d();return}if(t==="prompt"||t==="error"){p.upArrow&&i>0?s(i-1):p.downArrow&&i<u.length-1?s(i+1):p.return&&(i===0?(s(0),c()):l());return}t==="installed"&&p.return&&d();}),jsxs(Box,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[jsx(Et,{}),jsxs(Box,{flexDirection:"column",paddingX:1,gap:1,children:[jsx(Text,{color:"green",bold:true,children:o>0?"\u2713 Starter kit installed!":"\u2713 Setup complete!"}),t==="prompt"&&jsxs(Fragment,{children:[jsxs(Box,{flexDirection:"column",children:[jsx(Text,{bold:true,children:"Personalize your Claude Code"}),jsx(Text,{children:"This plugin helps Claude understand your preferences and work style."})]}),jsx(Vm,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]}),t==="installing"&&jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{type:"dots"})}),jsxs(Text,{color:"cyan",children:[" Installing ",ue,"..."]})]}),t==="installed"&&jsxs(Fragment,{children:[jsxs(Text,{color:"green",bold:true,children:["\u2713 ",ue," 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:["/",ue]})]}),jsx(Text,{children:"Claude will guide you through the rest."}),jsx(Text,{dimColor:true,children:"Press Enter to continue to the catalog..."})]}),t==="error"&&jsxs(Fragment,{children:[jsxs(Text,{color:"red",bold:true,children:["\u2717 Failed to install ",ue]}),jsx(Vm,{options:u,cursorIndex:i}),jsx(Text,{dimColor:true,children:"You can always install it later from the catalog."})]})]})]})}function Vm({options:e,cursorIndex:a}){return jsx(Box,{flexDirection:"column",children:e.map((o,t)=>jsxs(Text,{bold:t===a,color:t===a?"cyan":void 0,children:[t===a?"\u203A ":" ",o]},o))})}var _P=promisify(execFile),Os="@ciandt-flow/cli";async function Xm(){let e=te;if(qd.prerelease(e)||process.env.NODE_ENV==="development")return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Os};try{let a=await fetch(`https://registry.npmjs.org/${Os}/latest`);if(!a.ok)throw new Error(`Registry returned ${a.status}`);let t=(await a.json()).version;return {currentVersion:e,latestVersion:t,isOutdated:t!==e,packageName:Os}}catch{return {currentVersion:e,latestVersion:e,isOutdated:false,packageName:Os}}}async function Ns(e){try{return await _P(Ka(),["install","-g",e.packageName],{timeout:6e4,shell:process.platform==="win32"}),{success:!0}}catch(a){return {success:false,error:String(a)}}}async function XP(e){let a=ta(e.alias);if(!a?.installMethod)return a?.installedVersion??null;try{let t=await Oa(a.installMethod).getInstalledVersion(e);return t&&t!==a.installedVersion&&await ya({...a,installedVersion:t,lastChecked:new Date().toISOString()}),t??a.installedVersion}catch{return a.installedVersion}}async function Km(e){let a=await XP(e),o=null,t=AbortSignal.timeout(3e4);try{if(e.versionCheck.type==="npm-registry"){let i=await fetch(`https://registry.npmjs.org/${e.versionCheck.package}/latest`,{signal:t});if(!i.ok)throw new Error(`Registry returned ${i.status}`);o=(await i.json()).version;}else if(e.versionCheck.type==="github-releases"){let i=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:t});if(!i.ok)throw new Error(`GitHub returned ${i.status}`);o=(await i.json()).tag_name.replace(/^v/,"");}}catch{}let r=a!==null&&o!==null&&a!==o;return {moduleAlias:e.alias,currentVersion:a,latestVersion:o,isOutdated:r}}async function $m(e,a){let o=ta(e.alias);if(!o?.installMethod)return {success:false,error:"Unknown install method"};let r=await Oa(o.installMethod).update(e,a.currentVersion??"");return r.success?(await ya({...o,installedVersion:r.version??o.installedVersion,lastChecked:new Date().toISOString()}),{success:true,newVersion:r.version}):{success:false,error:r.error?.message}}function Ym(e){let o=ta(e.alias)?.installMethod,t=e.platforms[process.platform];if(t?.status==="supported"){if(o==="npm"){let r=t.strategies.find(i=>i.type==="npm");if(r?.type==="npm")return `npm install -g ${r.package}`}if(o==="homebrew"){let r=t.strategies.find(i=>i.type==="homebrew");if(r?.type==="homebrew")return `brew upgrade ${r.formula}`}}}function Zm(){let[e,a]=useState({outcome:"running",items:[{id:"cli",label:"@ciandt-flow/cli",status:"pending"},...se.map(t=>({id:t.alias,label:t.name,status:"pending"}))]}),o=useCallback((t,r)=>{a(i=>({...i,items:i.items.map(s=>s.id===t?{...s,...r}:s)}));},[]);return useEffect(()=>{async function t(){try{let[r,i,s]=await Promise.all([Xm(),Yt(se),Promise.all(se.map(d=>Km(d)))]);if(Ts(),r.isOutdated){o("cli",{status:"updating",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),(await Ns(r)).success?(o("cli",{status:"updated",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`}),a(l=>({...l,outcome:"cli-updated"}))):(o("cli",{status:"error",detail:`v${r.currentVersion} \u2192 v${r.latestVersion}`,manualCommand:`npm install -g ${r.packageName}`}),a(l=>({...l,outcome:"cli-update-failed"})));return}o("cli",{status:"ok",detail:`v${r.currentVersion}`});let n=i.some(d=>!d.alreadyInstalled);for(let d of i)d.alreadyInstalled||o(d.module.alias,{status:"missing"});if(n){a(d=>({...d,outcome:"module-missing"}));return}for(let d of s){let l=se.find(u=>u.alias===d.moduleAlias);if(!l)continue;if(!d.isOutdated){o(d.moduleAlias,{status:"ok",detail:d.currentVersion?`v${d.currentVersion}`:void 0});continue}o(d.moduleAlias,{status:"updating",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`});let c=await $m(l,d);c.success?o(d.moduleAlias,{status:"updated",detail:`v${c.newVersion}`}):o(d.moduleAlias,{status:"error",detail:`v${d.currentVersion} \u2192 v${d.latestVersion}`,manualCommand:Ym(l)});}a(d=>({...d,items:d.items.map(l=>l.status==="pending"?{...l,status:"ok"}:l)})),await et(),a(d=>({...d,outcome:"done"}));}catch{await et(),a(r=>({...r,outcome:"done"}));}}t();},[o]),e}U();function aD({item:e}){return e.status==="pending"||e.status==="updating"?jsxs(Box,{children:[jsx(Text,{color:"cyan",children:jsx(wp,{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 oD({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 eg(){let{outcome:e,items:a}=Zm(),o=y(r=>r.setScreen),t=y(r=>r.setFocus);return useEffect(()=>{if(e==="done"){let r=setTimeout(()=>{let i=ne().some(s=>s.name===ue);o(i?"main":"claudeMdSuggestion"),t("list");},1500);return ()=>clearTimeout(r)}if(e==="module-missing"){let r=setTimeout(()=>{o("moduleSetup"),t("moduleSetup");},500);return ()=>clearTimeout(r)}},[e,o,t]),jsxs(Box,{flexDirection:"column",paddingX:2,paddingY:1,children:[jsx(Box,{marginBottom:1,children:jsx(Text,{bold:true,children:"Checking environment..."})}),jsx(Box,{flexDirection:"column",gap:0,children:a.map(r=>jsx(aD,{item:r},r.id))}),e!=="running"&&jsx(Box,{marginTop:1,children:jsx(oD,{outcome:e})})]})}Se();St();I();mn();var sD={debug:"gray",info:"cyan",warn:"yellow",error:"red"},ag=10;function og(){let[e,a]=useState(pn());useEffect(()=>Hc(()=>{a([...pn()]);}),[]);let o=e.slice(-ag);return jsxs(Box,{flexDirection:"column",borderStyle:"single",borderColor:"cyan",paddingX:1,children:[jsxs(Text,{color:"cyan",bold:true,children:["Debug Log (last ",ag,") \u2014 press Ctrl+D to close"]}),o.length===0?jsx(Text,{dimColor:true,children:"No log entries yet"}):o.map((t,r)=>jsxs(Text,{color:sD[t.level],children:["[",t.level.toUpperCase(),"] [",t.module,"] ",t.message]},r))]})}var lD=P("app"),uD={auth:Bl,starterKitSetup:Dm,moduleSetup:Hm,claudeMdSuggestion:_m,verify:eg,main:lm};function ig(){let{setScreen:e,setFocus:a}=y.getState();e("auth"),a("auth");}function Ui(e){let{setScreen:a,setFocus:o}=y.getState();!e.starterKit||e.starterKit.trim()===""?(a("starterKitSetup"),o("starterKitList")):(a("verify"),o("verify"));}function sg(){S(w.CLI_SESSION_STARTED,{cli_version:te,os:process.platform,node_version:process.version,duration_ms:yo(),interface:"tui"}).catch(()=>{});}async function dg(){let e=await Y();if(e&&Rl()&&await vo()){e.customUrl&&Ia(e.customUrl);let{clientSecret:t,...r}=e;oa.getState().setCredentials(r),sg(),Ui(e);return}if(!e){ig();return}try{e.customUrl&&Ia(e.customUrl),await Ma();}catch(t){lD.debug(`Token validation failed: ${String(t)}`),ig();return}sg();let{clientSecret:a,...o}=e;oa.getState().setCredentials(o),Ui(e);}function cg(){let{columns:e,rows:a}=useWindowSize(),o=y(n=>n.screen),t=uD[o],{pendingExit:r}=bl(),i=y(n=>n.debugPanelOpen),s=!!process.env.DEBUG;return useInput((n,d)=>{if(s&&d.ctrl&&n==="d"){let l=y.getState().debugPanelOpen;y.getState().setDebugPanelOpen(!l);}}),t?jsxs(Box,{flexDirection:"column",width:e,height:a,children:[jsx(t,{}),s&&i&&jsx(og,{}),r&&jsx(Box,{paddingX:1,children:jsx(Text,{color:"yellow",children:"Press Ctrl+C again to quit"})})]}):jsxs(Text,{color:"red",children:["Unknown screen: ",o]})}Se();Ci();j();U();I();lr();Se();async function ic(e,a={}){let o=Ii({clientId:e.clientId,clientSecret:e.clientSecret,tenant:e.tenant,customUrl:e.customUrl,starterKit:e.starterKit},a);return Ti(o),await bo(e),{jwt:o.jwt,anthropicBaseUrl:o.anthropicBaseUrl,previousToken:o.previousToken,previousBaseUrl:o.previousBaseUrl,hadExistingFile:o.hadExistingFile}}var Aa=P("auth");function ug(){Ve.clearFallbackFile(),Pi();}var pD=3,lg=3,pg=` \u2139 The data collected during setup is used solely to improve
|
|
122
122
|
Flow's internal tools and will not be shared externally.
|
|
123
123
|
`;function Qa(e,a={}){return new Promise((o,t)=>{let{masked:r=false,defaultValue:i=""}=a;process.stdout.write(e+i);let s=i,n=c=>{if(c===""){d(),t(new Error("SIGINT"));return}if(c==="\r"||c===`
|
|
124
124
|
`){d(),process.stdout.write(`
|
|
125
|
-
`),o(s);return}if(c==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(s+=c,process.stdout.write(r?"*".repeat(c.length):c));};function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",n),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",n);})}async function
|
|
125
|
+
`),o(s);return}if(c==="\x7F"){s.length>0&&(s=s.slice(0,-1),process.stdout.write("\b \b"));return}c.startsWith("\x1B")||(s+=c,process.stdout.write(r?"*".repeat(c.length):c));};function d(){process.stdin.setRawMode(false),process.stdin.removeListener("data",n),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l),process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l);}function l(){try{process.stdin.setRawMode(!1);}catch{}process.exit(1);}process.on("uncaughtException",l),process.on("unhandledRejection",l),process.on("SIGINT",l),process.on("SIGTERM",l),process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",n);})}async function mD(){let e=$o();return process.stdout.write(`
|
|
126
126
|
`+R.yellow(" \u26A0 ")+`${b(e)} contains invalid JSON.
|
|
127
|
-
`),(await Qa(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function mg(e,a,o){try{await ic(e,{jwtOverride:o});return}catch(t){if(!(t instanceof Yo))throw t;if(!a)throw new Error(`${t.message}. Fix or remove ${$o()} and retry.`);if(!await
|
|
128
|
-
`));}}async function
|
|
127
|
+
`),(await Qa(R.cyan(" ? ")+"Overwrite it with a fresh file containing only the auth token? (y/N): ")).trim().toLowerCase()==="y"}async function mg(e,a,o){try{await ic(e,{jwtOverride:o});return}catch(t){if(!(t instanceof Yo))throw t;if(!a)throw new Error(`${t.message}. Fix or remove ${$o()} and retry.`);if(!await mD())throw new Error("Setup cancelled: settings.json must be valid JSON to continue");await ic(e,{allowOverwriteMalformed:true,jwtOverride:o});}}async function gD(){if((await Qa(R.cyan(" ? ")+"Does your organization use a custom Flow URL? (y/N): ")).trim().toLowerCase()!=="y")return null;for(;;){let a=(await Qa(R.cyan(" ? ")+"Enter custom Flow URL: ")).trim();if(mt.test(a))return a;process.stderr.write(R.yellow(` \u26A0 ${gt}. Try again.
|
|
128
|
+
`));}}async function fD(){let e=(await Qa(R.cyan(" ? ")+"Does your email use the @ciandt.com domain? (Y/n): ")).trim();if(e===""||e.toLowerCase()==="y")return null;for(;;){let a=(await Qa(R.cyan(" ? ")+"Enter your email address: ")).trim();if(ft.test(a))return a;process.stderr.write(R.yellow(` \u26A0 ${ht}. Try again.
|
|
129
129
|
`));}}async function gg(e,a){process.stdout.write(R.dim(" Installing flow-ai-obs..."));let{npmFailed:o,initFailed:t,unexpectedError:r}=await ji(e,a);return o?process.stdout.write(R.yellow(` \u26A0 npm install failed. Please contact Flow support.
|
|
130
130
|
`)):r?process.stdout.write(R.yellow(` \u26A0 Unexpected error. Please contact Flow support.
|
|
131
131
|
`)):t?process.stdout.write(R.yellow(`
|
|
@@ -140,7 +140,7 @@ This will run: ${i}
|
|
|
140
140
|
Starter kit '${b(e.name)}' has no plugins to install.
|
|
141
141
|
`)),true;process.stdout.write(`
|
|
142
142
|
Installing ${e.plugins.length} plugins from '${b(e.name)}'...
|
|
143
|
-
`);let a=0,o=0,t=e.plugins.length;for(let r of e.plugins){let i=a+o+1;process.stdout.write(R.dim(` [${i}/${t}] Installing ${b(r)}...`));let s=false;for(let n=1;n<=
|
|
143
|
+
`);let a=0,o=0,t=e.plugins.length;for(let r of e.plugins){let i=a+o+1;process.stdout.write(R.dim(` [${i}/${t}] Installing ${b(r)}...`));let s=false;for(let n=1;n<=pD;n++)try{await Ge(r),a++,s=!0;break}catch(d){if(d instanceof Xe){a++,s=true;break}}s?process.stdout.write(R.green(` done
|
|
144
144
|
`)):(o++,process.stdout.write(R.red(` failed
|
|
145
145
|
`)));}return o===0?process.stdout.write(R.green(` \u2713 Starter kit '${b(e.name)}' selected. ${a}/${t} plugins installed successfully.
|
|
146
146
|
`)):process.stdout.write(R.yellow(` \u26A0 Starter kit '${b(e.name)}' selected. ${a}/${t} plugins installed. ${o} failed.
|
|
@@ -158,7 +158,7 @@ This will run: ${i}
|
|
|
158
158
|
`),process.stdout.write(` Open Claude in a new terminal or in VS Code and type:
|
|
159
159
|
`),process.stdout.write(R.cyan.bold(` /${ue}
|
|
160
160
|
`)),process.stdout.write(` Claude will guide you through the rest.
|
|
161
|
-
`);}async function
|
|
161
|
+
`);}async function hD(e){if(ug(),process.stdout.write(`
|
|
162
162
|
`+pg+`
|
|
163
163
|
`),e.customUrl!==void 0&&!mt.test(e.customUrl))return process.stderr.write(R.red(` \u2717 ${gt}.
|
|
164
164
|
`)),1;if(e.customEmail!==void 0&&!ft.test(e.customEmail))return process.stderr.write(R.red(` \u2717 ${ht}.
|
|
@@ -174,11 +174,11 @@ This will run: ${i}
|
|
|
174
174
|
|
|
175
175
|
`)),t&&process.stdout.write(R.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
176
176
|
`)),0}catch(r){if(r instanceof Error&&r.message==="SIGINT")throw r;let i=b(r instanceof Error?r.message:"unknown error");return Aa.error(`[${o.tenant}] Starter kit setup failed: ${i}`),process.stderr.write(R.red(` \u2717 Starter kit setup failed: ${i}
|
|
177
|
-
`)),1}}async function
|
|
177
|
+
`)),1}}async function bD(e,a){ug(),Aa.debug("[auth] Starting interactive authentication");try{process.stdout.write(`
|
|
178
178
|
`),process.stdout.write(pg+`
|
|
179
179
|
`);let o=(await Qa(R.cyan(" ? ")+"JWT: ",{masked:!0})).trim();if(!o)return Aa.error("[auth] Validation failed: JWT is required"),process.stderr.write(R.red(` \u2717 JWT is required
|
|
180
180
|
`)),1;let t;try{t=kr(o);}catch(d){let l=b(d instanceof Error?d.message:"Invalid JWT");return process.stderr.write(R.red(` \u2717 ${l}
|
|
181
|
-
`)),1}let r=e??await
|
|
181
|
+
`)),1}let r=e??await gD(),i=a??await fD();r&&Ia(r),Aa.debug(`[${t.tenant}] Authenticating tenant`);try{await Qo(t);}catch(d){let l=b(d instanceof Error?d.message:"unknown error");return Aa.error(`[${t.tenant}] Authentication failed: ${l}`),process.stderr.write(R.red(` \u2717 Authentication failed: ${l}
|
|
182
182
|
`)),1}let{initFailed:s}=await gg(r,i),n=await hg();return await mg({...t,starterKit:n?.slug,customUrl:r??void 0},!0,o),n?await bg(n):process.stdout.write(R.dim(`
|
|
183
183
|
Skipped starter kit installation.
|
|
184
184
|
`)),await vg(),Aa.info(`[${t.tenant}] Authentication successful`),process.stdout.write(R.green(`
|
|
@@ -186,14 +186,14 @@ This will run: ${i}
|
|
|
186
186
|
|
|
187
187
|
`)),s&&process.stdout.write(R.yellow(` \u26A0 flow-ai-obs initialization failed \u2014 domain authentication failure. Please contact support.
|
|
188
188
|
`)),0}catch(o){if(o instanceof Error&&o.message==="SIGINT")throw o;let t=b(o instanceof Error?o.message:"unknown error");return Aa.error(`[auth] Unexpected error: ${t}`),process.stderr.write(R.red(` \u2717 Unexpected error: ${t}
|
|
189
|
-
`)),1}}async function sc(e={}){if(e.jwt)return
|
|
189
|
+
`)),1}}async function sc(e={}){if(e.jwt)return hD({jwt:e.jwt,starterKit:e.starterKit,customUrl:e.customUrl,customEmail:e.customEmail});if(e.customUrl!==void 0&&!mt.test(e.customUrl))return process.stderr.write(R.red(` \u2717 ${gt}.
|
|
190
190
|
`)),1;if(e.customEmail!==void 0&&!ft.test(e.customEmail))return process.stderr.write(R.red(` \u2717 ${ht}.
|
|
191
|
-
`)),1;try{return await
|
|
192
|
-
`),130;throw a}}async function
|
|
191
|
+
`)),1;try{return await bD(e.customUrl,e.customEmail)}catch(a){if(a instanceof Error&&a.message==="SIGINT")return process.stdout.write(`
|
|
192
|
+
`),130;throw a}}async function vD(){try{return process.stdout.write(`
|
|
193
193
|
`),(await Qa(R.cyan(" ? ")+"Are you sure? This will remove your local credentials. (y/N): ")).toLowerCase()!=="y"?(process.stdout.write(R.yellow(` \u26A0 Logout cancelled
|
|
194
194
|
`)),0):null}catch(e){if(e instanceof Error&&e.message==="SIGINT")return process.stdout.write(`
|
|
195
195
|
`),130;throw e}}async function yg(e){if(!await Y())return process.stdout.write(R.yellow(` \u26A0 You are not authenticated
|
|
196
|
-
`)),0;if(!e){let a=await
|
|
196
|
+
`)),0;if(!e){let a=await vD();if(a!==null)return a}try{return await tl(),process.stdout.write(R.green(` \u2713 Credentials removed successfully
|
|
197
197
|
`)),0}catch{return process.stderr.write(R.red(` \u2717 Error removing credentials
|
|
198
198
|
`)),1}}async function kg(){let e=await Y();return e?await vo()?(process.stdout.write(`
|
|
199
199
|
`+R.bold(` Authenticated
|
|
@@ -202,30 +202,30 @@ This will run: ${i}
|
|
|
202
202
|
`),process.stdout.write(R.dim(" Starter Kit: ")+b(e.starterKit??"not set")+`
|
|
203
203
|
`),process.stdout.write(R.dim(" Config: ")+b(await rl())+`
|
|
204
204
|
`),process.stdout.write(`
|
|
205
|
-
`),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}j();U();He();U();var
|
|
205
|
+
`),0):(process.stdout.write(R.yellow(" \u26A0 Session expired. Run `flow auth login` to re-authenticate.\n")),0):(process.stdout.write(R.yellow(" \u26A0 Not authenticated. Run `flow auth login` to set up.\n")),0)}j();U();He();U();var kD=[le,"flow-harness"];function Pg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function PD(e,a,o=process.env){return Pg(o.DISABLE_AUTOUPDATER)?{name:e,enabled:false,reason:"env-disabled"}:Pg(o.FORCE_AUTOUPDATE_PLUGINS)?{name:e,enabled:true,reason:"env-forced"}:a?.autoUpdate===false?{name:e,enabled:false,reason:"flag"}:a?.autoUpdate===true?{name:e,enabled:true,reason:"flag"}:{name:e,enabled:true,reason:"default"}}function Dg(e){switch(e.reason){case "env-disabled":return "DISABLE_AUTOUPDATER is set";case "env-forced":return "FORCE_AUTOUPDATE_PLUGINS is set";case "flag":return e.enabled?"autoUpdate: true":"autoUpdate: false";case "default":return "default (no explicit flag)"}}function Bs(e=process.env){let a=Uo();if(!we__default.existsSync(a))return [];try{let o=JSON.parse(we__default.readFileSync(a,"utf-8"));return Object.entries(o).map(([t,r])=>PD(t,r,e))}catch{return []}}function wg(){let e=Uo(),a={fixed:[],skipped:[]};if(!we__default.existsSync(e))return a;let o;try{o=JSON.parse(we__default.readFileSync(e,"utf-8"));}catch{return a.skipped.push({name:"(all)",reason:"known_marketplaces.json is malformed JSON"}),a}let t=false;for(let r of kD){let i=o[r];if(!i){a.skipped.push({name:r,reason:"not registered on this machine"});continue}if("autoUpdate"in i){a.skipped.push({name:r,reason:i.autoUpdate?"already autoUpdate: true":"explicitly set to autoUpdate: false \u2014 not overridden"});continue}i.autoUpdate=true,a.fixed.push(r),t=true;}if(t){let r=`${e}.${randomUUID()}.tmp`;we__default.writeFileSync(r,JSON.stringify(o,null,2),{encoding:"utf-8",mode:384}),we__default.renameSync(r,e);}return a}async function DD(e){let a=ne(),o;try{o=await eo(e.source);}catch(r){if(e.source)throw r;o=[];}let t=new Set(a.map(r=>r.name));return S(w.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"available",result_count:o.length}).catch(()=>{}),e.json?(go(o.map(r=>({...r,installed:t.has(r.name)}))),0):(kt(["","Name","Version","Category","Status"],o.map(r=>[t.has(r.name)?"*":" ",r.name??"",r.version??"n/a",r.category??"",t.has(r.name)?"installed":"available"])),0)}async function wD(e){let a=ne(),o=await eo(e.source),t=new Map(o.map(i=>[i.name,i])),r=a.map(i=>{let s=t.get(i.name);return s&&i.version&&s.version&&Ue(i.version,s.version)?{...i,availableVersion:s.version}:null}).filter(i=>i!==null);return S(w.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"outdated",result_count:r.length}).catch(()=>{}),r.length===0?(D("All plugins are up to date."),0):e.json?(go(r),0):(kt(["Name","Installed","Available"],r.map(i=>[i.name??"",i.version??"n/a",i.availableVersion??"n/a"])),process.stdout.write(`
|
|
206
206
|
${r.length} plugin(s) outdated.
|
|
207
|
-
`),0)}async function
|
|
207
|
+
`),0)}async function SD(e){let a=ne();if(S(w.CLI_CATALOG_VIEWED,{interface:Z().interfaceType,filter_type:"all",result_count:a.length}).catch(()=>{}),a.length===0)return D("No plugins installed. Use `flow plugin install <name>` to install one."),0;if(e.json)return go(a),0;let o=[];try{o=await eo(e.source);}catch{o=[];}let t=new Map(o.map(s=>[s.name,s])),r=new Map(Bs().map(s=>[s.name,s.enabled])),i=[...a].sort((s,n)=>{let d=Qr.indexOf(s.scope??"user"),l=Qr.indexOf(n.scope??"user");return (d===-1?1/0:d)-(l===-1?1/0:l)});return kt(["Name","Version","Type","Origin","Scope","Status","Auto-Update","Installed at"],i.map(s=>{let n=t.get(s.name),d=n?.type??"bundle",l=n?.origin??Fd(s.marketplace),c=s.marketplace?r.get(s.marketplace):void 0,u=c===void 0?"n/a":c?"on":"off";return [s.name??"",s.version??"n/a",pt[d]?.label??"Plugin",l,s.scope??"user",s.status??"enabled",u,Ea(s.installedAt??"")]})),process.stdout.write(`
|
|
208
208
|
${a.length} plugin(s) installed.
|
|
209
|
-
`),0}async function Sg(e){if(!await me())return 1;try{return e.available?await
|
|
209
|
+
`),0}async function Sg(e){if(!await me())return 1;try{return e.available?await DD(e):e.outdated?await wD(e):await SD(e)}catch(a){return C(a instanceof Error?a.message:"Failed to list plugins."),1}}xo();j();U();I();var ge=P("manage");function js(e,a){return a?ne().find(o=>o.name===e&&o.scope===a):ne().find(o=>o.name===e)}function CD(e,a){let o=a;return {callbacks:{onStatus:r=>{o&&(o.text=`${e}${r}`);},onError:r=>{o?.stop(),o=void 0,D(`${e}${r}`);},onPause:()=>{o?.stop(),o=void 0;},onResume:r=>{o?.stop(),o=nc({text:`${e}${r}`}).start();}},stopSpinner:()=>{o?.stop(),o=void 0;}}}async function RD(e,a,o,t){let r=t;if(!o.force){r?.stop();let s=b(e),n=b(Ot(e,o.scope));if(!await de(`${a}Install external plugin "${s}"?
|
|
210
210
|
This will run: ${n}
|
|
211
|
-
[y/N] `))return ge.debug(`[${e}] Installation cancelled by user`),o.silent||D(`${a}Skipped ${e} (cancelled).`),{name:e,success:true};o.silent||(r=nc({text:`${a}Installing ${e}...`}).start());}let i=r?
|
|
212
|
-
Installation summary: ${a} succeeded, ${o} failed`);}async function
|
|
213
|
-
Update summary: ${a} updated, ${o} already up to date, ${t} failed`);}async function
|
|
211
|
+
[y/N] `))return ge.debug(`[${e}] Installation cancelled by user`),o.silent||D(`${a}Skipped ${e} (cancelled).`),{name:e,success:true};o.silent||(r=nc({text:`${a}Installing ${e}...`}).start());}let i=r?CD(a,r):void 0;try{let s=await Hp(e,o.marketplaceSource,i?.callbacks,o.scope);if(i?.stopSpinner(),s.exitCode!==0){let n=s.stderr||"Command failed";return o.silent?Fe({status:"error",plugin:e,message:n}):C(`${a}Failed to install "${e}": ${n}`),{name:e,success:!1,error:n}}return o.silent?ye({status:"success",plugin:e,command:s.command,duration_ms:s.duration_ms}):K(`${a}${e} installed successfully (via proxy)`),{name:e,success:!0,duration_ms:s.duration_ms}}catch(s){i?.stopSpinner();let n=$(s);return o.silent?Fe({status:"error",plugin:e,message:n}):C(`${a}Failed to install "${e}": ${n}`),{name:e,success:false,error:n}}}async function AD(e,a,o){let t=o.silent?void 0:nc({text:`${a}Installing ${e}...`}).start();if(Lt(e))return RD(e,a,o,t);try{let r=await Ge(e,{...o,onDownloadProgress:o.silent?void 0:(i,s)=>{if(!t||s===0)return;let{bar:n,percent:d,label:l}=Qi(i,s);t.text=`${a}Downloading ${e}... ${n} ${d}% (${l})`;}});return t?.stop(),o.silent?ye({status:"success",plugin:e,version:r.version,duration_ms:r.duration_ms}):K(`${a}${e} v${r.version} installed successfully`),{name:e,success:!0,version:r.version,duration_ms:r.duration_ms}}catch(r){if(t?.stop(),r instanceof Xe)return o.silent?ye({status:"already_installed",plugin:e,message:r.message}):D(`${a}${r.message}`),{name:e,success:true};let i=$(r);return o.silent?Fe({status:"error",plugin:e,message:i}):C(`${a}Failed to install "${e}": ${i}`),{name:e,success:false,error:i}}}function xD(e){let a=e.filter(t=>t.success).length,o=e.filter(t=>!t.success).length;D(`
|
|
212
|
+
Installation summary: ${a} succeeded, ${o} failed`);}async function ED(e,a){let o=new Map;if(a.source){for(let t of e)o.set(t,a.source);return o}try{let t=await eo();for(let r of e){let s=t.filter(n=>n.name===r).find(n=>n.contentSource);s?.contentSource&&o.set(r,s.contentSource);}}catch{}return o}async function or(e,a={}){if(!await me())return 1;let o=[],t=await ED(e,a);for(let r=0;r<e.length;r++){let i=e.length>1?`[${r+1}/${e.length}] `:"",s=e[r],n=t.get(s)??a.source,d=await AD(s,i,{...a,source:n});o.push(d);}return e.length>1&&(a.silent?ye({status:"summary",succeeded:o.filter(r=>r.success).length,failed:o.filter(r=>!r.success).length,results:o.map(r=>({plugin:r.name,success:r.success,...r.error?{error:r.error}:{}}))}):xD(o)),o.some(r=>!r.success)?1:0}async function Us(e,a){if(!await me())return 1;if(ge.debug(`[${e}] Looking up installed plugin`),!a.force){let o=js(e,a.scope);if(!o)return ge.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;let t=b(o.name),r=o.version?b(o.version):void 0,i=a.scope?` (${a.scope})`:"";if(!await de(`Remove ${t} ${r?`v${r}`:"(n/a)"}${i}? [y/N] `))return ge.debug(`[${e}] Uninstall cancelled by user`),D("Operation cancelled."),0}try{return ge.debug(`[${e}] Uninstalling plugin${a.scope?` (scope: ${a.scope})`:""}`),await Ir(e,a.scope),ge.info(`[${e}] Uninstalled successfully`),K("Plugin removed successfully"),0}catch(o){return ge.error(`[${e}] Failed to uninstall: ${$(o)}`),C($(o)),1}}async function Cg(e,a={}){if(!await me())return 1;ge.debug(`[${e}] Looking up installed plugin`);let o=js(e,a.scope);if(!o)return ge.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;if(o.status==="enabled")return ge.debug(`[${e}] Already enabled, skipping`),D(`${o.name} is already enabled`),0;try{return ge.debug(`[${e}] Enabling plugin (current status: ${o.status})`),await Tr(e,"enabled",a.scope),ge.info(`[${e}] Enabled successfully`),K(`${o.name} enabled successfully`),0}catch(t){return ge.error(`[${e}] Failed to enable: ${$(t)}`),C($(t)),1}}async function Rg(e,a={}){if(!await me())return 1;ge.debug(`[${e}] Looking up installed plugin`);let o=js(e,a.scope);if(!o)return ge.error(`[${e}] Plugin is not installed`),C(`Plugin "${e}" is not installed`),1;if(o.status==="disabled")return ge.debug(`[${e}] Already disabled, skipping`),D(`${o.name} is already disabled`),0;try{return ge.debug(`[${e}] Disabling plugin (current status: ${o.status})`),await Tr(e,"disabled",a.scope),ge.info(`[${e}] Disabled successfully`),K(`${o.name} disabled successfully`),0}catch(t){return ge.error(`[${e}] Failed to disable: ${$(t)}`),C($(t)),1}}async function Ag(e,a,o){o.silent||D(`${a}Updating ${e}...`);try{let t=await ys(e,o);return o.silent?ye({status:"updated",plugin:t.name,previousVersion:t.previousVersion,newVersion:t.newVersion,duration_ms:t.duration_ms}):K(`${a}${t.name} v${t.previousVersion} \u2192 v${t.newVersion}`),{name:e,success:!0}}catch(t){if(t instanceof Ao)return o.silent?ye({status:"up_to_date",plugin:e,message:t.message}):D(`${a}${t.message}`),{name:e,success:true,skipped:true};let r=$(t);return o.silent?Fe({status:"error",plugin:e,message:r}):C(`${a}Failed to update ${e}: ${r}`),{name:e,success:false,error:r}}}function ID(e){let a=e.filter(r=>r.success&&!r.skipped).length,o=e.filter(r=>r.skipped).length,t=e.filter(r=>!r.success).length;D(`
|
|
213
|
+
Update summary: ${a} updated, ${o} already up to date, ${t} failed`);}async function TD(e,a,o){try{let t=await Bt(e,o.source);Ue(a,t.version,o.force)?D(`Would update ${e}: v${a} \u2192 v${t.version}`):D(`${e} is already up to date (v${a})`);}catch(t){return C($(t)),1}return 0}function MD(e){return new Map(e.filter(a=>!!a.version).map(a=>[a.name,a.version]))}function qD(e,a,o){let t=a.get(e.name);return t?e.version&&Ue(e.version,t,o)?(D(`Would update ${e.name}: v${e.version} \u2192 v${t}`),true):(D(`${e.name} is already up to date (${e.version?`v${e.version}`:"n/a"})`),false):(D(`Skipping ${e.name}: not found in catalog`),false)}async function LD(e,a){try{let o=await eo(a.source),t=MD(o),r=0;for(let i of e)qD(i,t,a.force)&&r++;r===0&&D("All plugins are up to date");}catch(o){return C($(o)),1}return 0}async function FD(e,a){let o=[];for(let t=0;t<e.length;t++){let r=`[${t+1}/${e.length}] `,i=await Ag(e[t].name,r,a);o.push(i);}return a.silent?ye({status:"summary",updated:o.filter(t=>t.success&&!t.skipped).length,upToDate:o.filter(t=>t.skipped).length,failed:o.filter(t=>!t.success).length,results:o.map(t=>({plugin:t.name,success:t.success,...t.skipped?{skipped:true}:{},...t.error?{error:t.error}:{}}))}):ID(o),o.some(t=>!t.success)?1:0}async function xg(e,a={}){if(!await me())return 1;if(e){let r=js(e,a.scope);return r?a.dryRun?TD(e,r.version??"",a):(await Ag(e,"",a)).success?0:1:(a.silent?Fe({status:"error",plugin:e,message:`Plugin "${e}" is not installed`}):C(`Plugin "${e}" is not installed`),1)}let t=ne().filter(r=>r.marketplace===le);return t.length===0?(a.silent?ye({status:"empty",message:"No plugins installed"}):D("No plugins installed"),0):a.dryRun?LD(t,a):FD(t,a)}j();I();var $r=P("cli:bundle");function OD(e){let a=b(e.name??e.flowId),o=b(e.type??"unknown");return e.available?` \u2713 ${a} (${o})`:` \u2717 ${a} (${o}) \u2014 unavailable`}function ND(e,a){let o=a.filter(r=>r.available).length,t=a.length-o;process.stdout.write(`
|
|
214
214
|
Bundle: ${b(e)} (${a.length} artifacts)
|
|
215
|
-
`);for(let r of a)process.stdout.write(`${
|
|
215
|
+
`);for(let r of a)process.stdout.write(`${OD(r)}
|
|
216
216
|
`);process.stdout.write(`
|
|
217
217
|
${o} available for installation`),t>0&&process.stdout.write(` | ${t} unavailable`),process.stdout.write(`
|
|
218
218
|
|
|
219
|
-
`);}async function Eg(e){if(!e.trim())return C("Bundle name cannot be empty."),1;if(!await me())return 1;$r.debug(`Fetching bundle "${e}"`);let o;try{o=await ws(e);}catch(n){return n instanceof Kt||n instanceof Hr?(C(n.message),1):(C(`Failed to fetch bundle: ${n instanceof Error?n.message:String(n)}`),1)}let t=o.artifact.artifacts,r=t.filter(n=>n.available);if($r.debug(`Bundle "${o.title}" \u2014 ${t.length} artifact(s), ${r.length} available`),
|
|
219
|
+
`);}async function Eg(e){if(!e.trim())return C("Bundle name cannot be empty."),1;if(!await me())return 1;$r.debug(`Fetching bundle "${e}"`);let o;try{o=await ws(e);}catch(n){return n instanceof Kt||n instanceof Hr?(C(n.message),1):(C(`Failed to fetch bundle: ${n instanceof Error?n.message:String(n)}`),1)}let t=o.artifact.artifacts,r=t.filter(n=>n.available);if($r.debug(`Bundle "${o.title}" \u2014 ${t.length} artifact(s), ${r.length} available`),ND(o.title,t),r.length===0)return C("No artifacts available for installation in this bundle."),1;if(!await de(`Install ${r.length} artifact(s)? [Y/n] `))return $r.debug("Installation cancelled by user"),0;$r.debug(`Starting installation of ${r.length} artifact(s)`);let s=await fs(o,{onProgress:({index:n,total:d,artifact:l,success:c,error:u})=>{let m=b(l.name??l.flowId),p=b(l.type??"unknown"),h=c?"\u2713":`\u2717 (${b(u??"failed")})`;n===1&&process.stdout.write(`
|
|
220
220
|
`),process.stdout.write(`[${n}/${d}] Installing ${m} (${p})... ${h}
|
|
221
221
|
`),n===d&&process.stdout.write(`
|
|
222
|
-
`);}});if($r.debug(`Installation complete \u2014 ${s.installed} installed, ${s.failed} failed, ${s.skipped} skipped`),s.installed>0&&K(`${s.installed} installed successfully`),s.failed>0){let n=s.failures.map(d=>d.name).join(", ");C(`${s.failed} failed: ${b(n)}`);}if(s.skipped>0){let n=t.filter(d=>!d.available).map(d=>b(d.name??d.flowId)).join(", ");D(`${s.skipped} unavailable: ${n}`);}return 0}xo();j();I();var Ig=P("marketplace");function
|
|
222
|
+
`);}});if($r.debug(`Installation complete \u2014 ${s.installed} installed, ${s.failed} failed, ${s.skipped} skipped`),s.installed>0&&K(`${s.installed} installed successfully`),s.failed>0){let n=s.failures.map(d=>d.name).join(", ");C(`${s.failed} failed: ${b(n)}`);}if(s.skipped>0){let n=t.filter(d=>!d.available).map(d=>b(d.name??d.flowId)).join(", ");D(`${s.skipped} unavailable: ${n}`);}return 0}xo();j();I();var Ig=P("marketplace");function BD(e){return `claude plugin marketplace add ${e}`}async function Tg(e,a){if(!await me())return 1;let o;try{o=es(e);}catch(i){let s=$(i);return a.silent?Fe({status:"error",source:e,message:s}):C(s),1}Ig.debug(`[marketplace] Adding marketplace source: ${o}`);let t=BD(o);if(!a.force){let i=b(o),s=b(t);if(!await de(`Add marketplace "${i}"?
|
|
223
223
|
This will run: ${s}
|
|
224
|
-
[y/N] `))return Ig.debug("[marketplace] Operation cancelled by user"),D("Operation cancelled."),0}let r=a.silent?void 0:nc({text:`Adding marketplace "${b(o)}"...`}).start();try{let i=await Te(t);return r?.stop(),i.exitCode!==0?(a.silent?Fe({status:"error",source:o,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(C(`Failed to add marketplace "${o}": ${i.stderr||"Command failed"}`),a.verbose&&i.stdout&&D(`stdout: ${i.stdout}`)),1):(a.silent?ye({status:"success",source:o,command:t,duration_ms:i.duration_ms}):(K(`Marketplace "${o}" added successfully`),a.verbose&&i.stdout&&D(i.stdout)),0)}catch(i){r?.stop();let s=$(i);return a.silent?Fe({status:"error",source:o,message:s}):C(`Failed to add marketplace "${o}": ${s}`),1}}Se();j();async function
|
|
224
|
+
[y/N] `))return Ig.debug("[marketplace] Operation cancelled by user"),D("Operation cancelled."),0}let r=a.silent?void 0:nc({text:`Adding marketplace "${b(o)}"...`}).start();try{let i=await Te(t);return r?.stop(),i.exitCode!==0?(a.silent?Fe({status:"error",source:o,exitCode:i.exitCode,message:i.stderr||"Command failed"}):(C(`Failed to add marketplace "${o}": ${i.stderr||"Command failed"}`),a.verbose&&i.stdout&&D(`stdout: ${i.stdout}`)),1):(a.silent?ye({status:"success",source:o,command:t,duration_ms:i.duration_ms}):(K(`Marketplace "${o}" added successfully`),a.verbose&&i.stdout&&D(i.stdout)),0)}catch(i){r?.stop();let s=$(i);return a.silent?Fe({status:"error",source:o,message:s}):C(`Failed to add marketplace "${o}": ${s}`),1}}Se();j();async function WD(){return await Y()?{passed:true,message:"Credentials configured"}:{passed:false,message:"Credentials not configured \u2014 Run `flow auth login`"}}async function JD(){let e=Date.now();try{await eo();let a=Date.now()-e;return {passed:!0,message:`Prompt Manager accessible (${a}ms)`,latency:a}}catch(a){return a instanceof Error&&a.name==="TimeoutError"?{passed:false,message:"Timeout after 5s \u2014 check your connection"}:{passed:false,message:`Connection error: ${a instanceof Error?a.message:"Unknown"}`}}}async function HD(){return await vo()?{passed:true,message:"Token is valid"}:{passed:false,message:"Token expired \u2014 run `flow auth login` to re-authenticate"}}function QD(){let e=join(homedir(),".claude","settings.json");return existsSync(e)?{passed:true,message:"Claude Code detected"}:{passed:false,message:"Claude Code not detected"}}function VD(){let e=Bs();if(e.length!==0){process.stdout.write(`
|
|
225
225
|
`+R.bold(` Marketplace Auto-Update
|
|
226
226
|
|
|
227
227
|
`));for(let a of e){let o=a.enabled?R.green("[ON] "):R.dim("[OFF]"),t=b(a.name).padEnd(20),r=b(Dg(a));process.stdout.write(` ${o} ${t} ${R.dim(r)}
|
|
228
|
-
`);}}}function
|
|
228
|
+
`);}}}function _D(){process.stdout.write(`
|
|
229
229
|
`+R.bold(` FlowSetup CLI \u2014 Auto-Update Fix
|
|
230
230
|
|
|
231
231
|
`));let e=wg();for(let a of e.fixed)process.stdout.write(` ${R.green("[FIXED]")} ${b(a)} \u2014 autoUpdate: true set
|
|
@@ -235,35 +235,35 @@ This will run: ${s}
|
|
|
235
235
|
|
|
236
236
|
`)):process.stdout.write(R.green(` \u2713 ${e.fixed.length} marketplace(s) updated.
|
|
237
237
|
|
|
238
|
-
`)),0}async function Mg(e={}){if(e.fix)return
|
|
238
|
+
`)),0}async function Mg(e={}){if(e.fix)return _D();process.stdout.write(`
|
|
239
239
|
`+R.bold(` FlowSetup CLI Diagnostics
|
|
240
240
|
|
|
241
|
-
`));let a=[{name:"Credentials",fn:
|
|
242
|
-
`);}return
|
|
241
|
+
`));let a=[{name:"Credentials",fn:WD},{name:"Prompt Manager",fn:JD},{name:"Valid Token",fn:HD},{name:"Claude Code",fn:QD}],o=true;for(let t of a){let r=await t.fn(),i="",s=R.green;r.passed?i=R.green("[OK] "):(i=R.red("[FAIL]"),s=R.red,o=false);let n=` ${i} ${s(t.name.padEnd(18))} ${b(r.message)}`;process.stdout.write(n+`
|
|
242
|
+
`);}return VD(),process.stdout.write(`
|
|
243
243
|
`),o?(process.stdout.write(R.green(` \u2713 All checks passed!
|
|
244
244
|
|
|
245
245
|
`)),0):(process.stdout.write(R.red(` \u2717 Some checks failed \u2014 verify your configuration
|
|
246
246
|
|
|
247
|
-
`)),1)}Se();Ho();U();async function qg(e){let a=await Y(),o=Ta("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),t={Authorization:`Bearer ${e}`,accept:"application/json"};if(a?.tenant){if(!_a.test(a.tenant))throw new Error(`Invalid tenant value: "${a.tenant}"`);t.FlowTenant=a.tenant;}let r=await Au.get(`${o}rate-limit/me`,{searchParams:{mode:"budget"},headers:t}).json();if(typeof r.consumed_usd!="number"||typeof r.budget_limit!="number"||typeof r.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return r}St();Si();Se();j();I();var
|
|
247
|
+
`)),1)}Se();Ho();U();async function qg(e){let a=await Y(),o=Ta("METRICS_COLLECTOR_URL","https://flow.ciandt.com/metrics-collector-api/"),t={Authorization:`Bearer ${e}`,accept:"application/json"};if(a?.tenant){if(!_a.test(a.tenant))throw new Error(`Invalid tenant value: "${a.tenant}"`);t.FlowTenant=a.tenant;}let r=await Au.get(`${o}rate-limit/me`,{searchParams:{mode:"budget"},headers:t}).json();if(typeof r.consumed_usd!="number"||typeof r.budget_limit!="number"||typeof r.percentage!="number")throw new Error("Unexpected budget response shape: missing consumed_usd, budget_limit, or percentage");return r}St();Si();Se();j();I();var KD=P("commands:usage"),zs=20,Lg="EMAIL",Fg="MONTHLY CONSUMPTION (USD)",Og="STATUS";function $D(e){let a=Math.min(100,Math.max(0,e)),o=Math.round(a/100*zs),t=zs-o,r=R.green;return a>=90?r=R.red:a>=70&&(r=R.yellow),r("\u2588".repeat(o))+R.dim("\u2591".repeat(t))}function Ng(e){return `$ ${e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function YD(e){let a=e.toLowerCase(),o=b(e),t=o.charAt(0).toUpperCase()+o.slice(1).toLowerCase();return a==="ok"||a==="unblocked"?R.green(`\u2299 ${t}`):a==="warning"?R.yellow(`\u26A0 ${t}`):a==="blocked"?R.red("\u2717 Budget limit reached"):R.red(`\u2717 ${t}`)}function ZD(e){let a=Ea(e),o=Math.ceil((new Date(e).getTime()-Date.now())/864e5),t=o>0?` (in ${o} day${o===1?"":"s"})`:"";return `${a}${t}`}async function ew(e){try{let a=await Dt();if(a?.email)return b(a.email);let o=wt(e);return b(o.email??"")}catch(a){return KD.debug(`JWT email decode failed: ${String(a)}`),""}}async function Gg(e){if(!await me())return 1;let o;try{o=await Ma();}catch(g){return C(`Authentication error: ${$(g)}`),1}let t;try{t=await qg(o);}catch(g){return C(`Failed to fetch usage data: ${$(g)}`),1}if(e.json)return go(t),0;let r=await ew(o)||b(t.user_id),i=Ng(t.consumed_usd),s=Ng(t.budget_limit),n=`${t.percentage.toFixed(1)}%`,d=`${i} / ${s} (${n})`,l=Math.max(Lg.length,r.length+2),c=Math.max(Fg.length,zs+2+d.length),u=` ${Lg.padEnd(l)} ${Fg.padEnd(c)} ${Og}`,m=` ${"\u2500".repeat(l)} ${"\u2500".repeat(c)} ${"\u2500".repeat(Og.length)}`,p=`${R.cyan("\u2022")} ${r.padEnd(l-2)}`,h=`${$D(t.percentage)} ${d.padEnd(c-zs-2)}`,f=` ${R.dim("Resets")} ${ZD(t.renewal_date)}`;return process.stdout.write(`
|
|
248
248
|
`),process.stdout.write(R.dim(u)+`
|
|
249
249
|
`),process.stdout.write(R.dim(m)+`
|
|
250
|
-
`),process.stdout.write(` ${p} ${h} ${
|
|
250
|
+
`),process.stdout.write(` ${p} ${h} ${YD(t.status)}
|
|
251
251
|
`),process.stdout.write(f+`
|
|
252
252
|
`),process.stdout.write(`
|
|
253
|
-
`),0}var
|
|
254
|
-
`,{encoding:"utf-8",mode:384}),renameSync(r,o);}async function $g(e,a,o){let t=nr(o);await Xg(t,async()=>{let r=await _s(o),i=new Date().toISOString(),s=r.skills[e];r.skills[e]={...a,installedAt:s?.installedAt??i,updatedAt:i},await Kg(r,o);});}async function Yg(e,a){let o=nr(a);await Xg(o,async()=>{let t=await _s(a);e in t.skills&&(delete t.skills[e],await Kg(t,a));});}He();I();var Zg=P("skillInstaller");async function
|
|
253
|
+
`),0}var tw=["github.com","www.github.com"],rw=/^([a-zA-Z0-9_.-]+)\/([a-zA-Z0-9_.@-]+)(\/.*)?$/,iw=/^([^@]+)@(.+)$/;function sw(e){return !!(isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")||e.startsWith(".\\")||e.startsWith("..\\")||/^[a-zA-Z]:[/\\]/.test(e))}function dc(e){let a=e.replace(/\\/g,"/");a=a.replace(/^\/+/,"").replace(/\/+$/,"");let o=a.split("/").filter(Boolean);for(let t of o)if(t==="..")throw new Error(`Invalid subpath: "${e}" contains path traversal ("..").`);return o.join("/")}function nw(e){let a=e.pathname.split("/").filter(Boolean);if(a.length<2)throw new Error(`Invalid GitHub URL: expected at least owner/repo in "${e.href}"`);let o=a[0],t=a[1];t.endsWith(".git")&&(t=t.slice(0,-4));let r={type:"github",url:`https://github.com/${o}/${t}.git`};if(a.length>=3&&(a[2]==="tree"||a[2]==="blob")){if(a.length>=4&&(r.ref=a[3]),a.length>=5){let i=a.slice(4).join("/");r.subpath=dc(i);}}else if(a.length>2){let i=a.slice(2).join("/");r.subpath=dc(i);}return e.hash&&e.hash.length>1&&(r.ref=decodeURIComponent(e.hash.slice(1))),r}function Ws(e){let a=e.trim();if(!a)throw new Error("Skill source cannot be empty.");if(sw(a)){let o=resolve(a);return {type:"local",url:o,localPath:o}}try{let o=new URL(a);if((o.protocol==="https:"||o.protocol==="http:")&&tw.includes(o.hostname))return nw(o);if(o.protocol==="https:"||o.protocol==="http:"){let t={type:"git",url:a};return o.hash&&o.hash.length>1&&(t.ref=decodeURIComponent(o.hash.slice(1)),t.url=a.replace(o.hash,"")),t}if(o.protocol==="git:"){let t={type:"git",url:a};return o.hash&&o.hash.length>1&&(t.ref=decodeURIComponent(o.hash.slice(1)),t.url=a.replace(o.hash,"")),t}}catch{}if(a.startsWith("git@")||a.includes(":")&&a.includes(".git")){let o=a,t,r=a.indexOf("#");r!==-1&&(t=a.slice(r+1),o=a.slice(0,r));let i={type:"git",url:o};return t&&(i.ref=t),i}{let o=a,t,r=o.indexOf("#");r!==-1&&(t=o.slice(r+1),o=o.slice(0,r));let i=o.match(rw);if(i){let s=i[1],n=i[2],d=i[3],l,c=n.match(iw);c&&(n=c[1],l=c[2]),n.endsWith(".git")&&(n=n.slice(0,-4));let u={type:"github",url:`https://github.com/${s}/${n}.git`};if(t&&(u.ref=t),l&&(u.skillFilter=l),d){let m=d.replace(/^\//,"");m&&(u.subpath=dc(m));}return u}}return {type:"git",url:a}}function Js(e){if(e.type!=="github")return null;try{let o=new URL(e.url).pathname.split("/").filter(Boolean);if(o.length<2)return null;let t=o[1];return t.endsWith(".git")&&(t=t.slice(0,-4)),`${o[0]}/${t}`}catch{return null}}function Bg(e){let a=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);return a?{data:parse(a[1])??{},content:a[2]??""}:{data:{},content:e}}var lc=new Set(["node_modules",".git","dist","build","__pycache__"]);function zg(e,a){let o=normalize(resolve(e)),t=normalize(resolve(a));return t.startsWith(o+sep)||t===o}function pw(e,a){let o=normalize(resolve(e)),t=normalize(resolve(join(e,a)));return t.startsWith(o+sep)||t===o}async function cc(e){try{let a=join(e,"SKILL.md");return (await stat(a)).isFile()}catch{return false}}async function Yr(e){try{let a=await readFile(e,"utf-8"),{data:o}=Bg(a);return typeof o.name!="string"||typeof o.description!="string"?null:{name:o.name,description:o.description,path:dirname(e),rawContent:a,metadata:o.metadata}}catch{return null}}async function Wg(e,a=0,o=5){if(a>o)return [];try{let[t,r]=await Promise.all([cc(e),readdir(e,{withFileTypes:!0}).catch(()=>[])]),i=t?[e]:[],s=await Promise.all(r.filter(n=>n.isDirectory()&&!lc.has(n.name)).map(n=>Wg(join(e,n.name),a+1,o)));return [...i,...s.flat()]}catch{return []}}async function Vs(e,a){let o=[],t=new Set;if(a&&!pw(e,a))throw new Error(`Invalid subpath: "${a}" resolves outside the repository directory.`);let r=a?join(e,a):e;if(await cc(r)){let s=await Yr(join(r,"SKILL.md"));if(s)return o.push(s),t.add(s.name),o}let i=[r,join(r,"skills"),join(r,".claude/skills"),join(r,".agents/skills")];for(let s of i)try{let n=await readdir(s,{withFileTypes:!0});for(let d of n){if(!d.isDirectory())continue;let l=join(s,d.name);if(await cc(l)){let c=await Yr(join(l,"SKILL.md"));c&&!t.has(c.name)&&(o.push(c),t.add(c.name));}}}catch{}if(o.length===0){let s=await Wg(r);for(let n of s){let d=await Yr(join(n,"SKILL.md"));d&&!t.has(d.name)&&(o.push(d),t.add(d.name));}}return o}function Jg(e,a){let o=a.map(t=>t.toLowerCase());return e.filter(t=>{let r=t.name.toLowerCase();return o.some(i=>i===r)})}He();var _g=1,vw={retries:5,minTimeout:50};async function Xg(e,a){mkdirSync(dirname(e),{recursive:true});let o=await Ab.lock(e+".lock",{realpath:false,retries:vw});try{return await a()}finally{await o();}}function Hg(){return {version:_g,skills:{}}}async function _s(e){let a=nr(e);try{let o=await readFile(a,"utf-8"),t=JSON.parse(o);return !t.version||t.version<_g?Hg():t}catch{return Hg()}}function yw(e){let a={};for(let o of Object.keys(e).sort())a[o]=e[o];return a}async function Kg(e,a){let o=nr(a);mkdirSync(dirname(o),{recursive:true});let t={version:e.version,skills:yw(e.skills)},r=`${o}.${randomUUID()}.tmp`;writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
254
|
+
`,{encoding:"utf-8",mode:384}),renameSync(r,o);}async function $g(e,a,o){let t=nr(o);await Xg(t,async()=>{let r=await _s(o),i=new Date().toISOString(),s=r.skills[e];r.skills[e]={...a,installedAt:s?.installedAt??i,updatedAt:i},await Kg(r,o);});}async function Yg(e,a){let o=nr(a);await Xg(o,async()=>{let t=await _s(a);e in t.skills&&(delete t.skills[e],await Kg(t,a));});}He();I();var Zg=P("skillInstaller");async function Aw(e,a,o,t){try{await S(w.CLI_TOOL_INSTALLED,{tool_id:e,tool_type:"skill",source:"external",scope:a,version:o,duration_ms:t,interface:Z().interfaceType});}catch(r){Zg.warn(`Failed to send skill install metrics: ${String(r)}`);}}async function xw(e,a){try{await S(w.CLI_TOOL_INSTALL_FAILED,{tool_id:e,tool_type:"skill",source:"external",error_code:a instanceof Error?a.name:"UNKNOWN",error_message:(a instanceof Error?a.message:String(a)).slice(0,500),interface:Z().interfaceType});}catch(o){Zg.warn(`Failed to send skill install-failed metrics: ${String(o)}`);}}async function Ew(e,a){await cp$1(e,a,{recursive:true,dereference:false,filter:o=>{if(lc.has(basename(o)))return false;try{return !lstatSync(o).isSymbolicLink()}catch{return false}}});}async function Iw(e,a,o){let t=na(e.name),r=zo(a),i=join(r,t);if(!zg(r,i))return {skill:e.name,success:false,path:i,error:`Unsafe install path: "${i}" escapes skills directory`};try{await rm$1(i,{recursive:!0,force:!0}),await mkdir(i,{recursive:!0}),await Ew(e.path,i);let n=Js(o)??o.url;return await $g(t,{source:n,sourceType:o.type,sourceUrl:o.url,ref:o.ref,skillPath:o.subpath},a),{skill:e.name,success:!0,path:i}}catch(s){return {skill:e.name,success:false,path:i,error:s instanceof Error?s.message:String(s)}}}async function ef(e,a){let o=Ws(e),t;try{let r;if(o.type==="local"){if(!o.localPath||!existsSync(o.localPath))return {source:e,results:[],discovered:0,installed:0,failed:0};r=o.localPath;}else t=await Ga(o.url,o.ref),r=t;let i=await Vs(r,o.subpath),s=[...a.skillFilter??[]];o.skillFilter&&s.push(o.skillFilter);let n=s.length>0?Jg(i,s):i,d=[],l=o.ref??"latest";for(let c of n){let u=Date.now(),m=await Iw(c,a.scope,o);d.push(m);let p=Date.now()-u;m.success?await Aw(c.name,a.scope,l,p):await xw(c.name,new Error(m.error??"Unknown error"));}return {source:e,results:d,discovered:i.length,installed:d.filter(c=>c.success).length,failed:d.filter(c=>!c.success).length}}finally{t&&await Ba(t).catch(()=>{});}}He();j();I();var Fw=P("skills");async function Ow(e){try{await S(w.CLI_TOOL_UNINSTALLED,{tool_id:e,tool_type:"skill",source:"external",interface:Z().interfaceType});}catch(a){Fw.warn(`Failed to send skill uninstall metrics: ${String(a)}`);}}async function Nw(e){let a=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(`${b(e)} (y/N) `,t=>{a.close(),o(t.trim().toLowerCase()==="y");});})}async function Gw(e){let a=Ws(e),o;try{let t;if(a.type==="local"){if(!a.localPath)return C("Invalid local path."),1;t=a.localPath;}else D(`Fetching skills from ${b(e)}...`),o=await Ga(a.url,a.ref),t=o;let r=await Vs(t,a.subpath);if(r.length===0)return D("No skills found in this source."),0;let s=Js(a)??b(e);D(`Found ${r.length} skill(s) in ${s}:
|
|
255
255
|
`);for(let n of r){let d=b(n.name),l=b(n.description);process.stdout.write(` ${R.bold(d)} ${R.dim(l)}
|
|
256
256
|
`);}return process.stdout.write(`
|
|
257
|
-
`),0}catch(t){return t instanceof Mo?C(t.message):C(t instanceof Error?t.message:String(t)),1}finally{o&&await Ba(o).catch(()=>{});}}function
|
|
258
|
-
`);let a=e.source;e.installed>0&&D(`Installed ${e.installed} of ${e.discovered} skill(s) from ${b(a)}`),e.failed>0&&C(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?D("No skills found in this source."):e.results.length===0&&e.discovered>0&&D(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function of(e,a){if(a.list)return
|
|
257
|
+
`),0}catch(t){return t instanceof Mo?C(t.message):C(t instanceof Error?t.message:String(t)),1}finally{o&&await Ba(o).catch(()=>{});}}function Bw(e){for(let o of e.results){let t=b(o.skill);if(o.success){let r=relative(process.cwd(),o.path);K(`${t} installed ${R.dim(`\u2192 ${r}/`)}`);}else C(`${t}: ${b(o.error??"unknown error")}`);}process.stdout.write(`
|
|
258
|
+
`);let a=e.source;e.installed>0&&D(`Installed ${e.installed} of ${e.discovered} skill(s) from ${b(a)}`),e.failed>0&&C(`${e.failed} skill(s) failed to install`),e.results.length===0&&e.discovered===0?D("No skills found in this source."):e.results.length===0&&e.discovered>0&&D(`Found ${e.discovered} skill(s) but none matched the filter. Use --list to see available skills.`);}async function of(e,a){if(a.list)return Gw(e);let o=a.global?"global":"project";try{let t=await ef(e,{scope:o,skillFilter:a.skill,yes:a.yes});return Bw(t),t.failed>0?1:0}catch(t){return t instanceof Mo?C(t.message):C(t instanceof Error?t.message:String(t)),1}}async function tf(e){let a=zo(e),o=[];try{let t=await readdir(a,{withFileTypes:!0});for(let r of t){if(!r.isDirectory())continue;let i=join(a,r.name),s=join(i,"SKILL.md");try{if(!(await stat(s)).isFile())continue}catch{continue}let n=await Yr(s);n?o.push({name:n.name,description:n.description,path:i}):o.push({name:r.name,description:"(no metadata)",path:i});}}catch{}return o}async function rf(e){let a=e.global?"global":"project",o=await tf(a),t=await _s(a);if(e.json){let i=o.map(s=>({name:s.name,description:s.description,path:s.path,source:t.skills[na(s.name)]?.source}));return go(i),0}if(o.length===0)return D(`No skills installed (${a==="global"?"global":"project"} scope).`),0;D(`${a==="global"?"Global":"Project"} skills (${o.length}):
|
|
259
259
|
`);for(let i of o){let s=t.skills[na(i.name)]?.source,n=b(i.name),d=b(i.description),l=d.length>80?d.slice(0,77)+"...":d,c=s?R.dim(` (${s})`):"";process.stdout.write(` ${R.bold(n)}${c}
|
|
260
260
|
`),process.stdout.write(` ${R.dim(l)}
|
|
261
261
|
|
|
262
262
|
`);}return 0}async function sf(e,a){let o=a.global?"global":"project";if(!e){let s=await tf(o);if(s.length===0)return D("No skills installed."),0;D("Installed skills:");for(let n of s)process.stdout.write(` - ${b(n.name)}
|
|
263
263
|
`);return process.stdout.write(`
|
|
264
|
-
`),D("Specify a skill name to remove: flow skills remove <name>"),1}let t=na(e),r=zo(o),i=join(r,t);try{await stat(i);}catch{return C(`Skill "${b(e)}" is not installed.`),1}if(!a.force&&!await
|
|
265
|
-
Import summary: 0 installed, ${r.length} failed`);for(let n of r)C(` ${n.name}: ${n.error}`);return r.length>0?1:0}D(`Importing ${t.length} plugin(s)...`);let s=0;for(let n of t){let d=a.scope??n.scope??"user",l=
|
|
266
|
-
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)C(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();j();function G(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}j();I();var
|
|
264
|
+
`),D("Specify a skill name to remove: flow skills remove <name>"),1}let t=na(e),r=zo(o),i=join(r,t);try{await stat(i);}catch{return C(`Skill "${b(e)}" is not installed.`),1}if(!a.force&&!await Nw(`Remove skill "${b(t)}"?`))return D("Cancelled."),0;try{return await rm$1(i,{recursive:!0,force:!0}),await Yg(t,o),await Ow(t),K(`Skill "${b(t)}" removed.`),0}catch(s){return C(`Failed to remove skill: ${s instanceof Error?s.message:String(s)}`),1}}j();I();U();var Xs=P("transfer"),pc=1;function jw(e){return e.marketplace&&e.marketplace!==le?`${e.name}@${e.marketplace}`:e.name}function Uw(e,a){let o=e.filter(r=>a.has(r.name)),t=e.filter(r=>!a.has(r.name));o.length>0&&D(`Already installed (${o.length}): ${o.map(r=>r.name).join(", ")}`),D(`To install (${t.length}): ${t.length>0?t.map(r=>r.name).join(", "):"none"}`);}function cf(e){let a=De__default.resolve(e.output);try{let o=ne(),t={version:pc,exportedAt:new Date().toISOString(),plugins:o.map(r=>({name:r.name,marketplace:r.marketplace,scope:r.scope,...r.type!==void 0?{type:r.type}:{}}))};return we__default.writeFileSync(a,JSON.stringify(t,null,2),"utf-8"),K(`Exported ${o.length} plugin(s) to ${a}`),0}catch(o){let t=$(o);return Xs.error(`Export failed: ${t}`),C(`Failed to export plugins: ${t}`),1}}async function lf(e,a={}){if(!await me())return 1;let o;try{let n=we__default.readFileSync(De__default.resolve(e),"utf-8");o=JSON.parse(n);}catch(n){return C(`Failed to read import file "${e}": ${$(n)}`),1}if(o.version!==pc)return C(`Unsupported export format version ${o.version??"(none)"} \u2014 expected ${pc}`),1;if(!Array.isArray(o.plugins))return C('Invalid export file format: missing or invalid "plugins" array'),1;if(o.plugins.length===0)return D("No plugins to import"),0;let t=[],r=[],i=0;for(let[n,d]of o.plugins.entries())if(!d?.name||typeof d.name!="string"){let l=`entry[${n}]`;Xs.warn(`Skipping ${l}: missing or invalid name`),r.push({name:l,error:"missing or invalid name"});}else d.type==="mcp"?(Xs.debug(`[${d.name}] Skipping MCP entry`),i++):t.push(d);if(i>0&&D(`Skipping ${i} MCP(s) \u2014 use 'flow mcp add' to install them manually`),a.diff||a.dryRun){let n=new Set(ne().map(d=>d.name));Uw(t,n);}if(a.dryRun)return D("Dry-run mode: no plugins were installed"),0;if(t.length===0){D(`
|
|
265
|
+
Import summary: 0 installed, ${r.length} failed`);for(let n of r)C(` ${n.name}: ${n.error}`);return r.length>0?1:0}D(`Importing ${t.length} plugin(s)...`);let s=0;for(let n of t){let d=a.scope??n.scope??"user",l=jw(n);Xs.debug(`[${n.name}] Installing as "${l}" in scope "${d}"`),await or([l],{scope:d,force:a.force})===0?s++:r.push({name:n.name,error:"installation failed"});}D(`
|
|
266
|
+
Import summary: ${s} installed, ${r.length} failed`);for(let n of r)C(` ${n.name}: ${n.error}`);return r.length>0?1:0}I();j();function G(e){process.exitCode=e,setTimeout(()=>process.exit(e),100).unref();}j();I();var Ww=P("moduleProxy");function Jw(e){if(!process.stdin.isTTY)return Promise.resolve(false);let a=Pd.createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{a.question(b(e),t=>{a.close(),o(!["n","no"].includes(t.toLowerCase().trim()));});})}async function uf(e,a){let o=Date.now(),r=spawnSync(e.binaryName,a,{stdio:"inherit",env:process.env}).status??1;await S(w.CLI_MODULE_PROXY_EXECUTED,{module_alias:e.alias,exit_code:r,duration_ms:Date.now()-o,subcommand:a[0]??null}).catch(i=>{Ww.warn(`Failed to emit proxy executed event: ${String(i)}`);}),G(r);}async function mf(e,a){let o=se.find(r=>r.alias===e);if(!o){C(`Unknown module alias: '${e}'`),G(1);return}if(!await La(o.binaryName)){C(`Module '${e}' (${o.binaryName}) is not installed.`);let r=o.platforms[process.platform];if(!r||r.status!=="supported"){await S(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_not_supported"}).catch(()=>{}),G(1);return}let i=(await Promise.all(r.strategies.map(async n=>{try{return await Oa(n.type).isAvailable()?n.type:null}catch{return null}}))).find(n=>n!==null)??null;if(!i){C(`No supported installation method available for '${e}' on this platform.`),G(1);return}if(await Jw("Would you like to install it now? [Y/n] ")){await S(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_accepted"}).catch(()=>{});let n=await Co(o,"inline",i);if(!n.success){C(`Failed to install '${e}': ${n.error?.message??"unknown error"}`),G(1);return}await uf(o,a);}else D(`To install manually, run: flow modules install ${e}`),await S(w.CLI_MODULE_NOT_FOUND,{module_alias:e,action_taken:"install_declined"}).catch(()=>{}),G(1);return}await uf(o,a);}j();var _w=promisify(execFile);async function Xw(e){try{if(e.versionCheck.type==="npm-registry"){let{stdout:t}=await _w(Ka(),["view",e.versionCheck.package,"version"],{timeout:5e3,shell:process.platform==="win32"});return String(t).trim()||null}let a=new AbortController,o=setTimeout(()=>a.abort(),5e3);try{let t={"User-Agent":`flow-plugins-cli/${te}`,Accept:"application/vnd.github+json"};process.env.GITHUB_TOKEN&&(t.Authorization=`Bearer ${process.env.GITHUB_TOKEN}`);let r=await fetch(`https://api.github.com/repos/${e.versionCheck.repo}/releases/latest`,{signal:a.signal,headers:t});return r.ok?(await r.json()).tag_name?.replace(/^v/,"")??null:null}finally{clearTimeout(o);}}catch{return null}}function Kw(e,a,o,t){return t?.status==="experimental"?"experimental":!t||t.status!=="supported"||!e?"not_installed":a&&o&&Ue(a,o)?"outdated":"installed"}async function mc(){let e=await Promise.all(se.map(async a=>{let[o,t]=await Promise.all([La(a.binaryName),Xw(a)]),i=ta(a.alias)?.installedVersion??null,s=a.platforms[process.platform],n=Kw(o,i,t,s),d=i??"\u2014";return [a.name,a.alias,d,n,process.platform]}));return kt(["Name","Alias","Version","Status","Platform"],e),0}async function hf(e){let a=se.find(s=>s.alias===e);if(!a)return C(`Unknown module alias: '${e}'`),1;let[o]=await Yt([a]);if(o.alreadyInstalled){let s=ta(a.alias),n=s?.installedVersion?` (v${s.installedVersion})`:"";return D(`Module ${a.name} already installed${n}. Use: flow modules update ${e}`),0}if(o.availableStrategies.length===0){let s=a.platforms[process.platform],n=a.docs?` See: ${a.docs}`:"";return !s||s.status!=="supported"?C(`Module ${a.name} is not supported on ${process.platform}.${n}`):C(`No installation method available for ${a.name} on ${process.platform}.${n}`),1}let t=o.availableStrategies[0],r=nc({text:`Installing ${a.name}...`}).start(),i;try{i=await Co(a,"on_demand",t);}finally{r.stop();}return i.success?(K(`${a.name} v${i.version??"unknown"} installed`),i.pendingInteractiveSetup&&spawnSync(i.pendingInteractiveSetup[0],i.pendingInteractiveSetup.slice(1),{stdio:"inherit"}),0):(C(i.error?.message??"Installation failed"),1)}async function gf(e,a){let o=nc({text:`Updating ${e.name}...`}).start(),t;try{t=await Gi(e,"command");}catch(r){return o.error(`${e.name}: ${r instanceof Error?r.message:String(r)}`),"error"}if(t.success){let r=t.version??"unknown";return r===a?(o.success(`${e.name}: already up to date (v${a})`),"up_to_date"):(o.success(`${e.name}: v${a} \u2192 v${r}`),"success")}return o.error(`${e.name}: ${t.error?.message??"Update failed"}`),"error"}async function bf(e){if(e!==null){let t=se.find(s=>s.alias===e);if(!t)return C(`Unknown module alias: '${e}'`),1;let r=ta(t.alias);return r?.installMethod?await gf(t,r.installedVersion??"unknown")==="error"?1:0:(C(`Module '${e}' not installed. Run: flow modules install ${e}`),1)}let a=Zo().filter(t=>t.installMethod!==null);if(a.length===0)return D("No installed modules to update."),0;let o=0;for(let t of a){let r=se.find(s=>s.alias===t.alias);if(!r)continue;await gf(r,t.installedVersion??"unknown")==="error"&&(o=1);}return o}var vf="ea77652b607cf8d3dd0a1359c08565561e4f758f",Zr=[{path:"0-current-state/INDEX.md",sha256:"987ca6b98f338b82e05e2cab71453ccb7a3e987a56dfd68631735e38356bddff",content:`---
|
|
267
267
|
title: "0-current-state \u2014 Index"
|
|
268
268
|
type: index
|
|
269
269
|
domain: platform
|
|
@@ -555,7 +555,7 @@ analyzes these files and creates the correct \`.md\` files in the numbered folde
|
|
|
555
555
|
If you create a folder with app or script source code, keep it out of the 5 numbered folders
|
|
556
556
|
entirely (e.g. \`prototypes/\`).
|
|
557
557
|
`},{path:"docs/README.md",sha256:"da3c8e019b808bd66cc794d8350bd204d75ba0387eb1545f7223eb9049a911c8",content:"# docs/ \u2014 Raw Input\n\nDrop raw files here \u2014 PDFs, images, standalone Markdowns, tool exports (Jira, Miro, Confluence),\nlegacy documentation. Nothing in this folder is curated content: it exists to be analyzed and\nsynthesized into `0-current-state/`, `1-strategy/`, `2-plan/`, `3-delivery/` or `4-learn/`.\n\nSee `STRUCTURE.md` at the repo root for the full folder guide.\n"}];var Ks=".flow-harness-lock";function $s(e){if(!existsSync(e))return {};try{let a=readFileSync(e,"utf8"),o=JSON.parse(a);return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}catch{return {}}}function Ys(e,a){return e.files?.[a]?.sha256}function yf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,strategy_context:true,strategy_context_source:`@ciandt-flow/cli@${te}`,strategy_context_harness_commit:t};"core_commit"in a||(i.core_commit=""),writeFileSync(e,JSON.stringify(i,null,2)+`
|
|
558
|
-
`,"utf8");}j();var bc="CLAUDE.md";function
|
|
558
|
+
`,"utf8");}j();var bc="CLAUDE.md";function oS(e){return createHash("sha256").update(e,"utf8").digest("hex")}function vc(){return {new:0,unchanged:0,clean:0,divergent:0,declined:0}}async function Pf(e={}){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??kc,s=e.confirmCreate??tS,n=join(a,Ks),d=$s(n),l=[],c=vc(),u={},m=Zr.find(f=>f.path===bc),p=m?existsSync(join(a,m.path)):true;if(m&&!p){let f=join(a,m.path);r?await s(m.path)?(l.push({path:m.path,status:"new"}),c.new++,o||(mkdirSync(dirname(f),{recursive:true}),writeFileSync(f,m.content,"utf8"),u[m.path]=m.sha256)):D(`declined: ${bc} not created`):e.assistant==="claude-code"&&(l.push({path:m.path,status:"new"}),c.new++,o||(mkdirSync(dirname(f),{recursive:true}),writeFileSync(f,m.content,"utf8"),u[m.path]=m.sha256));}for(let f of Zr){if(f.path===bc&&!p)continue;let g=join(a,f.path),v=await yc({dstPath:g,template:f,existingLockHash:Ys(d,f.path),force:t,isInteractive:r,confirmOverwrite:k=>i(k)});l.push({path:f.path,status:v.status}),c[v.status]++,v.write&&!o&&(mkdirSync(dirname(g),{recursive:true}),writeFileSync(g,f.content,"utf8")),v.recordHash&&!o&&(u[f.path]=v.recordHash);}!o&&Object.keys(u).length>0&&yf(n,d,u,vf);let h=c.divergent>0||c.declined>0;return {files:l,counts:c,hasUnresolved:h}}async function yc(e){let{dstPath:a,template:o,existingLockHash:t,force:r,isInteractive:i,confirmOverwrite:s}=e;if(!existsSync(a))return {status:"new",write:true,recordHash:o.sha256};let n=oS(readFileSync(a,"utf8"));return n===o.sha256?{status:"unchanged",write:false,recordHash:o.sha256}:t!==void 0&&n===t?r?{status:"clean",write:true,recordHash:o.sha256}:i?await s(o.path)?{status:"clean",write:true,recordHash:o.sha256}:{status:"declined",write:false,recordHash:void 0}:{status:"declined",write:false,recordHash:void 0}:r?{status:"divergent",write:true,recordHash:o.sha256}:(D(`divergent, kept local (customized): ${o.path}`),{status:"divergent",write:false,recordHash:n})}async function kc(e){return de(` Overwrite ${e} with the updated template? [y/N] `)}async function tS(e){return de(` Create a generic ${e} with Flow strategy conventions? [y/N] `)}var Df="64feeb4e5f6f282d4e0fae6568c0520c5ecd4d5a",wf=[{path:"docs/catalog/TEMPLATES/agents/_TEMPLATE-LEVEL-0.md",sha256:"5f6d1ef6336d69c9fa53ec3167e4f0eb8ec212e21e771356e357e397946f3638",content:`---
|
|
559
559
|
id: <slug-do-card>
|
|
560
560
|
kind: agent | skill
|
|
561
561
|
level: 0
|
|
@@ -84777,29 +84777,37 @@ flow plugin marketplace add cit-flow/flow-harness
|
|
|
84777
84777
|
flow plugin install runbook-tech-common
|
|
84778
84778
|
\`\`\`
|
|
84779
84779
|
`}]};function Sf(e,a,o,t){let r={...a.files??{}};for(let[s,n]of Object.entries(o))r[s]={sha256:n};let i={...a,files:r,docs_content:true,docs_content_source:`@ciandt-flow/cli@${te}`,docs_content_harness_commit:t};"core_commit"in a||(i.core_commit=""),writeFileSync(e,JSON.stringify(i,null,2)+`
|
|
84780
|
-
`,"utf8");}function
|
|
84780
|
+
`,"utf8");}function dS(e){let a=new Set,o=[];for(let t of e){let r=en[t];if(r)for(let i of r)a.has(i.path)||(a.add(i.path),o.push(i));}return o}function cS(e){return e.endsWith(".en.md")||e.endsWith(".es.md")?e.slice(0,-6)+".md":e}function lS(e){return e.endsWith(".en.md")?"en":e.endsWith(".es.md")?"es":"pt"}function uS(e,a){if(a==="all")return e;let o=new Map,t=[];for(let i of e){if(!i.path.endsWith(".md")){t.push(i);continue}let s=cS(i.path),n=lS(i.path),d=o.get(s);d||(d=new Map,o.set(s,d)),d.set(n,i);}let r=[];for(let[i,s]of o){let n=s.get(a)??s.get("pt")??s.get("en")??s.get("es");r.push({...n,path:i});}return [...t,...r]}async function Rf(e){let a=e.targetDir??process.cwd(),o=e.dryRun??false,t=e.force??false,r=e.isInteractive??!!process.stdin.isTTY,i=e.confirmOverwrite??kc,s=join(a,Ks),n=$s(s),d=e.docsLang??"all",l=e.installedBundles.length===0,c=l?[]:dS(e.installedBundles),u=uS([...wf,...c],d),m=[],p=vc(),h={};for(let g of u){let v=join(a,g.path),k=await yc({dstPath:v,template:g,existingLockHash:Ys(n,g.path),force:t,isInteractive:r,confirmOverwrite:T=>i(T)});m.push({path:g.path,status:k.status}),p[k.status]++,k.write&&!o&&(mkdirSync(dirname(v),{recursive:true}),writeFileSync(v,g.content,"utf8")),k.recordHash&&!o&&(h[g.path]=k.recordHash);}!o&&Object.keys(h).length>0&&Sf(s,n,h,Df);let f=p.divergent>0||p.declined>0;return {files:m,counts:p,hasUnresolved:f,skippedPlaybooks:l}}function Af(){let e=Ce().plugins,a=process.cwd(),o=new Set(Object.keys(en)),t=new Set;for(let[r,i]of Object.entries(e)){let s=r.split("@")[0];if(!s||!o.has(s))continue;i.some(d=>d.scope==="user"||d.projectPath===a)&&t.add(s);}return [...t].sort()}j();I();Se();Ho();I();var Pc=P("lib:otelMetrics"),mS="flow-plugins-cli",gS="1.0.0",fS=5e3;function hS(){return Ta("FLOW_OTEL_ENDPOINT_URL","https://flow.ciandt.com/otel")}function bS(e,a){return typeof a=="number"?{key:e,value:{intValue:String(a)}}:typeof a=="boolean"?{key:e,value:{boolValue:a}}:{key:e,value:{stringValue:a}}}function vS(e,a){let o=String(Date.now()*1e6);return {resourceMetrics:[{resource:{attributes:[]},scopeMetrics:[{scope:{name:mS,version:gS},metrics:[{name:e,sum:{dataPoints:[{asInt:"1",startTimeUnixNano:o,timeUnixNano:o,attributes:Object.entries(a).map(([t,r])=>bS(t,r))}],aggregationTemporality:1,isMonotonic:true}}]}]}]}}async function Dc(e,a={}){try{let[o,t]=await Promise.all([Dt(),Y()]),r=o?.email,i=t?.tenant;if(!r||!i){Pc.debug(`Skipping OTel metric "${e}": no cached identity available`);return}let s=vS(e,a);await Au.post(hS(),{json:s,timeout:fS,headers:{"Content-Type":"application/json","x-flow-user":r,flowtenant:i}}),Pc.debug(`OTel metric sent: ${e}`);}catch(o){Pc.warn(`Failed to send OTel metric "${e}": ${String(o)}`);}}var wc=P("cli:init"),PS={new:{label:"new",color:R.green},unchanged:{label:"unchanged",color:R.dim},clean:{label:"updated",color:R.cyan},divergent:{label:"kept (customized)",color:R.yellow},declined:{label:"pending (declined)",color:R.yellow}};function DS(e){process.stdout.write(`
|
|
84781
84781
|
`+R.bold(` flow setup strategy
|
|
84782
84782
|
`)),process.stdout.write(R.dim(` Target: ${e}
|
|
84783
84783
|
|
|
84784
84784
|
`)),process.stdout.write(R.dim(` Files evaluated:
|
|
84785
84785
|
`));for(let a of Zr)process.stdout.write(R.dim(` \xB7 ${a.path}
|
|
84786
84786
|
`));process.stdout.write(`
|
|
84787
|
-
`);}function
|
|
84787
|
+
`);}function wS(e,a,o,t){S(w.CLI_STRATEGY_INIT_COMPLETED,{files_new:e.new,files_unchanged:e.unchanged,files_updated:e.clean,files_divergent:e.divergent,files_declined:e.declined,dry_run:a,duration_ms:t,exit_code:o}).catch(r=>{wc.warn(`Failed to emit strategy init completed event: ${String(r)}`);}),Dc("flow_cli.strategy_init",{dry_run:a,files_new:e.new,files_updated:e.clean,exit_code:o}).catch(()=>{});}function xf(e,a){S(w.CLI_STRATEGY_INIT_FAILED,{error_message:e.slice(0,500),duration_ms:a}).catch(o=>{wc.warn(`Failed to emit strategy init failed event: ${String(o)}`);}),Dc("flow_cli.strategy_init_failed",{duration_ms:a}).catch(()=>{});}async function SS(e){try{return await simpleGit(e).checkIsRepo(CheckRepoActions.IN_TREE)}catch{return false}}async function CS(){return de(" Continue anyway? [y/N] ")}async function RS(){return D(`docs/catalog/ is the skill/agent/command catalog (~2.6MB); docs/playbooks/ is the
|
|
84788
84788
|
runbook + sub-runbook docs for your installed bundles, in every language they ship
|
|
84789
84789
|
in (.md/.en.md/.es.md). This is the same content flow-playbooks-app renders \u2014 skip
|
|
84790
|
-
it if you don't run that app.`),de(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function
|
|
84791
|
-
`));for(let k of i.files){let{label:T,color:L}=
|
|
84790
|
+
it if you don't run that app.`),de(" Also scaffold docs/catalog and docs/playbooks content? [y/N] ")}async function AS(){return ts(" Which language?",[{value:"all",label:"All variants",description:"every .md/.en.md/.es.md kept as-is"},{value:"pt",label:"pt (default)",description:"the base, unsuffixed .md files only"},{value:"en",label:"en",description:".en.md only"},{value:"es",label:"es",description:".es.md only"}])}async function Ef(e){wc.debug(`Running flow setup strategy: ${JSON.stringify(e)}`);let a=e.path??process.cwd(),o=e.isInteractive??!!process.stdin.isTTY,t=e.confirmContinueWithoutGit??CS;if(!await SS(a)){let k=`${a} is not a git repository. Strategy docs are meant to be version-controlled \u2014 consider running "git init" first.`;if(!o)return e.json?Fe({error:k,exitCode:1}):C(`${k} Re-run interactively to confirm, or run "git init" first.`),1;if(D(k),!await t())return 1}e.json||DS(a);let r=Date.now(),i;try{i=await Pf({targetDir:a,dryRun:e.dryRun,force:e.force,assistant:e.assistant});}catch(k){throw xf(k instanceof Error?k.message:String(k),Date.now()-r),k}let s,n=e.confirmDocsContent??RS,d=e.selectDocsLang??AS,l=!!e.docsContent,c=e.docsLang??"all";if(!l&&o&&(l=await n(),l&&(c=await d())),l){let k=Af();try{s=await Rf({targetDir:a,dryRun:e.dryRun,force:e.force,installedBundles:k,docsLang:c});}catch(T){throw xf(T instanceof Error?T.message:String(T),Date.now()-r),T}}let u=i.hasUnresolved||s?.hasUnresolved?2:0;if(wS(i.counts,!!e.dryRun,u,Date.now()-r),e.json)return ye({dryRun:!!e.dryRun,counts:i.counts,files:i.files,docsContent:s?{counts:s.counts,files:s.files,skippedPlaybooks:s.skippedPlaybooks}:void 0,exitCode:u}),u;let m=e.dryRun?R.dim("[dry-run] "):"";process.stdout.write(R.bold(` Result:
|
|
84791
|
+
`));for(let k of i.files){let{label:T,color:L}=PS[k.status];process.stdout.write(` ${m}${L(T.padEnd(18))} ${k.path}
|
|
84792
84792
|
`);}process.stdout.write(`
|
|
84793
84793
|
`);let{new:p,unchanged:h,clean:f,divergent:g,declined:v}=i.counts;if(K(`${p} new, ${h} unchanged, ${f} updated, ${g} kept (customized)`+(v>0?`, ${v} pending confirmation`:"")),g>0&&D("Some files were kept as-is because they differ from what this command last wrote. Re-run with --force to overwrite them."),v>0&&D("Some updates were declined or skipped (no TTY). Re-run with --force to apply them."),s){process.stdout.write(`
|
|
84794
84794
|
`+R.bold(` docs/catalog + docs/playbooks:
|
|
84795
|
-
`)),s.skippedPlaybooks&&D('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let k=s.counts;K(`${k.new} new, ${k.unchanged} unchanged, ${k.clean} updated, ${k.divergent} kept (customized)`+(k.declined>0?`, ${k.declined} pending confirmation`:"")),(k.divergent>0||k.declined>0)&&D("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return u!==0&&C("flow setup strategy finished with unresolved files \u2014 see above."),u}j();U();var rr=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Cc="repos.yaml",
|
|
84795
|
+
`)),s.skippedPlaybooks&&D('No bundles installed (run "flow setup harness" first) \u2014 docs/playbooks/ was skipped; docs/catalog/ was still scaffolded.');let k=s.counts;K(`${k.new} new, ${k.unchanged} unchanged, ${k.clean} updated, ${k.divergent} kept (customized)`+(k.declined>0?`, ${k.declined} pending confirmation`:"")),(k.divergent>0||k.declined>0)&&D("Some docs-content files were kept as-is or pending confirmation. Re-run with --force to resolve.");}return u!==0&&C("flow setup strategy finished with unresolved files \u2014 see above."),u}j();U();var rr=["runbook-common","runbook-design","runbook-ops","runbook-product","runbook-quality","runbook-security","runbook-tech"];var Cc="repos.yaml",TS="projects",MS="projects-ref";function If(e){return Array.isArray(e)?e.filter(a=>typeof a=="object"&&a!==null).map(a=>({name:String(a.name??""),remote:String(a.remote??""),group:a.group!==void 0?String(a.group):void 0})).filter(a=>a.name&&a.remote):[]}function Lf(e){let a=join(e,Cc);if(!existsSync(a))return null;let o=parse(readFileSync(a,"utf8"));if(!o||typeof o!="object"||Array.isArray(o))return null;let t=o.workspace??{};return {workspace:{repos_dir:String(t.repos_dir??TS),refs_dir:String(t.refs_dir??MS)},repos:If(o.repos),references:If(o.references)}}function Ff(e,a){let o=join(e,Cc);writeFileSync(o,stringify(a),"utf8");}function Of(e){let a=join(e,".gitignore"),o=Cc;if(!existsSync(a)){writeFileSync(a,`${o}
|
|
84796
84796
|
`,"utf8");return}readFileSync(a,"utf8").split(`
|
|
84797
84797
|
`).some(i=>i.trim()===o)||appendFileSync(a,`${o}
|
|
84798
|
-
`,"utf8");}var Nf="projects",Gf="projects-ref";function
|
|
84799
|
-
`);}function
|
|
84800
|
-
`),130;throw r}let t=[];for(let r=0;r<rr.length;r++){let i=rr[r],s=`[${r+1}/${rr.length}] `,n=e.force??false;if(!n){let d=
|
|
84801
|
-
`),130;throw l}}}e.silent||D(`${s}Installing ${i}...`),t.push(await or([i],{scope:o,silent:e.silent,force:n}));}return t.some(r=>r!==0)?1:0}var
|
|
84802
|
-
`)
|
|
84798
|
+
`,"utf8");}var Nf="projects",Gf="projects-ref";function qS(e){let a=e.match(/^https?:\/\/github\.com\/([^/]+)\/([^/.]+)(\.git)?\/?$/);return a?`git@github.com:${a[1]}/${a[2]}.git`:e}async function LS(){let e=await To(" Repo name (ENTER to finish): ");if(!e)return null;let a=await To(` Group/category for '${e}' (optional, default: general): `),o=await To(` Remote (URL) for '${e}' \u2014 SSH or HTTPS: `);if(!o)return null;let t=qS(o),r=await de(` Is '${e}' a reference/read-only repo? [y/N] `);return {entry:{name:e,remote:t,group:a||"general"},isReference:r}}async function Bf(){if(!await de("repos.yaml not found. Set up this repo as a multi-repo workspace? [y/N] "))return null;let a=await To(` Folder for work repos (default: ${Nf}): `),o=await To(` Folder for reference repos (default: ${Gf}): `),t=[],r=[];for(;;){let i=await LS();if(!i)break;i.isReference?r.push(i.entry):t.push(i.entry);}return t.length===0&&r.length===0?null:{workspace:{repos_dir:a||Nf,refs_dir:o||Gf},repos:t,references:r}}I();var Uf=P("workspace:repos"),Wf=6e4;async function NS(e){try{return (await simpleGit(e).status()).current}catch{return null}}function Jf(){let{HOME:e,PATH:a,USER:o,SSH_AUTH_SOCK:t}=process.env;return {HOME:e,PATH:a,USER:o,SSH_AUTH_SOCK:t,GIT_TERMINAL_PROMPT:"0"}}async function GS(e){await simpleGit(e,{timeout:{block:Wf}}).env(Jf()).pull(["--ff-only"]);}async function BS(e,a){await simpleGit({timeout:{block:Wf}}).env(Jf()).clone(e,a);}async function Ac(e,a,o){let t=join(a,e.name),r=join(t,".git");if(existsSync(r)){let i=await NS(t);if(i==="main"||i==="master")try{return await GS(t),{name:e.name,kind:o,outcome:"updated"}}catch(s){return Uf.warn(`[${e.name}] pull failed (branch diverged?): ${String(s)}`),{name:e.name,kind:o,outcome:"skipped"}}return {name:e.name,kind:o,outcome:"skipped"}}try{return mkdirSync(a,{recursive:!0}),await BS(e.remote,t),{name:e.name,kind:o,outcome:"cloned"}}catch(i){let s=i instanceof Error?i.message:String(i);return Uf.error(`[${e.name}] clone failed: ${s}`),{name:e.name,kind:o,outcome:"failed",error:s}}}function an(e,a){return existsSync(e)?readdirSync(e,{withFileTypes:true}).filter(o=>o.isDirectory()&&!a.has(o.name)).map(o=>o.name):[]}async function Hf(e={}){let a=e.targetDir??process.cwd(),o=e.isInteractive??!!process.stdin.isTTY,t=Lf(a);if(!t){if(!o)return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true};let u=await Bf();if(!u)return {repos:[],orphans:[],prunedCount:0,skippedNoManifest:true};Ff(a,u),Of(a),t=u;}let r=join(a,t.workspace.repos_dir),i=join(a,t.workspace.refs_dir),s=[];for(let u of t.repos)s.push(await Ac(u,r,"repo"));for(let u of t.references)s.push(await Ac(u,i,"reference"));let n=new Set(t.repos.map(u=>u.name)),d=new Set(t.references.map(u=>u.name)),l=[...an(r,n),...an(i,d)],c=0;if(e.prune&&l.length>0)for(let u of [r,i]){let m=an(u,u===r?n:d);for(let p of m)rmSync(join(u,p),{recursive:true,force:true}),c++;}return {repos:s,orphans:e.prune?[]:l,prunedCount:c,skippedNoManifest:false}}var WS=promisify(execFile),Qf=5e3;async function Vf(){try{let{stdout:e,stderr:a}=await WS("ssh",["-T","git@github.com","-o","BatchMode=yes","-o",`ConnectTimeout=${Qf/1e3}`],{timeout:Qf+2e3});return `${e}${a}`.includes("successfully authenticated")}catch(e){return `${e.stdout??""}${e.stderr??""}`.includes("successfully authenticated")}}I();var JS=["local","project","user"];function HS(){D(`The following ${rr.length} runbook bundles will be installed:`);for(let e of rr)process.stdout.write(` - ${e}
|
|
84799
|
+
`);}function QS(e){let a=Ce().plugins,o=process.cwd();for(let[t,r]of Object.entries(a))if(t===e||t.startsWith(`${e}@`)){let i=r.find(s=>s.scope==="user"||s.projectPath===o);if(i)return i}}function on(e){return e.scope==="user"?"globally (~/.claude/)":`at ${e.scope} scope in ${e.projectPath??"(unknown project)"}`}async function VS(e,a,o){return D(`${e} is already installed ${on(o)}.`),de(` Move it to ${Va[a].actionLabel} instead? This uninstalls it from ${on(o)} first. [y/N] `)}async function _S(){return ts(" Install scope:",JS.map(e=>({value:e,label:Va[e].actionLabel,description:Va[e].description})))}async function _f(e={}){let a=e.isInteractive??!!process.stdin.isTTY;e.silent||HS();let o=e.scope;if(!o&&!e.silent&&a)try{o=await _S();}catch(r){if(r instanceof Error&&r.message==="SIGINT")return process.stdout.write(`
|
|
84800
|
+
`),130;throw r}let t=[];for(let r=0;r<rr.length;r++){let i=rr[r],s=`[${r+1}/${rr.length}] `,n=e.force??false;if(!n){let d=QS(i);if(d){if(e.silent||!a){e.silent||D(`${s}Skipping ${i} \u2014 already installed ${on(d)}. Re-run with --force to install here too.`);continue}try{if(!await VS(i,o,d)){D(`${s}Skipped ${i}.`);continue}let c=await Us(i,{force:!0,scope:d.scope});if(c!==0){D(`${s}Could not remove ${i} from ${on(d)} \u2014 skipping rather than leaving it in an inconsistent state.`),t.push(c);continue}}catch(l){if(l instanceof Error&&l.message==="SIGINT")return process.stdout.write(`
|
|
84801
|
+
`),130;throw l}}}e.silent||D(`${s}Installing ${i}...`),t.push(await or([i],{scope:o,silent:e.silent,force:n}));}return t.some(r=>r!==0)?1:0}var XS=P("cli:setup-workspace");function KS(e){switch(e){case "cloned":return "cloned";case "updated":return "updated";case "skipped":return "skipped (diverged or another branch)";case "failed":return "failed"}}async function $S(e){e||await Vf()||(D("SSH key not configured for GitHub (or not added to your account)."),process.stdout.write(` This may cause repo clones below to fail. To set one up:
|
|
84802
|
+
`),process.stdout.write(` 1. Check for an existing key: ls -la ~/.ssh/id_ed25519.pub
|
|
84803
|
+
`),process.stdout.write(` 2. If none, generate one: ssh-keygen -t ed25519 -C "your_email@example.com"
|
|
84804
|
+
`),process.stdout.write(` 3. Start the agent: eval "$(ssh-agent -s)"
|
|
84805
|
+
`),process.stdout.write(` 4. Add the key to the agent: ssh-add ~/.ssh/id_ed25519
|
|
84806
|
+
`),process.stdout.write(` 5. Copy the public key: pbcopy < ~/.ssh/id_ed25519.pub (macOS)
|
|
84807
|
+
`),process.stdout.write(` 6. Add it on GitHub: https://github.com/settings/ssh/new
|
|
84808
|
+
`),process.stdout.write(` 7. Test the connection: ssh -T git@github.com
|
|
84809
|
+
`));}async function Xf(e={}){XS.debug(`Running flow setup workspace: ${JSON.stringify(e)}`),await $S(e.json);let a=await Hf({targetDir:e.path,prune:e.prune});if(e.json)return ye({repos:a.repos,orphans:a.orphans,prunedCount:a.prunedCount,skippedNoManifest:a.skippedNoManifest}),a.repos.some(s=>s.outcome==="failed")?1:0;if(a.skippedNoManifest)return D("No repos.yaml and no interactive terminal \u2014 nothing to do."),0;for(let s of a.repos)process.stdout.write(` ${s.name}: ${KS(s.outcome)}
|
|
84810
|
+
`);let o=a.repos.filter(s=>s.outcome==="cloned").length,t=a.repos.filter(s=>s.outcome==="updated").length,r=a.repos.filter(s=>s.outcome==="skipped").length,i=a.repos.filter(s=>s.outcome==="failed").length;return K(`${o} cloned, ${t} updated, ${r} skipped`+(i>0?`, ${i} failed`:"")+(a.prunedCount>0?`, ${a.prunedCount} pruned`:"")),a.orphans.length>0&&D(`Orphan director${a.orphans.length===1?"y":"ies"} not in repos.yaml: ${a.orphans.join(", ")}. Re-run with --prune to remove.`),i>0?1:0}function Kf(e){let a=new Command;a.enablePositionalOptions(),a.name("flow").description("FlowSetup CLI \u2014 Manage Flow plugins in your Claude Code").version(`@ciandt-flow/cli v${te}`,"-V, --version","Display the CLI version").addHelpText("after",`
|
|
84803
84811
|
Without arguments, opens the interactive interface (TUI).
|
|
84804
84812
|
Use 'flow <command> --help' for details on each command.`).action(async()=>{await e();});let o=new Command("setup").description("Configure the CLI and provision Flow structure in the current repository");o.command("init").description("Initialize the Flow CLI configuration").addHelpText("after",`
|
|
84805
84813
|
Examples:
|
|
@@ -84821,11 +84829,11 @@ Without --scope and with an interactive terminal, prompts once for the scope
|
|
|
84821
84829
|
(local/project/user) before installing all 7 bundles. A bundle already
|
|
84822
84830
|
installed elsewhere (any scope, any project) prompts to move it here instead
|
|
84823
84831
|
(uninstall there, install here) unless --force is passed, which installs
|
|
84824
|
-
here too without asking, leaving the bundle enabled in both places.`).action(async c=>{let u=await
|
|
84832
|
+
here too without asking, leaving the bundle enabled in both places.`).action(async c=>{let u=await _f({scope:c.scope,silent:c.silent,force:c.force});G(u);}),o.command("workspace").description("Clone / update repos declared in repos.yaml (wizard on first run)").option("--path <dir>","Target repository root (defaults to the current directory)").option("--prune","Remove local directories no longer declared in repos.yaml",false).option("--json","Output machine-readable JSON",false).addHelpText("after",`
|
|
84825
84833
|
Examples:
|
|
84826
84834
|
$ flow setup workspace
|
|
84827
84835
|
$ flow setup workspace --prune
|
|
84828
|
-
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let u=await
|
|
84836
|
+
$ flow setup workspace --json --path ./my-workspace`).action(async c=>{let u=await Xf({path:c.path,prune:c.prune,json:c.json});G(u);}),a.addCommand(o);let t=new Command("plugin").description("Manage plugins from the Findr catalog installed in your Claude Code");t.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",`
|
|
84829
84837
|
Examples:
|
|
84830
84838
|
$ flow plugin list
|
|
84831
84839
|
$ flow plugin list --available
|
|
@@ -84924,8 +84932,8 @@ Examples:
|
|
|
84924
84932
|
$ flow modules install dashboard`).action(async c=>{let u=await hf(c);G(u);}),l.command("update").description("Update an installed module, or all installed modules").argument("[alias]","Module alias to update (omit to update all installed)").addHelpText("after",`
|
|
84925
84933
|
Examples:
|
|
84926
84934
|
$ flow modules update
|
|
84927
|
-
$ flow modules update metrics`).action(async c=>{let u=await bf(c??null);G(u);}),a.addCommand(l);for(let c of se)a.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await mf(c.alias,u);});return a.hook("preAction",()=>{Ts();}),a}I();function
|
|
84935
|
+
$ flow modules update metrics`).action(async c=>{let u=await bf(c??null);G(u);}),a.addCommand(l);for(let c of se)a.command(c.alias).description(c.description).helpOption(false).allowUnknownOption().passThroughOptions().argument("[passthrough...]","Arguments forwarded to the module binary").action(async u=>{await mf(c.alias,u);});return a.hook("preAction",()=>{Ts();}),a}I();function eC(){return De__default.join(Le__default.homedir(),".claude","settings.json")}function Yf(){let e=eC();try{if(!we__default.existsSync(e))return !0;let o=JSON.parse(we__default.readFileSync(e,"utf-8")).flowCli?.autoUpdate;return o===!1?!1:o==="modules-only"?"modules-only":!0}catch{return true}}I();var sC=P("updateChecker"),nC=promisify(execFile),dC=1440*60*1e3,Zf=3e4;function cC(){let e=process.env.FLOW_HOME??De__default.join(Le__default.homedir(),".flow");return De__default.join(e,"update.lock")}async function eh(e){try{let{stdout:a}=await nC(Ka(),["view",e,"version"],{timeout:Zf,shell:process.platform==="win32"});return String(a).trim()||null}catch{return null}}async function lC(e){let a=new AbortController,o=setTimeout(()=>a.abort(),Zf);try{let t=await fetch(`https://api.github.com/repos/${e}/releases/latest`,{signal:a.signal});return t.ok?(await t.json()).tag_name?.replace(/^v/,"")??null:null}catch{return null}finally{clearTimeout(o);}}async function uC(e){return e.versionCheck.type==="npm-registry"?eh(e.versionCheck.package):lC(e.versionCheck.repo)}async function pC(){let e=await eh("@ciandt-flow/cli");return e&&Ue(te,e)?(Ns({currentVersion:te,latestVersion:e,isOutdated:true,packageName:"@ciandt-flow/cli"}).catch(()=>{}),e):null}async function mC(){let e=Zo().filter(a=>a.installMethod!==null);await Promise.all(e.map(async a=>{let o=se.find(s=>s.alias===a.alias);if(!o||o.hasOwnUpdateCheck)return;let t=Date.now(),r=a.lastChecked?new Date(a.lastChecked).getTime():0;if(t-r<dC)return;let i=await uC(o);try{await ya({...a,lastChecked:new Date().toISOString()});}catch(s){sC.warn(`Failed to update lastChecked for ${a.alias}: ${String(s)}`);}i&&a.installedVersion&&Ue(a.installedVersion,i)&&Gi(o,"background").catch(()=>{});}));}async function Ic(){let e=Yf();if(e===false)return;let a=cC();we__default.mkdirSync(De__default.dirname(a),{recursive:true});let o=null;try{o=await Ab.lock(a,{realpath:!1,retries:0});}catch{return}try{if(e!=="modules-only"){let t=await pC().catch(()=>null);t&&process.stdout.write(`
|
|
84928
84936
|
\u26A0 @ciandt-flow/cli v${t} installing in background.
|
|
84929
84937
|
Restart flow to apply the update.
|
|
84930
84938
|
|
|
84931
|
-
`);}await
|
|
84939
|
+
`);}await mC().catch(()=>{});}finally{await o().catch(()=>{});}}var fC=P("cli"),Tc=Kf(async()=>{Qe("tui"),pl("tui"),ml(),process.on("SIGINT",()=>{let{activeTab:a,screen:o}=y.getState();pr("sigint",a,o).finally(()=>process.exit(130));}),process.on("SIGTERM",()=>{let{activeTab:a,screen:o}=y.getState();pr("sigterm",a,o).finally(()=>process.exit(143));}),await Ic().catch(()=>{}),await Tu().catch(a=>{fC.error(`Failed to init catalog registry: ${String(a)}`);}),await dg();let{waitUntilExit:e}=render(jsx(cg,{}),{alternateScreen:true,exitOnCtrlC:false});await e(),process.exit(0);});Tc.hook("preAction",async(e,a)=>{a!==Tc&&await Ic().catch(()=>{});});Tc.parse();
|